0

Within a python script which I would like to be able to execute from some arbitrary location within a git repositories working tree, in some arbitrary git repository, and I would like to use GitPython to extract some information about said repository.

I can get the information I need from the Repo object, but I can't figure out how to open a Repo object , but the Repo constructor requires a path to repo-root.

Is there a way to construct a Repo object with a path to somewhere in the repo, not just the repo-root location? Alternatively is there a way to query the location of repo root for a given path?

I'm looking for something like:

import git
r = git.Repo('whatever repo the cwd is in')

The following works, but I find it hopelessly clunky:

import git
import subprocess

rtpath = subprocess.check_output(["git", "rev-parse", "--show-toplevel"])
repo = git.Repo(rtpath.strip())
Spacemoose
  • 3,856
  • 1
  • 27
  • 48
  • Please rephrase what you're trying to do, and where you get stuck. Currently your problem is extremely unclear. – Joost Feb 03 '16 at 13:34

1 Answers1

0

One option would be to implement the same search semantics that git implements internally...e.g., look for .git directory, if it doesn't exist, chdir up one level, check again, etc. Something like:

import os
import git

lastcwd=os.getcwd()
while not os.path.isdir('.git'):
    os.chdir('..')
    cwd=os.getcwd()
    if cwd == lastcwd:
        raise OSError('no .git directory')
    lastcwd=cwd

r = git.Repo('.')

The above code is simplistic; for example, git won't traverse over a filesystem boundary in it's default configuration, while the above code will always iterate all the way up to /.

larsks
  • 277,717
  • 41
  • 399
  • 399