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

I am trying to rename some committers in a git repository using git filter-branch

. I'd really like to use more complex logic, but I don't really understand bash. The working (working) script I am currently using looks like this:

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


if [ $cn = "ew" ]

' -- --all


Is it possible to use a python script as an argument --env-filter

? If so, how do I get $GIT_COMMITTER_NAME

read / write access ?

How would I make the equivalent of this bash line in a python file?


source to share

1 answer

In python you need import os

followed os.environ

by a dictionary with an input environment. Changes to are os.environ

exported automatically. The real problem is that the git --filter- * filters are being executed as it says:

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

So it does use a shell, and if you have a shell, Python is called, you are terminated by a shell sub-process, and any changes made in the Python process will not affect that shell. You should eval

output the Python script file:

eval `python`


where outputs the corresponding commands export


import os

def example():
    cn = os.environ['GIT_COMMITTER_NAME']
    cm = os.environ['GIT_COMMITTER_EMAIL']
    if cn == 'ew':
        cn = 'Eric'
        cm = ''
    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).



All Articles