Пример #1
0
    def testNormal(self):
        change_info = gcl.ChangeInfo('naame', 0, 0, 'deescription',
                                     [('A', 'aa'),
                                      ('M', 'bb')], self.fake_root_dir)
        self.mox.StubOutWithMock(change_info, 'Save')
        args = ['--no_watchlists']
        change_info.Save()
        gcl.DoPresubmitChecks(change_info, False, True).AndReturn(True)
        gcl.GetCodeReviewSetting('CODE_REVIEW_SERVER').AndReturn('my_server')
        gcl.tempfile.mkstemp(text=True).AndReturn((42, 'descfile'))
        gcl.os.write(42, change_info.description)
        gcl.os.close(42)
        gcl.GetCodeReviewSetting('CC_LIST')
        gcl.os.getcwd().AndReturn('somewhere')
        gcl.os.chdir(change_info.GetLocalRoot())
        gcl.GenerateDiff(change_info.GetFileNames())
        gcl.upload.RealMain([
            'upload.py', '-y', '--server=my_server',
            "--description_file=descfile", "--message=deescription"
        ], change_info.patch).AndReturn(("1", "2"))
        gcl.os.remove('descfile')
        gcl.SendToRietveld("/lint/issue%s_%s" % ('1', '2'), timeout=0.5)
        gcl.GetCodeReviewSetting('TRY_ON_UPLOAD').AndReturn('True')
        gcl.TryChange(change_info, [], swallow_exception=True)
        gcl.os.chdir('somewhere')
        self.mox.ReplayAll()

        gcl.UploadCL(change_info, args)
        self.assertEquals(change_info.issue, 1)
        self.assertEquals(change_info.patchset, 2)
Пример #2
0
    def testNew(self):
        change_info = self.mox.CreateMock(gcl.ChangeInfo)
        change_info.name = 'naame'
        change_info.issue = 1
        change_info.patchset = 0
        change_info.description = 'deescription',
        change_info.files = [('A', 'aa'), ('M', 'bb')]
        change_info.patch = None
        files = [item[1] for item in change_info.files]
        args = ['--foo=bar']
        gcl.DoPresubmitChecks(change_info, False, True).AndReturn(True)
        gcl.GetCodeReviewSetting('CODE_REVIEW_SERVER').AndReturn('my_server')
        gcl.os.getcwd().AndReturn('somewhere')
        change_info.GetFiles().AndReturn(change_info.files)
        change_info.GetLocalRoot().AndReturn('proout')
        gcl.os.chdir('proout')
        change_info.GetFileNames().AndReturn(files)
        gcl.GenerateDiff(files)
        gcl.upload.RealMain([
            'upload.py', '-y', '--server=my_server', '--foo=bar',
            "--message=''", '--issue=1'
        ], change_info.patch).AndReturn(("1", "2"))
        gcl.SendToRietveld("/lint/issue%s_%s" % ('1', '2'), timeout=0.5)
        gcl.GetCodeReviewSetting('TRY_ON_UPLOAD').AndReturn('True')
        gcl.TryChange(change_info, [], swallow_exception=True)
        gcl.os.chdir('somewhere')
        change_info.Save()
        self.mox.ReplayAll()

        gcl.UploadCL(change_info, args)
Пример #3
0
def do_cpp_lint(changeset, repo, args):
    # Try to import cpplint from depot_tools first
    try:
        import cpplint
    except ImportError:
        TryAddDepotToolsToPythonPath()

    try:
        import cpplint
        import cpplint_chromium
        import gcl
    except ImportError:
        sys.stderr.write("Can't find cpplint, please add your depot_tools "\
                         "to PATH or PYTHONPATH\n")
        raise
    print '_____ do cpp lint'
    if len(changeset) == 0:
        print 'changeset is empty except python files'
        return
    # pass the build/header_guard check
    if repo == 'cameo':
        os.rename('.git', '.git.rename')
    # Following code is referencing depot_tools/gcl.py: CMDlint
    try:
        # Process cpplints arguments if any.
        filenames = cpplint.ParseArguments(args + changeset)

        white_list = gcl.GetCodeReviewSetting("LINT_REGEX")
        if not white_list:
            white_list = gcl.DEFAULT_LINT_REGEX
        white_regex = re.compile(white_list)
        black_list = gcl.GetCodeReviewSetting("LINT_IGNORE_REGEX")
        if not black_list:
            black_list = gcl.DEFAULT_LINT_IGNORE_REGEX
        black_regex = re.compile(black_list)
        extra_check_functions = [
            cpplint_chromium.CheckPointerDeclarationWhitespace
        ]
        # pylint: disable=W0212
        cpplint_state = cpplint._cpplint_state
        for filename in filenames:
            if white_regex.match(filename):
                if black_regex.match(filename):
                    print "Ignoring file %s" % filename
                else:
                    cpplint.ProcessFile(filename, cpplint_state.verbose_level,
                                        extra_check_functions)
            else:
                print "Skipping file %s" % filename
        print "Total errors found: %d\n" % cpplint_state.error_count
    finally:
        if repo == 'cameo':
            os.rename('.git.rename', '.git')
Пример #4
0
 def testGetCodeReviewSettingOk(self):
   self.mox.StubOutWithMock(gcl, 'GetCachedFile')
   gcl.GetCachedFile(gcl.CODEREVIEW_SETTINGS_FILE).AndReturn(
       'foo:bar\n'
       '# comment\n'
       ' c : d \n\r'
       'e: f')
   self.mox.ReplayAll()
   self.assertEquals('bar', gcl.GetCodeReviewSetting('foo'))
   self.assertEquals('d', gcl.GetCodeReviewSetting('c'))
   self.assertEquals('f', gcl.GetCodeReviewSetting('e'))
   self.assertEquals('', gcl.GetCodeReviewSetting('other'))
   self.assertEquals(
       {'foo': 'bar', 'c': 'd', 'e': 'f', '__just_initialized': None},
       gcl.CODEREVIEW_SETTINGS)
Пример #5
0
  def testNormal(self):
    change_info = gcl.ChangeInfo(
        'naame',
        0,
        0,
        'deescription',
        [('A', 'aa'), ('M', 'bb')],
        self.fake_root_dir,
        'my_server',
        False)
    self.mox.StubOutWithMock(change_info, 'Save')
    change_info.Save()
    output = presubmit_support.PresubmitOutput()
    gcl.DoPresubmitChecks(change_info, False, True).AndReturn(output)
    gcl.tempfile.mkstemp(text=True).AndReturn((42, 'descfile'))
    gcl.os.write(42, change_info.description)
    gcl.os.close(42)
    gcl.GetCodeReviewSetting('CC_LIST')
    gcl.GetCodeReviewSetting('PRIVATE')
    gcl.GetCodeReviewSetting('PROJECT')
    gcl.os.getcwd().AndReturn('somewhere')
    gcl.os.chdir(change_info.GetLocalRoot())
    gcl.GenerateDiff(change_info.GetFileNames())
    gcl.upload.RealMain(
        ['upload.py', '-y', '--server=https://my_server', "--file=descfile" ],
        change_info.patch).AndReturn(("1", "2"))
    gcl.os.remove('descfile')
    change_info.SendToRietveld("/lint/issue%s_%s" % ('1', '2'), timeout=60)
    gcl.os.chdir('somewhere')
    gcl.sys.stdout.write("*** Upload does not submit a try; use gcl try to"
                         " submit a try. ***")
    gcl.sys.stdout.write("\n")
    gcl.GetRepositoryRoot().AndReturn(self.fake_root_dir)
    gcl.ChangeInfo.Load('naame', self.fake_root_dir, True, True
        ).AndReturn(change_info)
    self.mox.ReplayAll()

    gcl.CMDupload(['naame', '--no_watchlists'])
    self.assertEquals(change_info.issue, 1)
    self.assertEquals(change_info.patchset, 2)
    self.checkstdout('*** Upload does not submit a try; use gcl try to submit '
        'a try. ***\n'
        '*** Upload does not submit a try; use gcl try to submit a try. ***\n')
Пример #6
0
 def testGetCodeReviewSettingFail(self):
     self.mox.StubOutWithMock(gcl, 'GetCachedFile')
     gcl.GetCachedFile(gcl.CODEREVIEW_SETTINGS_FILE).AndReturn('aaa\n'
                                                               ' c : d \n\r'
                                                               'e: f')
     self.mox.ReplayAll()
     try:
         gcl.GetCodeReviewSetting('c')
         self.fail()
     except gcl.gclient_utils.Error:
         pass
     self.assertEquals({}, gcl.CODEREVIEW_SETTINGS)
Пример #7
0
def GetTryServerSettings():
    """Grab try server settings local to the repository."""
    def _SafeResolve(host):
        try:
            return socket.getaddrinfo(host, None)
        except socket.gaierror:
            return None

    settings = {}
    settings['http_port'] = gcl.GetCodeReviewSetting('TRYSERVER_HTTP_PORT')
    settings['http_host'] = gcl.GetCodeReviewSetting('TRYSERVER_HTTP_HOST')
    settings['svn_repo'] = gcl.GetCodeReviewSetting('TRYSERVER_SVN_URL')
    settings['default_project'] = gcl.GetCodeReviewSetting('TRYSERVER_PROJECT')
    settings['default_root'] = gcl.GetCodeReviewSetting('TRYSERVER_ROOT')

    # Pick a patchlevel, default to 0.
    default_patchlevel = gcl.GetCodeReviewSetting('TRYSERVER_PATCHLEVEL')
    if default_patchlevel:
        default_patchlevel = int(default_patchlevel)
    else:
        default_patchlevel = 0
    settings['default_patchlevel'] = default_patchlevel

    # Use http is the http_host name resolve, fallback to svn otherwise.
    if (settings['http_port'] and settings['http_host']
            and _SafeResolve(settings['http_host'])):
        settings['default_transport'] = 'http'
    elif settings.get('svn_repo'):
        settings['default_transport'] = 'svn'
    return settings
Пример #8
0
    def mockCommit(self, change_info, commit_message, shell_output):
        gcl.tempfile.mkstemp(text=True).AndReturn((42, 'commit'))
        gcl.os.write(42, commit_message)
        gcl.os.close(42)
        gcl.tempfile.mkstemp(text=True).AndReturn((43, 'files'))
        gcl.os.write(43, '\n'.join(change_info.GetFileNames()))
        gcl.os.close(43)

        gcl.RunShell(['svn', 'commit', '--file=commit', '--targets=files'],
                     True).AndReturn(shell_output)
        if 'Committed' in shell_output:
            self.mox.StubOutWithMock(gcl, 'GetCodeReviewSetting')
            gcl.GetCodeReviewSetting('VIEW_VC').AndReturn('http://view/')

        gcl.os.remove('commit')
        gcl.os.remove('files')
Пример #9
0
  def testLoadEmpty(self):
    self.mox.StubOutWithMock(gcl, 'GetCodeReviewSetting')
    gcl.GetChangelistInfoFile('bleh').AndReturn('bleeeh')
    gcl.os.path.exists('bleeeh').AndReturn(True)
    gcl.gclient_utils.FileRead('bleeeh').AndReturn(
        gcl.ChangeInfo.SEPARATOR.join(["", "", ""]))
    gcl.GetCodeReviewSetting('CODE_REVIEW_SERVER').AndReturn('foo')
    # Does an upgrade.
    gcl.GetChangelistInfoFile('bleh').AndReturn('bleeeh')
    gcl.gclient_utils.FileWrite('bleeeh', mox.IgnoreArg())
    self.mox.ReplayAll()

    change_info = gcl.ChangeInfo.Load('bleh', self.fake_root_dir, True, False)
    self.assertEquals(change_info.name, 'bleh')
    self.assertEquals(change_info.issue, 0)
    self.assertEquals(change_info.patchset, 0)
    self.assertEquals(change_info.description, "")
    self.assertEquals(change_info.GetFiles(), [])
Пример #10
0
    def GetCodeReviewSetting(self, key):
        """Returns a value for the given key for this repository.

    Uses gcl-style settings from the repository.
    """
        if gcl:
            gcl_setting = gcl.GetCodeReviewSetting(key)
            if gcl_setting != '':
                return gcl_setting
        if self.codereview_settings is None:
            self.codereview_settings = {}
            settings_file = self.ReadRootFile(self.codereview_settings_file)
            if settings_file:
                for line in settings_file.splitlines():
                    if not line or line.lstrip().startswith('#'):
                        continue
                    k, v = line.split(":", 1)
                    self.codereview_settings[k.strip()] = v.strip()
        return self.codereview_settings.get(key, '')
Пример #11
0
  def testLoadWithIssue(self):
    self.mox.StubOutWithMock(gcl, 'GetCodeReviewSetting')
    description = ["This is some description.", "force an extra separator."]
    gcl.GetChangelistInfoFile('bleh').AndReturn('bleeeh')
    gcl.os.path.exists('bleeeh').AndReturn(True)
    gcl.gclient_utils.FileRead('bleeeh').AndReturn(
      gcl.ChangeInfo.SEPARATOR.join(["42, 53", "G      b.cc"] + description))
    gcl.GetCodeReviewSetting('CODE_REVIEW_SERVER').AndReturn('foo')
    # Does an upgrade.
    gcl.GetChangelistInfoFile('bleh').AndReturn('bleeeh')
    gcl.gclient_utils.FileWrite('bleeeh', mox.IgnoreArg())
    self.mox.ReplayAll()

    change_info = gcl.ChangeInfo.Load('bleh', self.fake_root_dir, True, False)
    self.assertEquals(change_info.name, 'bleh')
    self.assertEquals(change_info.issue, 42)
    self.assertEquals(change_info.patchset, 53)
    self.assertEquals(change_info.description,
                      gcl.ChangeInfo.SEPARATOR.join(description))
    self.assertEquals(change_info.GetFiles(), [('G      ', 'b.cc')])
Пример #12
0
def do_cpp_lint(changeset, repo, args):
    # Try to import cpplint from depot_tools first
    try:
        import cpplint
    except ImportError:
        TryAddDepotToolsToPythonPath()

    try:
        import cpplint
        import cpplint_chromium
        import gcl
    except ImportError:
        sys.stderr.write("Can't find cpplint, please add your depot_tools "\
                         "to PATH or PYTHONPATH\n")
        raise

    origin_error = cpplint.Error

    def MyError(filename, linenum, category, confidence, message):
        # Skip no header guard  error for MSVC generated files.
        if (filename.endswith('resource.h')):
            sys.stdout.write(
                'Ignored Error:\n  %s(%s):  %s  [%s] [%d]\n' %
                (filename, linenum, message, category, confidence))
        # Skip no header guard  error for ipc messages definition,
        # because they will be included multiple times for different macros.
        elif (filename.endswith('messages.h') and linenum == 0
              and category == 'build/header_guard'):
            sys.stdout.write(
                'Ignored Error:\n  %s(%s):  %s  [%s] [%d]\n' %
                (filename, linenum, message, category, confidence))
        else:
            origin_error(filename, linenum, category, confidence, message)

    cpplint.Error = MyError

    origin_FileInfo = cpplint.FileInfo

    class MyFileInfo(origin_FileInfo):
        def RepositoryName(self):
            ''' Origin FileInfo find the first .git and take it as project root,
          it's not the case for xwalk, header in xwalk should have guard
          relevant to root dir of chromium project, which is one level
          upper of the origin output of RepositoryName.
      '''
            repo_name = origin_FileInfo.RepositoryName(self)
            if repo == "xwalk" and not repo_name.startswith('xwalk'):
                return 'xwalk/%s' % repo_name
            else:
                return repo_name

    cpplint.FileInfo = MyFileInfo

    print '_____ do cpp lint'
    if len(changeset) == 0:
        print 'changeset is empty except python files'
        return
    # Following code is referencing depot_tools/gcl.py: CMDlint
    # Process cpplints arguments if any.
    filenames = cpplint.ParseArguments(args + changeset)

    white_list = gcl.GetCodeReviewSetting("LINT_REGEX")
    if not white_list:
        white_list = gcl.DEFAULT_LINT_REGEX
    white_regex = re.compile(white_list)
    black_list = gcl.GetCodeReviewSetting("LINT_IGNORE_REGEX")
    if not black_list:
        black_list = gcl.DEFAULT_LINT_IGNORE_REGEX
    black_regex = re.compile(black_list)
    extra_check_functions = [
        cpplint_chromium.CheckPointerDeclarationWhitespace
    ]
    # pylint: disable=W0212
    cpplint_state = cpplint._cpplint_state
    for filename in filenames:
        if white_regex.match(filename):
            if black_regex.match(filename):
                print "Ignoring file %s" % filename
            else:
                cpplint.ProcessFile(filename, cpplint_state.verbose_level,
                                    extra_check_functions)
        else:
            print "Skipping file %s" % filename
    print "Total errors found: %d\n" % cpplint_state.error_count