This question is quite old, but I came across the same problem, so here's my solution:
import git
import shutil
url = 'ssh://url-to.my/repo.git'
remote_ref = 'master'
tmprepo = 'temprepo'
tarball = 'contents.tar'
try:
repo = git.Repo.init(tmprepo)
repo.create_remote('origin', url)
repo.remote().fetch(remote_ref)
with open(tarball, 'wb') as f:
repo.archive(f, f'remotes/origin/{remote_ref}', path=None)
print('Success')
finally:
shutil.rmtree(tmprepo)
A few notes:
- This solution creates a temporary repository, fetches the requested remote ref and archives it. Ideally we wouldn't need to have all these extra steps, but I wasn't able to find a better solution. Please suggest improvements!
- Set the
path
parameter to something meaningful in case you only want to include a subset of the directory
- Because we don't require any history whatsoever, the
fetch()
call can probably be optimized. The **kwargs
taken by the functions may help here (see man git-fetch
)