GitPython get all commits in range between start sha1 and end sha1

Viewed 688

I am using the GitPython library and was wondering how to get all commits on a branch in range of two commit sha-1's. I have the start one and end one. Is there any way to get list of them?

I have instantiated the repo object and was wondering if there was a way to query it and obtain a list of commits in the range of two shas?

Would be looking to do something similar to this command but return them as a list:

git log e0d8a4c3fec7ef2c352342c2ffada21fa07c1dc..63af686e626e0a5cbb0508367983765154e188ce --pretty=format:%h,%an,%s > commits.csv

Seems like there is Repo.iter_commits() method but can't see how to specify a range.

1 Answers

@shlomi33 here was my solution:

This is the method that I used to set a List of GitPyhton Commit Object. Within the class I have already instantiated the Repo object which this method relies on.

Edit: have also added the init method that is used to set up the Repo object instance.

def __init__(self, repo_url, project_name, branch_name) -> None:
    """
    Clone the required repo in the repo folder and instantiate the Repo instance
    :param repo_url: str of the git repository url
    :param project_name: str of the project name
    :param branch_name: str of the branch name
    """
    self._repo_url = repo_url
    self._project = project_name
    self._branch = branch_name
    self._project_dir = Path(self._repo_dir, self._project)

    if self._project_dir.exists():
        self._logger.info('Deleting existing repo: ' + str(self._project_dir))
        shutil.rmtree(self._project_dir)

    self._logger.info('Creating directory for repo: ' + str(self._project_dir))
    os.makedirs(self._project_dir)

    try:
        self.repo = GitRepo.clone_from(self._repo_url, self._project_dir, branch=self._branch,
                                       progress=self.__progress)
    except GitCommandError:
        self._logger.error('Failed to clone repo. Make sure you have git ssh access set up.')
        raise
    self._logger.info('Repository downloaded to: ' + str(self._repo_dir))

def set_commits(self, start_rev: str, end_rev: str):
    """
    Sets a list of Commits for the range of the start rev and end rev
    :param start_rev: Start commit revision SHA1
    :param end_rev: End commit revision
    """
    self._start_rev = start_rev
    self._end_rev = end_rev
    commits = self.repo.iter_commits(start_rev + '..' + end_rev)
    self._commits = list(map(Commit, list(commits)))
Related