Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the root of the git repository where the file lives

Tags:

git

python

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?

like image 734
Amelio Vazquez-Reina Avatar asked Feb 27 '14 21:02

Amelio Vazquez-Reina


People also ask

How do I find my git root directory?

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

Where is the root of a repository?

The repository root directory is the parent directory of the . hg directory. Mercurial stores its internal data structures – the metadata – inside that . hg directory.

What is root in git?

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.


2 Answers

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") 
like image 138
quat Avatar answered Oct 05 '22 00:10

quat


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 
like image 32
CivFan Avatar answered Oct 05 '22 00:10

CivFan