Search code examples
pythonpython-3.xgitgitpython

How to call rev_list with GitPython


This program fails

import git

repo = git.repo.Repo('..')
res = repo.git.rev_list('--since="2024-01-01" master').split('\n')

with the following error

git.exc.GitCommandError: Cmd('git') failed due to: exit code(129)
cmdline: git rev-list --since="2024-01-01" master
stderr: 'usage: git rev-list [<options>] <commit>... [--] [<path>...]

despite that the command git rev-list --since="2024-01-01" master works just fine from the command line.

Any ideas how to fix it?


Solution

  • I believe you are misuing the repo.git.rev_list method. The first argument is meant to be a branch name (or other commit reference). You are effectively running the command:

    ['git', 'rev-list', '--since="2024-01-01" master']
    

    Which is to say, you're looking for a branch or other reference with the literal name --since="2024-01-01" master. You should get the result you expect if you spell the command like this:

    res = repo.git.rev_list("master", since="2024-01-01").split('\n')
    

    Although on my system I had to be explicit and use refs/heads/master to avoid a warning: refname 'master' is ambiguous. message from git.


    Instead of using git rev-list, you could also do this entirely using the GitPython API:

    import git
    from datetime import datetime
    
    repo = git.repo.Repo('.')
    d =datetime.strptime('2024-01-01', '%Y-%m-%d')
    ts = int(d.timestamp())
    commits = [
      commit for commit in repo.iter_commits('refs/heads/master')
      if commit.committed_date > d.timestamp()
    ]
    

    Or if you want just the hex sha values:

    commits = [
      commit.hexsha for commit in repo.iter_commits('refs/heads/master')
      if commit.committed_date > d.timestamp()
    ]