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())
1
  • Please rephrase what you're trying to do, and where you get stuck. Currently your problem is extremely unclear. Commented Feb 3, 2016 at 13:34

2 Answers 2

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 /.

Sign up to request clarification or add additional context in comments.

Comments

0

I just came here looking for the same thing. It seems if you set the parameter search_parent_directories=True of git.Repo() you do not need to specify the root folder of the repo but can use any subdirectory, e.g. if you use os.path.dirname(os.path.realpath(__file__)) for some file deeper within the folder structure

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.