fastgit

Use git from python, fast

fastgit is a Python wrapper for the git command line, for use in scripts and interactive sessions. You call git subcommands as Python methods and pass options as keyword arguments.

Commands run through the installed git executable and return its text output. There is no separate object model for repositories and commits. Both synchronous and asynchronous clients are available.

Usage

Installation

Install latest from pypi

$ pip install fastgit

How to use

Create a Git object for the directory you want to work in. Every command runs in that directory. Results have leading and trailing whitespace stripped:

import shutil, tempfile
td = tempfile.mkdtemp()
g = Git(td)
g.init(b='main')
'Initialized empty Git repository in /private/var/folders/51/b2_szf2945n072c0vj2cyty40000gn/T/tmp8zyj76q7/.git/'
(g.d/'.gitignore').mk_write('*.bak')
g.add('.gitignore')
g.commit(m='add .gitignore')
'[main (root-commit) 5113ce1] add .gitignore\n 1 file changed, 1 insertion(+)\n create mode 100644 .gitignore'

Keyword arguments become command-line options:

  • Single-letter names produce short options, such as n=1 for -n 1.
  • Longer names produce long options, with underscores replaced by dashes.
  • A value of True passes the flag without a value.
g.log(n=1, oneline=True)
'5113ce1 add .gitignore'

You can also pass path arguments after -- using the __ parameter:

g.log('--oneline', __=['.gitignore'])
'5113ce1 add .gitignore'

Frequent queries are properties:

g.current_branch, g.commits
('main', ['5113ce1 add .gitignore'])

Command output is returned in a str subclass with the exit code in .returncode. A failed command prints git’s message and returns None. Pass raise_exc=True to raise an exception instead. You can set this per call or when creating the client.

Some git commands use exit code 1 for a negative result. For example, grep returns 1 when nothing matches. fastgit returns the output for these results without treating them as failures:

res = g.grep('missing')
res.returncode
1

Pass sync=False for an async client. Its commands and properties return awaitables. Waiting for git does not block the event loop:

ag = Git(td, sync=False)
await ag.last_commit
'add .gitignore'