Skip to content
Advertisement

Configure GitPython to output/log commands and process output

I’m using GitPython to run several simple commands against repos. Essentially most of it is just:

repo = Repo(repo_dir)
repo.git.fetch()
result = repo.git.diff("origin", name_only=True)
repo.git.merge()
# ...

Is there some way to setup GitPython to output/log the commands that are run, and also display the raw output they produce?

For example, the above I would expect to be something along the lines of:

$ git fetch
$ git diff --name-only origin
path/to/differing_file
path/to/another/differing_file
$ git merge

Advertisement

Answer

GitPython uses the module logging. By adding logging.basicConfig(level=logging.DEBUG) before your code, it prints logs like

DEBUG:git.cmd:Popen(['git', 'fetch'], cwd=E:pathfoo, universal_newlines=False, shell=None)

If you want it to print formatted logs as you expect, you could modify GitPython‘s source code. I’m using Python 2.7 and my GitPython is installed at C:Python27libsite-packagesgit. You can run git.__file__ in REPL to find your installation directory. In the file C:Python27libsite-packagesgitcmd.py, you can find a method def execute. It calls subprocess.Popen to run the command. You can modify the line log.debug before Popen or just insert print(' '.join(cmd)) at a proper line. If you are using Python 3.3 or newer, you could also refer to this answer on how to print the command with subprocess.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement