Exemple #1
0
 def test_sorting(self):
     self.assertEqual(
         sorted(
             [Contributor('Jonathan Bedard'),
              Contributor('Aakash Jain')]),
         [Contributor('Aakash Jain'),
          Contributor('Jonathan Bedard')],
     )
Exemple #2
0
    def test_branch_commits(self):
        with OutputCapture() as captured, mocks.local.Git(
                self.path) as mock, mocks.local.Svn(), MockTime:
            contirbutors = Contributor.Mapping()
            contirbutors.create('Jonathan Bedard', '*****@*****.**')

            local.Git(self.path).checkout('branch-a')
            mock.commits['branch-a'].append(
                Commit(
                    hash='f93138e3bf1d5ecca25fc0844b7a2a78b8e00aae',
                    branch='branch-a',
                    author=Contributor('*****@*****.**',
                                       emails=['*****@*****.**']),
                    branch_point=mock.commits['branch-a'][-1].branch_point,
                    identifier=mock.commits['branch-a'][-1].identifier + 1,
                    timestamp=1601668000,
                    message='New commit 1\n',
                ))
            mock.commits['branch-a'].append(
                Commit(
                    hash='0148c0df0faf248aa133d6d5ad911d7cb1b56a5b',
                    branch='branch-a',
                    author=Contributor('*****@*****.**',
                                       emails=['*****@*****.**']),
                    branch_point=mock.commits['branch-a'][-1].branch_point,
                    identifier=mock.commits['branch-a'][-1].identifier + 1,
                    timestamp=1601669000,
                    message='New commit 2\n',
                ))

            self.assertEqual(
                0,
                program.main(
                    args=('canonicalize', ),
                    path=self.path,
                    contributors=contirbutors,
                ))

            commit_a = local.Git(self.path).commit(branch='branch-a~1')
            self.assertEqual(commit_a.author,
                             contirbutors['*****@*****.**'])
            self.assertEqual(commit_a.message,
                             'New commit 1\nIdentifier: 2.3@branch-a')

            commit_b = local.Git(self.path).commit(branch='branch-a')
            self.assertEqual(commit_b.author,
                             contirbutors['*****@*****.**'])
            self.assertEqual(commit_b.message,
                             'New commit 2\nIdentifier: 2.4@branch-a')

        self.assertEqual(
            captured.stdout.getvalue(),
            'Rewrite f93138e3bf1d5ecca25fc0844b7a2a78b8e00aae (1/2) (--- seconds passed, remaining --- predicted)\n'
            'Rewrite 0148c0df0faf248aa133d6d5ad911d7cb1b56a5b (2/2) (--- seconds passed, remaining --- predicted)\n'
            '2 commits successfully canonicalized!\n',
        )
Exemple #3
0
    def test_hash(self):
        self.assertEqual(
            hash(Contributor('Jonathan Bedard', ['*****@*****.**'])),
            hash(Contributor('Jonathan Bedard', ['*****@*****.**'])),
        )

        self.assertNotEqual(
            hash(Contributor('Jonathan Bedard', ['*****@*****.**'])),
            hash(Contributor('Aakash Jain', ['*****@*****.**'])),
        )
Exemple #4
0
    def test_string_comparison(self):
        self.assertEqual(
            Contributor('Jonathan Bedard', ['*****@*****.**']),
            'Jonathan Bedard',
        )

        self.assertNotEqual(
            Contributor('Jonathan Bedard', ['*****@*****.**']),
            'Aakash Jain',
        )
Exemple #5
0
    def test_json_decode(self):
        contributor_a = Contributor(
            name='Jonathan Bedard',
            emails=['*****@*****.**', '*****@*****.**'],
        )

        dictionary = json.loads(
            json.dumps(contributor_a, cls=Contributor.Encoder))
        contributor_b = Contributor(**dictionary)

        self.assertEqual(contributor_a, contributor_b)
Exemple #6
0
 def test_unicode(self):
     self.assertEqual(
         str(
             Contributor(u'Michael Br\u00fcning',
                         ['*****@*****.**'])),
         string_utils.encode(
             u'Michael Br\u00fcning <*****@*****.**>',
             target_type=str),
     )
Exemple #7
0
 def test_json_encode(self):
     self.assertDictEqual(
         dict(
             name='Jonathan Bedard',
             emails=['*****@*****.**', '*****@*****.**'],
         ),
         json.loads(
             json.dumps(Contributor(
                 name='Jonathan Bedard',
                 emails=['*****@*****.**', '*****@*****.**'],
             ),
                        cls=Contributor.Encoder)))
Exemple #8
0
    def test_formated_identifier(self):
        with OutputCapture() as captured, mocks.local.Git(
                self.path) as mock, mocks.local.Svn(), MockTime:
            contirbutors = Contributor.Mapping()
            contirbutors.create('\u017dan Dober\u0161ek',
                                '*****@*****.**')

            mock.commits[mock.default_branch].append(
                Commit(
                    hash='38ea50d28ae394c9c8b80e13c3fb21f1c262871f',
                    branch=mock.default_branch,
                    author=Contributor('\u017dan Dober\u0161ek',
                                       emails=['*****@*****.**']),
                    identifier=mock.commits[mock.default_branch][-1].identifier
                    + 1,
                    timestamp=1601668000,
                    message='New commit\n',
                ))

            self.assertEqual(
                0,
                program.main(
                    args=(
                        'canonicalize',
                        '-v',
                    ),
                    path=self.path,
                    contributors=contirbutors,
                    identifier_template=
                    'Canonical link: https://commits.webkit.org/{}',
                ))

            commit = local.Git(self.path).commit(branch=mock.default_branch)
            self.assertEqual(commit.author,
                             contirbutors['*****@*****.**'])
            self.assertEqual(
                commit.message,
                'New commit\nCanonical link: https://commits.webkit.org/5@main'
            )

        self.assertEqual(
            captured.stdout.getvalue(),
            'Rewrite 38ea50d28ae394c9c8b80e13c3fb21f1c262871f (1/1) (--- seconds passed, remaining --- predicted)\n'
            'Overwriting 38ea50d28ae394c9c8b80e13c3fb21f1c262871f\n'
            '1 commit successfully canonicalized!\n',
        )
Exemple #9
0
    def test_git_svn(self):
        with OutputCapture() as captured, mocks.local.Git(
                self.path, git_svn=True) as mock, mocks.local.Svn(), MockTime:
            contirbutors = Contributor.Mapping()
            contirbutors.create('Jonathan Bedard', '*****@*****.**')

            mock.commits[mock.default_branch].append(
                Commit(
                    hash='766609276fe201e7ce2c69994e113d979d2148ac',
                    branch=mock.default_branch,
                    author=Contributor('*****@*****.**',
                                       emails=['*****@*****.**']),
                    identifier=mock.commits[mock.default_branch][-1].identifier
                    + 1,
                    timestamp=1601668000,
                    revision=9,
                    message='New commit\n',
                ))

            self.assertEqual(
                0,
                program.main(
                    args=('canonicalize', '-vv'),
                    path=self.path,
                    contributors=contirbutors,
                ))

            commit = local.Git(self.path).commit(branch=mock.default_branch)
            self.assertEqual(commit.author, contirbutors['*****@*****.**'])
            self.assertEqual(
                commit.message,
                'New commit\n'
                'Identifier: 5@main\n'
                'svn-id: https://svn.example.org/repository/repository/trunk@9 268f45cc-cd09-0410-ab3c-d52691b4dbfc',
            )

        self.assertEqual(
            captured.stdout.getvalue(),
            'Rewrite 766609276fe201e7ce2c69994e113d979d2148ac (1/1) (--- seconds passed, remaining --- predicted)\n'
            'Overwriting 766609276fe201e7ce2c69994e113d979d2148ac\n'
            '    GIT_AUTHOR_NAME=Jonathan Bedard\n'
            '    [email protected]\n'
            '    GIT_COMMITTER_NAME=Jonathan Bedard\n'
            '    [email protected]\n'
            '1 commit successfully canonicalized!\n',
        )
Exemple #10
0
    def test_existing_identifier(self):
        with OutputCapture() as captured, mocks.local.Git(
                self.path) as mock, mocks.local.Svn(), MockTime:
            contirbutors = Contributor.Mapping()
            contirbutors.create('Jonathan Bedard', '*****@*****.**')

            mock.commits[mock.default_branch].append(
                Commit(
                    hash='38ea50d28ae394c9c8b80e13c3fb21f1c262871f',
                    branch=mock.default_branch,
                    author=Contributor('Jonathan Bedard',
                                       emails=['*****@*****.**']),
                    identifier=mock.commits[mock.default_branch][-1].identifier
                    + 1,
                    timestamp=1601668000,
                    message='New commit\nIdentifier: {}@{}'.format(
                        mock.commits[mock.default_branch][-1].identifier + 1,
                        mock.default_branch,
                    ),
                ))

            self.assertEqual(
                0,
                program.main(
                    args=(
                        'canonicalize',
                        '-v',
                    ),
                    path=self.path,
                    contributors=contirbutors,
                ))

            commit = local.Git(self.path).commit(branch=mock.default_branch)
            self.assertEqual(commit.author, contirbutors['*****@*****.**'])
            self.assertEqual(commit.message, 'New commit\nIdentifier: 5@main')

        self.assertEqual(
            captured.stdout.getvalue(),
            'Rewrite 38ea50d28ae394c9c8b80e13c3fb21f1c262871f (1/1) (--- seconds passed, remaining --- predicted)\n'
            'Overwriting 38ea50d28ae394c9c8b80e13c3fb21f1c262871f\n'
            '1 commit successfully canonicalized!\n',
        )
Exemple #11
0
    def __init__(
        self,
        hash=None,
        revision=None,
        identifier=None,
        branch=None,
        branch_point=None,
        timestamp=None,
        author=None,
        message=None,
    ):
        self.hash = self._parse_hash(hash, do_assert=True)
        self.revision = self._parse_revision(revision, do_assert=True)

        parsed_identifier = self._parse_identifier(identifier, do_assert=True)
        if parsed_identifier:
            parsed_branch_point, self.identifier, parsed_branch = parsed_identifier
            self.branch_point = parsed_branch_point or branch_point
            self.branch = parsed_branch or branch
        else:
            self.identifier = None
            self.branch_point = branch_point
            self.branch = branch

        if branch and not isinstance(branch, six.string_types):
            raise ValueError("Expected 'branch' to be a string")
        if branch and branch != self.branch:
            raise ValueError(
                "Caller passed both 'branch' and 'identifier', but specified different branches ({} and {})"
                .format(
                    branch,
                    self.branch,
                ), )

        if branch_point and not isinstance(branch_point, int):
            raise ValueError("Expected 'branch_point' to be an int")
        if branch_point and branch_point != self.branch_point:
            raise ValueError(
                "Caller passed both 'branch_point' and 'identifier', but specified different values ({} and {})"
                .format(
                    branch_point,
                    self.branch_point,
                ), )

        if timestamp and not isinstance(timestamp, int):
            raise TypeError(
                "Expected 'timestamp' to be of type int, got '{}'".format(
                    timestamp))
        self.timestamp = timestamp

        if author and isinstance(author, dict) and author.get('name'):
            self.author = Contributor(author.get('name'), author.get('emails'))
        elif author and not isinstance(author, Contributor):
            raise TypeError(
                "Expected 'author' to be of type {}, got '{}'".format(
                    Contributor, author))
        else:
            self.author = author

        if message and not isinstance(message, six.string_types):
            raise ValueError(
                "Expected 'message' to be a string, got '{}'".format(message))
        self.message = message

        # Force a commit format check
        self.__repr__()
Exemple #12
0
    def filter_branch(self,
                      range,
                      identifier_template=None,
                      environment_shell=None):
        # We can't effectively mock the bash script in the command, but we can mock the python code that
        # script calls, which is where the program logic is.
        head, start = range.split('...')
        head = self.find(head)
        start = self.find(start)

        commits_to_edit = []
        for commit in reversed(self.commits[head.branch]):
            if commit.branch == start.branch and commit.identifier <= start.identifier:
                break
            commits_to_edit.insert(0, commit)
        if head.branch != self.default_branch:
            for commit in reversed(
                    self.commits[self.default_branch][:head.branch_point]):
                if commit.identifier <= start.identifier:
                    break
                commits_to_edit.insert(0, commit)

        stdout = StringIO()
        original_env = {
            key: os.environ.get('OLDPWD')
            for key in [
                'OLDPWD',
                'GIT_COMMIT',
                'GIT_AUTHOR_NAME',
                'GIT_AUTHOR_EMAIL',
                'GIT_COMMITTER_NAME',
                'GIT_COMMITTER_EMAIL',
            ]
        }

        try:
            count = 0
            os.environ['OLDPWD'] = self.path
            for commit in commits_to_edit:
                count += 1
                os.environ['GIT_COMMIT'] = commit.hash
                os.environ['GIT_AUTHOR_NAME'] = commit.author.name
                os.environ['GIT_AUTHOR_EMAIL'] = commit.author.email
                os.environ['GIT_COMMITTER_NAME'] = commit.author.name
                os.environ['GIT_COMMITTER_EMAIL'] = commit.author.email

                stdout.write(
                    'Rewrite {hash} ({count}/{total}) (--- seconds passed, remaining --- predicted)\n'
                    .format(
                        hash=commit.hash,
                        count=count,
                        total=len(commits_to_edit),
                    ))

                if identifier_template:
                    messagefile = StringIO()
                    messagefile.write(commit.message)
                    messagefile.seek(0)
                    with OutputCapture() as captured:
                        message_main(messagefile, identifier_template)
                    lines = captured.stdout.getvalue().splitlines()
                    if lines[-1].startswith('git-svn-id: https://svn'):
                        lines.pop(-1)
                    commit.message = '\n'.join(lines)

                if not environment_shell:
                    continue
                if re.search(r'echo "Overwriting', environment_shell):
                    stdout.write('Overwriting {}\n'.format(commit.hash))

                match = re.search(r'(?P<json>\S+\.json)', environment_shell)
                if match:
                    with OutputCapture() as captured:
                        committer_main(match.group('json'))
                    captured.stdout.seek(0)
                    for line in captured.stdout.readlines():
                        line = line.rstrip()
                        os.environ[line.split(' ')[0]] = ' '.join(
                            line.split(' ')[1:])

                commit.author = Contributor(
                    name=os.environ['GIT_AUTHOR_NAME'],
                    emails=[os.environ['GIT_AUTHOR_EMAIL']])

                if re.search(r'echo "\s+', environment_shell):
                    for key in [
                            'GIT_AUTHOR_NAME', 'GIT_AUTHOR_EMAIL',
                            'GIT_COMMITTER_NAME', 'GIT_COMMITTER_EMAIL'
                    ]:
                        stdout.write('    {}={}\n'.format(
                            key, os.environ[key]))

        finally:
            for key, value in original_env.items():
                if value is not None:
                    os.environ[key] = value
                else:
                    del os.environ[key]

        return mocks.ProcessCompletion(
            returncode=0,
            stdout=stdout.getvalue(),
        )
Exemple #13
0
    def test_pretty_print(self):
        self.assertEqual(
            Commit(
                identifier='123@master',
                hash='c3bd784f8b88bd03f64467ddd3304ed8be28acbe',
                author=Contributor('Jonathan Bedard', ['*****@*****.**']),
                message='NOT PRINTED',
            ).pretty_print(),
            '''123@master
    git hash: c3bd784f8b88 on master
    identifier: 123 on master
    by Jonathan Bedard <*****@*****.**>
''',
        )

        self.assertEqual(
            Commit(
                identifier='123@trunk',
                revision='r123',
                author=Contributor('Jonathan Bedard', ['*****@*****.**']),
                timestamp=1000,
                message='NOT PRINTED',
            ).pretty_print(),
            '''123@trunk
    SVN revision: r123 on trunk
    identifier: 123 on trunk
    by Jonathan Bedard <*****@*****.**> @ {}
'''.format(datetime.utcfromtimestamp(1000)),
        )

        self.assertEqual(
            Commit(
                identifier='123.1@branch-a',
                revision='r124',
                author=Contributor('Jonathan Bedard', ['*****@*****.**']),
                timestamp=1000,
                message='NOT PRINTED',
            ).pretty_print(),
            '''123.1@branch-a
    SVN revision: r124 on branch-a
    identifier: 1 on branch-a branched from 123
    by Jonathan Bedard <*****@*****.**> @ {}
'''.format(datetime.utcfromtimestamp(1000)),
        )

        self.assertEqual(
            Commit(
                identifier='123@trunk',
                revision='r123',
                author=Contributor('Jonathan Bedard', ['*****@*****.**']),
                timestamp=1000,
                message='PRINTED\n',
            ).pretty_print(message=True),
            '''123@trunk
    SVN revision: r123 on trunk
    identifier: 123 on trunk
    by Jonathan Bedard <*****@*****.**> @ {}

PRINTED
'''.format(datetime.utcfromtimestamp(1000)),
        )