Python git.Commit() Examples

The following are 22 code examples of git.Commit(). 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 git , or try the search function .
Example #1
Source File: test_graph_animator.py    From lookml-tools with Apache License 2.0 6 votes vote down vote up
def test_get_commits():
    config = {
                "infile_globs": [
                    "test/grapher/*.lkml"
                ],

                "options": {
                    "node_size": 400,
                    "label_font_size": 10,
                    "text_angle": 30,
                    "image_width": 12,
                    "image_height" : 8
                }
            }
    animator = GraphAnimator(config)
    repo, commits = animator.get_commits("./", branch='master')
    assert isinstance(repo, git.Repo)
    assert len(commits) > 1
    assert isinstance(commits[0], git.Commit) 
Example #2
Source File: scanner.py    From tartufo with GNU General Public License v2.0 6 votes vote down vote up
def __str__(self) -> str:
        output = []
        diff_body = self.printable_diff
        for bad_str in self.strings_found:  # type: ignore
            diff_body = diff_body.replace(bad_str, style_warning(bad_str))
        output.append(self.OUTPUT_SEPARATOR)
        output.append(style_ok("Reason: {}".format(self.issue_type.value)))  # type: ignore
        if self.issue_detail:
            output.append(style_ok("Detail: {}".format(self.issue_detail)))
        if self.diff:
            output.append(style_ok("Filepath: {}".format(self.file_path)))
        if self.branch_name:
            output.append(style_ok("Branch: {}".format(self.branch_name)))
        if self.commit:
            output.append(style_ok("Date: {}".format(self.commit_time)))
            output.append(style_ok("Hash: {}".format(self.commit_hash)))
            output.append(style_ok("Commit: {}".format(self.commit_message)))

        output.append(diff_body)
        output.append(self.OUTPUT_SEPARATOR)
        return "\n".join(output) 
Example #3
Source File: git_repo.py    From allura with Apache License 2.0 6 votes vote down vote up
def new_commits(self, all_commits=False):
        graph = {}

        to_visit = [self._git.commit(rev=hd.object_id) for hd in self.heads]
        while to_visit:
            obj = to_visit.pop()
            if obj.hexsha in graph:
                continue
            if not all_commits:
                # Look up the object
                if M.repository.Commit.query.find(dict(_id=obj.hexsha)).count():
                    graph[obj.hexsha] = set()  # mark as parentless
                    continue
            graph[obj.hexsha] = set(p.hexsha for p in obj.parents)
            to_visit += obj.parents
        return list(topological_sort(graph)) 
Example #4
Source File: git_repo.py    From allura with Apache License 2.0 6 votes vote down vote up
def commit(self, rev):
        '''Return a Commit object.  rev can be _id or a branch/tag name'''
        cache = getattr(c, 'model_cache', '') or M.repository.ModelCache()
        result = cache.get(M.repository.Commit, dict(_id=rev))
        if result is None:
            # find the id by branch/tag name
            try:
                impl = self._git.rev_parse(str(rev) + '^0')
                result = cache.get(M.repository.Commit, dict(_id=impl.hexsha))
            except Exception:
                url = ''
                try:
                    from tg import request
                    url = ' at ' + request.url
                except:
                    pass
                log.exception('Error with rev_parse(%s)%s' %
                              (str(rev) + '^0', url))
        if result:
            result.set_context(self._repo)
        return result 
Example #5
Source File: git_utils.py    From lang2program with Apache License 2.0 6 votes vote down vote up
def commit_diff(c):
    """Return the set of changed files.

    Args:
        c (git.Commit)

    Returns:
        set[str]: a set of file paths (relative to the git repo's root directory).
    """
    changed = set()

    def add_path(blob):
        if blob is not None:
            changed.add(blob.path)

    prev_c = c.parents[0]
    for x in c.diff(prev_c):
        add_path(x.a_blob)
        add_path(x.b_blob)
    return changed 
Example #6
Source File: git_utils.py    From lang2program with Apache License 2.0 6 votes vote down vote up
def commit_diff(c):
    """Return the set of changed files.

    Args:
        c (git.Commit)

    Returns:
        set[str]: a set of file paths (relative to the git repo's root directory).
    """
    changed = set()

    def add_path(blob):
        if blob is not None:
            changed.add(blob.path)

    prev_c = c.parents[0]
    for x in c.diff(prev_c):
        add_path(x.a_blob)
        add_path(x.b_blob)
    return changed 
Example #7
Source File: security.py    From packit with MIT License 5 votes vote down vote up
def get_commit_signature_status(commit: git.Commit) -> "CommitSignatureStatus":
        """Get a signature status from the given commit."""
        signature_mark = CommitVerifier._get_commit_info(commit, pretty_format="%G?")
        return CommitSignatureStatus(signature_mark) 
Example #8
Source File: security.py    From packit with MIT License 5 votes vote down vote up
def _get_commit_info(commit: git.Commit, pretty_format: str) -> str:
        """
        Return a commit information in a given format.

        See `git show --help` and `--pretty=format` for more information.
        """
        try:
            return commit.repo.git.show(commit.hexsha, pretty=f"format:{pretty_format}")
        except git.GitCommandError as error:
            raise PackitException(
                f"Cannot find commit {commit.hexsha!r} to check its signature.", error
            ) 
Example #9
Source File: repository.py    From auto-changelog with MIT License 5 votes vote down vote up
def _init_commit_tags_index(
        repo: Repo, tag_prefix: str, tag_pattern: Optional[str] = None
    ) -> Dict[Commit, List[TagReference]]:
        """ Create reverse index """
        reverse_tag_index = {}
        semver_regex = default_tag_pattern
        for tagref in repo.tags:
            tag_name = tagref.name
            commit = tagref.commit

            consider_tag = False

            # consider & remove the prefix if we found one
            if tag_name.startswith(tag_prefix):
                tag_name = tag_name.replace(tag_prefix, "")

                # if user specified a tag pattern => consider it
                if tag_pattern is not None:
                    if re.fullmatch(tag_pattern, tag_name):
                        consider_tag = True
                # no tag pattern specified by user => check semver semantic
                elif re.fullmatch(semver_regex, tag_name):
                    consider_tag = True

            # good format of the tag => consider it
            if consider_tag:
                if commit not in reverse_tag_index:
                    reverse_tag_index[commit] = []
                reverse_tag_index[commit].append(tagref)
        return reverse_tag_index 
Example #10
Source File: test_repository.py    From auto-changelog with MIT License 5 votes vote down vote up
def test_include_unreleased(mock_ggu, mock_ena, mock_era, mock_repo):
    mock_repo.return_value.iter_commits.return_value = [Mock(spec=Commit), Mock(spec=Commit)]

    repository = GitRepository(".", skip_unreleased=False)
    changelog = repository.generate_changelog()

    assert changelog.releases[0].title == "Unreleased" 
Example #11
Source File: test_repository.py    From auto-changelog with MIT License 5 votes vote down vote up
def test_latest_version(mock_ggu, mock_ena, mock_era, mock_repo):
    mock_repo.return_value.iter_commits.return_value = [Mock(spec=Commit), Mock(spec=Commit)]

    repository = GitRepository(".", latest_version="v1.2.3")
    changelog = repository.generate_changelog()

    assert changelog.releases[0].title == "v1.2.3" 
Example #12
Source File: security.py    From packit with MIT License 5 votes vote down vote up
def is_commit_signature_valid(self, commit: git.Commit) -> bool:
        """
        Check the validity of the commit signature.
        Key needs to be already present.
        """
        commit_status = self.get_commit_signature_status(commit)
        if commit_status in VALID_SIGNATURE_STATUSES:
            logger.debug(f"Commit {commit.hexsha!r} signature is valid.")
            return True

        logger.warning(f"Commit {commit.hexsha!r} signature is not valid.")
        return False 
Example #13
Source File: security.py    From packit with MIT License 5 votes vote down vote up
def check_signature_of_commit(
        self, commit: git.Commit, possible_key_fingerprints: List[str]
    ) -> bool:
        """
        Check the validity of the commit signature
        and test if the signer is present in the provided list.
        (Commit without signature returns False.)
        """
        status = self.get_commit_signature_status(commit=commit)
        if status == CommitSignatureStatus.no_signature:
            logger.debug("Commit not signed.")
            return False

        if status == CommitSignatureStatus.cannot_be_checked:
            # We need to download keys before getting the signer
            for key in possible_key_fingerprints:
                self.download_gpg_key_if_needed(key_fingerprint=key)

        signer = self.get_commit_signer_fingerprint(commit)

        if not signer:
            logger.debug("Cannot get a signer of the commit.")
            return False

        if signer not in possible_key_fingerprints:
            logger.warning("Signature author not authorized.")
            return False

        is_valid = self.is_commit_signature_valid(commit)
        if not is_valid:
            logger.warning(f"Commit {commit.hexsha!r} signature is not valid.")
        return is_valid 
Example #14
Source File: repo_hist.py    From llvm-premerge-checks with Apache License 2.0 5 votes vote down vote up
def __init__(self, commit: git.Commit):
        self.commit = commit
        self.chash = commit.hexsha  # type: str
        self.author = hash(commit.author.email + MyCommit.SALT)  # type: int
        self.author_domain = commit.author.email.rsplit("@")[-1].lower()  # type: str
        self.commiter = hash(commit.committer.email.lower() + MyCommit.SALT)  # type:int
        self.summary = commit.summary  # type: str
        self.date = datetime.datetime.fromtimestamp(
            commit.committed_date)  # type: datetime.datetime
        self.phab_revision = self._get_revision(commit)  # type: Optional[str]
        self.reverts = None   # type: Optional[MyCommit]
        self.reverted_by = None   # type: Optional[MyCommit]
        self._diff_index = None  # type: Optional[git.DiffIndex] 
Example #15
Source File: repo_hist.py    From llvm-premerge-checks with Apache License 2.0 5 votes vote down vote up
def _get_revision(commit: git.Commit) -> Optional[str]:
        m = REVISION_REGEX.search(commit.message)
        if m is None:
            return None
        return m.group(1) 
Example #16
Source File: gitutil.py    From cc-utils with Apache License 2.0 5 votes vote down vote up
def index_to_commit(self, message, parent_commits=None):
        '''moves all diffs from worktree to a new commit without modifying branches.
        The worktree remains unchanged after the method returns.

        @param parent_commits: optional iterable of parent commits; head is used if absent
        @return the git.Commit object representing the newly created commit
        '''
        if not parent_commits:
            parent_commits = [self.repo.head.commit]
        # add all changes
        git.cmd.Git(self.repo.working_tree_dir).add('.')
        tree = self.repo.index.write_tree()

        if self.github_cfg:
            credentials = self.github_cfg.credentials()
            author = git.objects.util.Actor(credentials.username(), credentials.email_address())
            committer = git.objects.util.Actor(credentials.username(), credentials.email_address())

            create_commit = functools.partial(
                git.Commit.create_from_tree,
                author=author,
                committer=committer,
            )
        else:
            create_commit = git.Commit.create_from_tree

        commit = create_commit(
            repo=self.repo,
            tree=tree,
            parent_commits=parent_commits,
            message=message
        )
        self.repo.index.reset()
        return commit 
Example #17
Source File: patches.py    From packit with MIT License 5 votes vote down vote up
def get_commits_since_ref(
        self,
        git_ref: str,
        add_upstream_head_commit: bool = True,
        no_merge_commits: bool = True,
    ) -> List[git.Commit]:
        """
        Return a list of different commits between HEAD and selected git_ref

        :param git_ref: get commits since this git ref
        :param add_upstream_head_commit: add also upstream rev/tag commit as a first value
        :param no_merge_commits: do not include merge commits in the list if True
        :return: list of commits (last commit on the current branch.).
        """

        if is_a_git_ref(repo=self.lp.git_repo, ref=git_ref):
            upstream_ref = git_ref
        else:
            upstream_ref = f"origin/{git_ref}"
            if upstream_ref not in self.lp.git_repo.refs:
                raise Exception(
                    f"Upstream {upstream_ref!r} branch nor {git_ref!r} tag not found."
                )

        commits = list(
            self.lp.git_repo.iter_commits(
                rev=f"{git_ref}..{self.lp.ref}",
                reverse=True,
                no_merges=no_merge_commits,  # do not include merge commits in the list
            )
        )
        if add_upstream_head_commit:
            commits.insert(0, self.lp.git_repo.commit(upstream_ref))

        logger.debug(f"Delta ({upstream_ref}..{self.lp.ref}): {len(commits)}")
        return commits 
Example #18
Source File: patches.py    From packit with MIT License 5 votes vote down vote up
def are_child_commits_contained(self, git_ref: str) -> bool:
        r"""
        Magic begins here.

        `git format-patch` produces patches which cannot be applied when commits,
        in front of a git ref, have parents behind:

        * | | | | | | | |   ea500ac513 (tag: v245) Merge pull request #15...
        |\ \ \ \ \ \ \ \ \
        | * | | | | | | | | 0d5aef3eb5 hwdb: update for v245
        | | |_|_|_|_|_|/ /
        | |/| | | | | | |
        * | | | | | | | | 03985d069b NEWS: final contributor update for v245

        In this example, you can see that ea500 is tagged with 245 and
        is a merge commit. The additional lines mean that child commits of v245
        have parents behind v245 which means that `git format-patch` may
        create patches which may not able able to be applied.

        This method detects the situation described above.

        :param git_ref: git ref to check
        :return: yes if all child commits of the selected git ref are contained
                 within the set of git_ref children commits
        """
        commits = self.get_commits_since_ref(
            git_ref, add_upstream_head_commit=True, no_merge_commits=False
        )
        for commit in islice(commits, 1, None):  # 0 = upstream, don't check that one
            for parent_commit in commit.parents:
                if parent_commit not in commits:
                    logger.info(f"Commit {commit!r} has a parent behind {git_ref!r}.")
                    return False
        logger.debug(f"All commits are contained on top of {git_ref!r}.")
        return True 
Example #19
Source File: release.py    From tox with MIT License 5 votes vote down vote up
def release_changelog(repo: Repo, version: Version) -> Commit:
    print("generate release commit")
    check_call(["towncrier", "--yes", "--version", version.public], cwd=str(ROOT_SRC_DIR))
    release_commit = repo.index.commit(f"release {version}")
    return release_commit 
Example #20
Source File: scanner.py    From tartufo with GNU General Public License v2.0 5 votes vote down vote up
def diff_worker(
    diff: git.DiffIndex,
    custom_regexes: Optional[Dict[str, Pattern]],
    do_entropy: bool,
    do_regex: bool,
    path_inclusions: Optional[Iterable[Pattern]],
    path_exclusions: Optional[Iterable[Pattern]],
    prev_commit: Optional[git.Commit] = None,
    branch_name: Optional[str] = None,
) -> List[Issue]:
    issues = []  # type: List[Issue]
    for blob in diff:
        printable_diff = blob.diff.decode("utf-8", errors="replace")
        if printable_diff.startswith("Binary files"):
            continue
        if not path_included(blob, path_inclusions, path_exclusions):
            continue
        found_issues = []  # type: List[Issue]
        if do_entropy:
            entropy_issue = find_entropy(printable_diff)
            if entropy_issue:
                found_issues.append(entropy_issue)
        if do_regex:
            found_issues += find_regex(printable_diff, custom_regexes)
        for finding in found_issues:
            finding.diff = blob
            finding.commit = prev_commit
            finding.branch_name = branch_name
        issues += found_issues
    return issues 
Example #21
Source File: git_repository.py    From pydriller with Apache License 2.0 5 votes vote down vote up
def get_commit_from_gitpython(self, commit: GitCommit) -> Commit:
        """
        Build a PyDriller commit object from a GitPython commit object.
        This is internal of PyDriller, I don't think users generally will need
        it.

        :param GitCommit commit: GitPython commit
        :return: Commit commit: PyDriller commit
        """
        return Commit(commit, self._conf) 
Example #22
Source File: commit.py    From pydriller with Apache License 2.0 5 votes vote down vote up
def __init__(self, commit: GitCommit, conf) -> None:
        """
        Create a commit object.

        :param commit: GitPython Commit object
        :param conf: Configuration class
        """
        self._c_object = commit

        self._modifications = None
        self._branches = None
        self._conf = conf