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:
path_to_containing_folder = os.path.dirname(os.path.realpath(__file__))
How can I then find out where the git repository lives?
--git-dir Show $GIT_DIR if defined else show the path to the . git directory. You can see it in action in this git setup-sh script. If you are using git rev-parse --show-toplevel , make sure it is with Git 2.25+ (Q1 2020).
The repository root directory is the parent directory of the . hg directory. Mercurial stores its internal data structures – the metadata – inside that . hg directory.
a . git directory at the root of the working tree; a <project>. git directory that is a bare repository (i.e. without its own working tree), that is typically used for exchanging histories with others by pushing into it and fetching from it.
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")
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With