Search code examples
pythongitgitpython

Git Python log with grep


On command line I am running

git log \
    --merges \
    --grep='^Merge pull request .* in repo/foo from' \
    --grep='^Merged .* to master' \
    tag1..tag2

This gives me a list of merge commits to master between the two given tags.

Now I am struggling getting the same from GitPython.

What I have tried so far:

git.Git(os.getcwd()).log(
    '--merges',
    '--grep="^Merge pull request .* in repo/foo from"',
    '--grep="^Merged .* to master"',
    'tag1..tag2')

This works only if I remove the grep lines. With grep it returns an empty string. Same behaviour here:

git.Git(os.getcwd()).execute(['git', 'log',
    '--merges',
    '--grep="^Merge pull request .* in repo/foo from"',
    '--grep="^Merged .* to master"',
    'tag1..tag2'])

Another thing I tried:

git.repo.fun.rev_parse(repo=git.Repo(), rev='tag1..tag2')

This errors out with BadName because the tag1..tag2 doesn't resolve to an object.


Solution

  • The quotes are required by the shell to prevent it from interpreting metacharacters in the strings; but here, you have no shell.

    git.Git(os.getcwd()).execute(['git', 'log',
        '--merges',
        '--grep=^Merge pull request .* in repo/foo from',
        '--grep=^Merged .* to master',
        'tag1..tag2'])
    

    I'm guessing you could also replace os.getcwd() with simply '.'.