Find the root of the git repository where the file lives

The GitPython module provides this attribute right out-of-the-box for you:

import git

repo = git.Repo('.', search_parent_directories=True)
repo.working_tree_dir

Use the GitPython module http://gitpython.readthedocs.io/en/stable/.

pip install gitpython

Assume you have a local Git repo at /path/to/.git. The below example receives /path/to/your/file as input, it correctly returns the Git root as /path/to/.

import git

def get_git_root(path):

        git_repo = git.Repo(path, search_parent_directories=True)
        git_root = git_repo.git.rev_parse("--show-toplevel")
        print git_root

if __name__ == "__main__":
    get_git_root("/path/to/your/file")

Tags:

Python

Git