Skip to content Skip to sidebar Skip to footer

Find The Root Of The Git Repository Where The File Lives

When working in Python (e.g. running a script), how can I find the path of the root of the git repository where the script lives? So far I know I can get the current path with: pat

Solution 1:

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

defget_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")

Solution 2:

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

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

Solution 3:

Looking for a .git directory will not work in all cases. The correct git command is:

git rev-parse --show-toplevel

Solution 4:

I just wrote a small python module for this task: https://github.com/MaxNoe/python-gitpath

Install with pip install git+https://github.com/maxnoe/python-gitpath

Usage:

import gitpath

print(gitpath.root())
print(gitpath.abspath('myfile.txt'))

gitpath.abspath(relative_path) will return the absolute path on your machine for a path given relative to the root of the git repository.

The code to get the root is partially derived from Ryne Everetts comment:

from subprocess import check_output, CalledProcessError
from functools import lru_cache

@lru_cache(maxsize=1)defroot():
    ''' returns the absolute path of the repository root '''try:
        base = check_output('git rev-parse --show-toplevel', shell=True)
    except CalledProcessError:
        raise IOError('Current working directory is not a git repository')
    return base.decode('utf-8').strip()

The caching makes the second call to root() ca. 3500 times faster (measured with ipython and %%timeit)

Solution 5:

This function is generic (not depending on external module or calling git command). It searches up from a given path to find the first one containing a .git directory.

deffind_vcs_root(test, dirs=(".git",), default=None):
    import os
    prev, test = None, os.path.abspath(test)
    while prev != test:
        ifany(os.path.isdir(os.path.join(test, d)) for d in dirs):
            return test
        prev, test = test, os.path.abspath(os.path.join(test, os.pardir))
    return default

Example use:

import os
print(find_vcs_root(os.path.dirname(__file__)))

Or check for other version control:

import os
print(find_vcs_root(os.path.dirname(__file__)), dirs=(".hg", ".git", ".svn"))

Post a Comment for "Find The Root Of The Git Repository Where The File Lives"