Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a python script as the filter for git filter-branch

Tags:

git

python

bash

I'm trying to rename some committers in a git repository, using git filter-branch. I'd quite like to use some more complex logic, but I don't really understand bash. The (working) script I'm currently using looks like this:

git filter-branch -f --tag-name-filter cat --env-filter '

cn="$GIT_COMMITTER_NAME"
cm="$GIT_COMMITTER_EMAIL"

if [ $cn = "ew" ]
then
    cn="Eric"
    cm="[email protected]"
fi

export GIT_COMMITTER_NAME="$cn"
export GIT_COMMITTER_EMAIL="$cm"
' -- --all

Is it possible for me to use a python script as the --env-filter argument? If so, how would I get access to $GIT_COMMITTER_NAME to read and write it?

How would I do the equivalent of that bash string in a python file?

like image 484
Eric Avatar asked Mar 13 '12 21:03

Eric


1 Answers

In python, you need to import os, after which os.environ is a dictionary with the incoming environment in it. Changes to os.environ are exported automatically. The real problem here is that git's --filter-* filters are run, as it says:

always evaluated in the shell context using the eval command (with the notable exception of the commit filter, for technical reasons).

So it's actually using the shell, and if you have the shell invoke Python, you wind up with a subprocess of the shell and any changes made in the Python process do not affect that shell. You'd have to eval the output of a Python script:

eval `python foo.py`

where foo.py outputs the appropriate export commands:

import os

def example():
    cn = os.environ['GIT_COMMITTER_NAME']
    cm = os.environ['GIT_COMMITTER_EMAIL']
    if cn == 'ew':
        cn = 'Eric'
        cm = '[email protected]'
    print ('export GIT_COMMITTER_NAME="%s"' % cn)
    print ('export GIT_COMMITTER_EMAIL="%s"' % cm)

example() # or if __name__ == '__main__', etc.

(all of the above is untested).

like image 115
torek Avatar answered Oct 22 '22 06:10

torek