Python pygit2.Signature() Examples

The following are 19 code examples of pygit2.Signature(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module pygit2 , or try the search function .
Example #1
Source File: __init__.py    From pagure with GNU General Public License v2.0 6 votes vote down vote up
def add_tag_git_repo(folder, tagname, obj_hash, message):
    """ Add a tag to the given object of the given repo annotated by given message. """
    repo, newfolder, branch_ref_obj = _clone_and_top_commits(
        folder, "master", branch_ref=True
    )

    tag_sha = repo.create_tag(
        tagname,
        obj_hash,
        repo.get(obj_hash).type,
        pygit2.Signature("Alice Author", "alice@authors.tld"),
        message,
    )

    # Push to origin
    ori_remote = repo.remotes[0]
    PagureRepo.push(
        ori_remote, "refs/tags/%s:refs/tags/%s" % (tagname, tagname)
    )

    shutil.rmtree(newfolder)
    return tag_sha 
Example #2
Source File: test_gitdata.py    From repostat with GNU General Public License v3.0 6 votes vote down vote up
def test_incomplete_signature_does_not_crash_gitdata_classes(self):
        import tempfile

        with tempfile.TemporaryDirectory(prefix="tmprepo_") as tmp_repo_location:
            # change working directory
            os.chdir(tmp_repo_location)
            subprocess.run(['git', 'init'], cwd=tmp_repo_location)
            # create a file a single line in it
            filename = 'file.txt'
            with open(os.path.join(tmp_repo_location, filename), "w") as f:
                f.write("A single line of code\n")
            subprocess.run(['git', 'add', 'file.txt'], cwd=tmp_repo_location)
            # apparently it is not possible to create pygit.Signature with empty author's email (and name)
            # but commits with no author's email can be created via git
            subprocess.run(['git', 'commit', '-m "No-email author" --author "Author NoEmail <>"'],
                           cwd=tmp_repo_location)
            try:
                # Commit without author's email does not crash data fetch
                git_repository = Repository(tmp_repo_location)
                WholeHistory(git_repository)
                BlameData(git_repository)
            except Exception as e:
                self.fail(str(e)) 
Example #3
Source File: test_pagure_flask_ui_repo_view_history.py    From pagure with GNU General Public License v2.0 6 votes vote down vote up
def test_view_history_file_on_tag(self):
        """ Test the view_history_file endpoint """
        # set a tag on the head's parent commit
        repo_obj = pygit2.Repository(
            os.path.join(self.path, "repos", "test.git")
        )
        commit = repo_obj[repo_obj.head.target]
        parent = commit.parents[0].oid.hex
        tagger = pygit2.Signature("Alice Doe", "adoe@example.com", 12347, 0)
        repo_obj.create_tag(
            "v1.0", parent, pygit2.GIT_OBJ_COMMIT, tagger, "Release v1.0"
        )

        output = self.app.get("/test/history/sources?identifier=v1.0")
        self.assertEqual(output.status_code, 200)
        output_text = output.get_data(as_text=True)
        self.assertIn("<strong>initial commit</strong>", output_text)
        data = self.regex.findall(output_text)
        self.assertEqual(len(data), 1) 
Example #4
Source File: test_pagure_lib_git_get_tags_objects.py    From pagure with GNU General Public License v2.0 6 votes vote down vote up
def add_repo_tag(git_dir, repo, tags, repo_name):
    """ Use a list to create multiple tags on a git repo """
    for tag in reversed(tags):
        time.sleep(1)
        tests.add_commit_git_repo(
            os.path.join(git_dir, "repos", repo_name), ncommits=1
        )
        first_commit = repo.revparse_single("HEAD")
        tagger = pygit2.Signature("Alice Doe", "adoe@example.com", 12347, 0)
        repo.create_tag(
            tag,
            first_commit.oid.hex,
            pygit2.GIT_OBJ_COMMIT,
            tagger,
            "Release " + tag,
        ) 
Example #5
Source File: utils.py    From git-annex-adapter with GNU General Public License v3.0 6 votes vote down vote up
def git_commit(self):
        """Commit the current index to the git repository."""
        author = pygit2.Signature(
            'Git-Annex-Adapter Tester',
            'git-annex-adapter-tester@example.com',
            1500000000, # Date: 2017-07-14 02:40:00
        )

        try:
            parents = [self.repo.head.get_object().hex]
        except pygit2.GitError:
            parents = []

        return self.repo.create_commit(
            'HEAD', author, author, 'Test commit',
            self.repo.index.write_tree(), parents,
        ) 
Example #6
Source File: __init__.py    From pagure with GNU General Public License v2.0 5 votes vote down vote up
def add_binary_git_repo(folder, filename):
    """ Create a fake image file for the specified git repo. """
    repo, newfolder, parents = _clone_and_top_commits(folder, "master")

    content = b"""\x00\x00\x01\x00\x01\x00\x18\x18\x00\x00\x01\x00 \x00\x88
\t\x00\x00\x16\x00\x00\x00(\x00\x00\x00\x18\x00x00\x00\x01\x00 \x00\x00\x00
\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00
00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xa7lM\x01\xa6kM\t\xa6kM\x01
\xa4fF\x04\xa2dE\x95\xa2cD8\xa1a
"""

    # Create a file in that git repo
    with open(os.path.join(newfolder, filename), "wb") as stream:
        stream.write(content)
    repo.index.add(filename)
    repo.index.write()

    # Commits the files added
    tree = repo.index.write_tree()
    author = pygit2.Signature("Alice Author", "alice@authors.tld")
    committer = pygit2.Signature("Cecil Committer", "cecil@committers.tld")
    repo.create_commit(
        "refs/heads/master",  # the name of the reference to update
        author,
        committer,
        "Add a fake image file",
        # binary string representing the tree object ID
        tree,
        # list of binary strings representing parents of the new commit
        parents,
    )

    # Push to origin
    ori_remote = repo.remotes[0]
    master_ref = repo.lookup_reference("HEAD").resolve()
    refname = "%s:%s" % (master_ref.name, master_ref.name)

    PagureRepo.push(ori_remote, refname)

    shutil.rmtree(newfolder) 
Example #7
Source File: test_pagure_flask_ui_repo_view_blame.py    From pagure with GNU General Public License v2.0 5 votes vote down vote up
def test_view_blame_file_on_tag(self):
        """ Test the view_blame_file endpoint """
        # set a tag on the head's parent commit
        repo_obj = pygit2.Repository(
            os.path.join(self.path, "repos", "test.git")
        )
        commit = repo_obj[repo_obj.head.target]
        parent = commit.parents[0].oid.hex
        tagger = pygit2.Signature("Alice Doe", "adoe@example.com", 12347, 0)
        repo_obj.create_tag(
            "v1.0", parent, pygit2.GIT_OBJ_COMMIT, tagger, "Release v1.0"
        )

        output = self.app.get("/test/blame/sources?identifier=v1.0")
        self.assertEqual(output.status_code, 200)
        output_text = output.get_data(as_text=True)
        self.assertIn('<table class="code_table">', output_text)
        self.assertTrue(
            '<tr><td class="cell1"><a id="1" href="#1" '
            'data-line-number="1"></a></td>' in output_text
            or '<tr><td class="cell1"><a data-line-number="1" '
            'href="#1" id="1"></a></td>' in output_text
        )
        self.assertIn(
            '<td class="cell2"><pre><code>foo</code></pre></td>', output_text
        )
        self.assertIn('<td class="cell_user">Alice Author</td>', output_text)
        data = self.regex.findall(output_text)
        self.assertEqual(len(data), 1) 
Example #8
Source File: test_pagure_flask_api_project_view_file.py    From pagure with GNU General Public License v2.0 5 votes vote down vote up
def test_view_file_from_tag_hex(self):
        repo = pygit2.Repository(os.path.join(self.path, "repos", "test.git"))
        commit = repo.revparse_single("HEAD")
        tagger = pygit2.Signature("Alice Doe", "adoe@example.com", 12347, 0)
        tag = repo.create_tag(
            "v1.0_tag",
            commit.oid.hex,
            pygit2.GIT_OBJ_COMMIT,
            tagger,
            "Release v1.0",
        )

        output = self.app.get("/api/0/test/tree/%s" % tag.hex)
        self.assertEqual(output.status_code, 200)
        data = json.loads(output.get_data(as_text=True))
        self.assertDictEqual(
            data,
            {
                "content": [
                    {
                        "content_url": "http://localhost/test/raw/"
                        "%s/f/README.rst" % tag.hex,
                        "name": "README.rst",
                        "path": "README.rst",
                        "type": "file",
                    }
                ],
                "name": None,
                "type": "folder",
            },
        ) 
Example #9
Source File: test_gitdata.py    From repostat with GNU General Public License v3.0 5 votes vote down vote up
def test_records_count_in_history(self):
        # create second branch from 'master' (which already had one commit)
        branch = self.test_repo.branches.local.create('second_branch', self.test_repo.head.peel())
        self.test_repo.checkout(branch)

        # create commit on new branch
        self.test_repo.commit_builder \
            .set_author("Author Author", "author@author.net") \
            .add_file(content=["some content"]) \
            .commit()

        # so far no merge commits, both linear and whole history caches should contain 2 records
        whole_history_df = WholeHistory(self.test_repo).as_dataframe()
        self.assertEqual(2, len(whole_history_df.index))
        linear_history_df = LinearHistory(self.test_repo).as_dataframe()
        self.assertEqual(2, len(linear_history_df.index))

        # now merge commit is being created
        # checkout to master
        master_branch = self.test_repo.branches.get('master')
        self.test_repo.checkout(master_branch)
        # and merge 'second_branch' into 'master'
        self.test_repo.merge(self.test_repo.branches.get('second_branch').peel().id)
        # by creating merge commit
        author = Signature("name", "email")
        committer = author
        tree = self.test_repo.index.write_tree()
        message = "Merge 'second_branch' into 'master'"
        self.test_repo.create_commit('HEAD', author, committer, message, tree,
                                     [self.test_repo.head.target,
                                      self.test_repo.branches.get('second_branch').peel().oid])

        # whole history cache should contain 3 records: initial commit + commit in merged branch + merge commit
        whole_history_df = WholeHistory(self.test_repo).as_dataframe()
        self.assertEqual(3, len(whole_history_df.index))
        # linear history cache still contains 2 records: initial commit + merge commit
        linear_history_df = LinearHistory(self.test_repo).as_dataframe()
        self.assertEqual(2, len(linear_history_df.index))

        # check merge commits count (there is a single merge commit)
        self.assertEqual(1, whole_history_df['is_merge_commit'].sum()) 
Example #10
Source File: git.py    From pagure with GNU General Public License v2.0 5 votes vote down vote up
def _make_signature(name, email):
    if six.PY2:
        if isinstance(name, six.text_type):
            name = name.encode("utf-8")
        if isinstance(email, six.text_type):
            email = email.encode("utf-8")
    return pygit2.Signature(name=name, email=email) 
Example #11
Source File: git.py    From pagure with GNU General Public License v2.0 5 votes vote down vote up
def new_git_tag(project, tagname, target, user, message=None, force=False):
    """ Create a new git tag in the git repositorie of the specified project.

    :arg project: the project in which we want to create a git tag
    :type project: pagure.lib.model.Project
    :arg tagname: the name of the tag to create
    :type tagname: str
    :arg user: the user creating the tag
    :type user: pagure.lib.model.User
    :kwarg message: the message to include in the annotation of the tag
    :type message: str or None
    :kwarg force: a boolean specifying wether to force the creation of
        the git tag or not
    :type message: bool
    """
    repopath = pagure.utils.get_repo_path(project)
    repo_obj = PagureRepo(repopath)

    target_obj = repo_obj.get(target)
    if not target_obj:
        raise pygit2.GitError("Unknown target: %s" % target)

    if force:
        existing_tag = repo_obj.lookup_reference("refs/tags/%s" % tagname)
        if existing_tag:
            existing_tag.delete()

    tag = repo_obj.create_tag(
        tagname,
        target,
        target_obj.type,
        pygit2.Signature(user.fullname, user.default_email),
        message,
    )

    return tag 
Example #12
Source File: git_mgr.py    From bootloader_instrumentation_suite with MIT License 5 votes vote down vote up
def commit_changes(self):
        self.repo.index.add_all()
        self.repo.index.write()
        tree = self.repo.index.write_tree()
        author = pygit2.Signature("bx", "bx@cs")
        old = self.repo.create_commit(self.get_head(),
                                      author,
                                      author,
                                      "auto commit for testing",
                                      tree,
                                      [self.repo.head.get_object().hex]) 
Example #13
Source File: gitdata.py    From repostat with GNU General Public License v3.0 5 votes vote down vote up
def map_signature(mailmap, signature: git.Signature):
    # the unmapped email is used on purpose
    email = signature.email
    try:
        mapped_signature = mailmap.resolve_signature(signature)
        name = mapped_signature.name
    except ValueError:
        name = signature.name
        if not name:
            name = "Empty Empty"
            # warnings.warn(f"{str(e)}. Name will be replaced with '{name}'")
        if not email:
            email = "empty@empty.empty"
            # warnings.warn(f"{str(e)}. Email will be replaced with '{email}'")
    return name, email 
Example #14
Source File: gitrepository.py    From repostat with GNU General Public License v3.0 5 votes vote down vote up
def set_author(self, name: str, email: str):
            self.author_signature = git.Signature(name, email)
            return self 
Example #15
Source File: test_pagure_flask_ui_no_master_branch.py    From pagure with GNU General Public License v2.0 4 votes vote down vote up
def set_up_git_repo(self):
        """ Set up the git repo to play with. """

        # Create a git repo to play with
        gitrepo = os.path.join(self.path, "repos", "test.git")
        repo = pygit2.init_repository(gitrepo, bare=True)

        newpath = tempfile.mkdtemp(prefix="pagure-other-test")
        repopath = os.path.join(newpath, "test")
        clone_repo = pygit2.clone_repository(gitrepo, repopath)

        # Create a file in that git repo
        with open(os.path.join(repopath, "sources"), "w") as stream:
            stream.write("foo\n bar")
        clone_repo.index.add("sources")
        clone_repo.index.write()

        # Commits the files added
        tree = clone_repo.index.write_tree()
        author = pygit2.Signature("Alice Author", "alice@authors.tld")
        committer = pygit2.Signature("Cecil Committer", "cecil@committers.tld")
        clone_repo.create_commit(
            "refs/heads/feature",  # the name of the reference to update
            author,
            committer,
            "Add sources file for testing",
            # binary string representing the tree object ID
            tree,
            # list of binary strings representing parents of the new commit
            [],
        )

        feature_branch = clone_repo.lookup_branch("feature")
        first_commit = feature_branch.peel().hex

        # Second commit
        with open(os.path.join(repopath, ".gitignore"), "w") as stream:
            stream.write("*~")
        clone_repo.index.add(".gitignore")
        clone_repo.index.write()

        tree = clone_repo.index.write_tree()
        author = pygit2.Signature("Alice Author", "alice@authors.tld")
        committer = pygit2.Signature("Cecil Committer", "cecil@committers.tld")
        clone_repo.create_commit(
            "refs/heads/feature",
            author,
            committer,
            "Add .gitignore file for testing",
            # binary string representing the tree object ID
            tree,
            # list of binary strings representing parents of the new commit
            [first_commit],
        )

        refname = "refs/heads/feature"
        ori_remote = clone_repo.remotes[0]
        PagureRepo.push(ori_remote, refname)

        shutil.rmtree(newpath) 
Example #16
Source File: test_gitdata.py    From repostat with GNU General Public License v3.0 4 votes vote down vote up
def test_annotated_tags_fetch(self):
        test_repo = GitTestRepository()

        # master branch
        test_repo.commit_builder \
            .set_author("John Doe", "john@doe.com") \
            .add_file(content="bzyk") \
            .commit()

        # create second branch from 'master' (which already had one commit)
        branch = test_repo.branches.local.create('second_branch', test_repo.head.peel())
        test_repo.checkout(branch)

        # create commit on new branch
        test_repo.commit_builder \
            .set_author("Author Author", "author@author.net") \
            .add_file(content=["some content"]) \
            .commit()

        # checkout to master
        master_branch = test_repo.branches.get('master')
        test_repo.checkout(master_branch)
        # create commit
        test_repo.commit_builder \
            .set_author("Jack Johns", "jack@johns.com").add_file() \
            .commit()

        # and merge 'second_branch' into 'master'
        test_repo.merge(test_repo.branches.get('second_branch').peel().id)
        # by creating merge commit
        author = Signature("name", "email")
        committer = author
        tree = test_repo.index.write_tree()
        message = "Merge 'second_branch' into 'master'"
        v1_oid = test_repo.create_commit('HEAD', author, committer, message, tree,
                                         [test_repo.head.target,
                                          test_repo.branches.get('second_branch').peel().oid])

        test_repo.create_tag("v1", str(v1_oid), pygit2.GIT_OBJ_COMMIT,
                             Signature('John Doe', 'jdoe@example.com', 1589748740, 0),
                             "v1 tag")

        v2_oid = test_repo.commit_builder \
            .set_author("Jack Johns", "jack@johns.com").add_file() \
            .commit()
        test_repo.create_tag("v2", str(v2_oid), pygit2.GIT_OBJ_COMMIT,
                             Signature('John Doe', 'jdoe@example.com'),
                             "v2 tag")

        test_repo.commit_builder \
            .set_author("Incognito", "j@anonimous.net").add_file() \
            .commit()

        tags_data = TagsData(test_repo).fetch()

        self.assertEqual(4, len([x for x in tags_data if x['tag_name'] == 'v1']))
        self.assertEqual(1, len([x for x in tags_data if x['tag_name'] == 'v2']))
        self.assertEqual(1, len([x for x in tags_data if x['tag_name'] is None])) 
Example #17
Source File: test_pagure_flask_docs.py    From pagure with GNU General Public License v2.0 4 votes vote down vote up
def _set_up_doc(self):
        # forked doc repo
        docrepo = os.path.join(self.path, "repos", "docs", "test", "test.git")
        repo = pygit2.init_repository(docrepo)

        # Create files in that git repo
        with open(os.path.join(docrepo, "sources"), "w") as stream:
            stream.write("foo\n bar")
        repo.index.add("sources")
        repo.index.write()

        folderpart = os.path.join(docrepo, "folder1", "folder2")
        os.makedirs(folderpart)
        with open(os.path.join(folderpart, "test_file"), "w") as stream:
            stream.write("row1\nrow2\nrow3")
        repo.index.add(os.path.join("folder1", "folder2", "test_file"))
        repo.index.write()

        # Commits the files added
        tree = repo.index.write_tree()
        author = pygit2.Signature("Alice Author", "alice@authors.tld")
        committer = pygit2.Signature("Cecil Committer", "cecil@committers.tld")
        repo.create_commit(
            "refs/heads/master",  # the name of the reference to update
            author,
            committer,
            "Add test files and folder",
            # binary string representing the tree object ID
            tree,
            # list of binary strings representing parents of the new commit
            [],
        )

        # Push the changes to the bare repo
        remote = repo.create_remote(
            "origin", os.path.join(self.path, "repos", "docs", "test.git")
        )

        PagureRepo.push(remote, "refs/heads/master:refs/heads/master")

        # Turn on the docs project since it's off by default
        repo = pagure.lib.query.get_authorized_project(self.session, "test")
        repo.settings = {"project_documentation": True}
        self.session.add(repo)
        self.session.commit() 
Example #18
Source File: __init__.py    From pagure with GNU General Public License v2.0 4 votes vote down vote up
def add_content_to_git(
    folder,
    branch="master",
    folders=None,
    filename="sources",
    content="foo",
    message=None,
    author=("Alice Author", "alice@authors.tld"),
    commiter=("Cecil Committer", "cecil@committers.tld"),
):
    """ Create some more commits for the specified git repo. """
    repo, newfolder, branch_ref_obj = _clone_and_top_commits(
        folder, branch, branch_ref=True
    )

    # Create a file in that git repo
    if folders:
        if not os.path.exists(os.path.join(newfolder, folders)):
            os.makedirs(os.path.join(newfolder, folders))
        filename = os.path.join(folders, filename)

    filepath = os.path.join(newfolder, filename)
    with open(filepath, "a", encoding="utf-8") as stream:
        stream.write("%s\n" % content)
    repo.index.add(filename)
    repo.index.write()

    parents = []
    commit = None
    try:
        if branch_ref_obj:
            commit = repo[branch_ref_obj.peel().hex]
        else:
            commit = repo.revparse_single("HEAD")
    except (KeyError, AttributeError):
        pass
    if commit:
        parents = [commit.oid.hex]

    # Commits the files added
    tree = repo.index.write_tree()
    author = pygit2.Signature(*author)
    committer = pygit2.Signature(*commiter)
    branch_ref = "refs/heads/%s" % branch
    message = message or "Add content to file %s" % (filename)
    repo.create_commit(
        branch_ref,  # the name of the reference to update
        author,
        committer,
        message,
        # binary string representing the tree object ID
        tree,
        # list of binary strings representing parents of the new commit
        parents,
    )

    # Push to origin
    ori_remote = repo.remotes[0]
    PagureRepo.push(ori_remote, "%s:%s" % (branch_ref, branch_ref))

    shutil.rmtree(newfolder) 
Example #19
Source File: __init__.py    From pagure with GNU General Public License v2.0 4 votes vote down vote up
def add_commit_git_repo(
    folder, ncommits=10, filename="sources", branch="master", symlink_to=None
):
    """ Create some more commits for the specified git repo. """
    repo, newfolder, branch_ref_obj = _clone_and_top_commits(
        folder, branch, branch_ref=True
    )

    for index in range(ncommits):
        # Create a file in that git repo
        if symlink_to:
            os.symlink(symlink_to, os.path.join(newfolder, filename))
        else:
            with open(os.path.join(newfolder, filename), "a") as stream:
                stream.write("Row %s\n" % index)
        repo.index.add(filename)
        repo.index.write()

        parents = []
        commit = None
        try:
            if branch_ref_obj:
                commit = repo[branch_ref_obj.peel().hex]
            else:
                commit = repo.revparse_single("HEAD")
        except (KeyError, AttributeError):
            pass
        if commit:
            parents = [commit.oid.hex]

        # Commits the files added
        tree = repo.index.write_tree()
        author = pygit2.Signature("Alice Author", "alice@authors.tld")
        committer = pygit2.Signature("Cecil Committer", "cecil@committers.tld")
        branch_ref = "refs/heads/%s" % branch
        repo.create_commit(
            branch_ref,
            author,
            committer,
            "Add row %s to %s file" % (index, filename),
            # binary string representing the tree object ID
            tree,
            # list of binary strings representing parents of the new commit
            parents,
        )
        branch_ref_obj = pagure.lib.git.get_branch_ref(repo, branch)

    # Push to origin
    ori_remote = repo.remotes[0]
    PagureRepo.push(ori_remote, "%s:%s" % (branch_ref, branch_ref))

    shutil.rmtree(newfolder)