49

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?

8 Answers 8

49

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")
2
  • 5
    This one did the trick for me. Useful to use os.getcwd() instead of "/path/to/your/file" when calling this function. Thanks.
    – Tom Wojcik
    Nov 22, 2017 at 10:06
  • 13
    Once you have the repo you can just use git_repo.working_dir Jan 16, 2018 at 4:05
45

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
2
  • 5
    This is the correct answer, as it doesn't rely on the shell which doesn't work well across platforms. Sep 19, 2018 at 20:25
  • 2
    If you want to support bare repositories, use working_dir instead. May 8, 2022 at 22:02
30

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

git rev-parse --show-toplevel
7
  • 16
    Note to Future Self: repo_dir = subprocess.Popen(['git', 'rev-parse', '--show-toplevel'], stdout=subprocess.PIPE).communicate()[0].rstrip().decode('utf-8') Jan 29, 2015 at 3:57
  • @RyneEverett thanks for that, FYI it threw LookupError: unknown encoding: utf-8 for me in 2.7.6, I had to remove the .decode('utf-8')
    – qneill
    Sep 2, 2016 at 19:35
  • 2
    Just wondering, in what cases would looking for a .git directory not work? Apr 24, 2018 at 10:39
  • @danodonovan fatal: Not a git repository (or any of the parent directories): .git
    – moooeeeep
    Jul 1, 2019 at 6:54
  • 3
    @danodonovan you can have a .git file not a directory if you have a worktree checkout.
    – Meitham
    Apr 13, 2021 at 12:08
11

Without any external libraries:

import subprocess

def getGitRoot():
    return subprocess.Popen(['git', 'rev-parse', '--show-toplevel'], stdout=subprocess.PIPE).communicate()[0].rstrip().decode('utf-8')
1
  • 4
    I turned this answer into a one-function-python package, which is available via pip (pip install git_root) and conda (conda install -c conda-forge git_root): see github.com/jtilly/git_root @rouble I hope this is okay with you!
    – jtilly
    Mar 1, 2019 at 10:59
8

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)
def root():
    ''' 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)

4
  • See also stackoverflow.com/questions/35948875/…
    – qneill
    Sep 2, 2016 at 19:30
  • 1
    Deserves to be on pypi!
    – nowox
    Nov 8, 2016 at 9:12
  • As @CivFan pointed out - GitPython now provides this with Reop(...,search_parent_directories)
    – qneill
    Feb 5, 2019 at 3:52
  • Note: This does not work from a submodule
    – Sigmatics
    Aug 4, 2023 at 10:05
7

I found the other answers too confusing for the task so I made this function to solve the issue. Basically, it loops through the parent directories of the given path and returns the first one that contains ".git" directory. If none found, None is returned.

from pathlib import Path

def find_repo(path):
    "Find repository root from the path's parents"
    for path in Path(path).parents:
        # Check whether "path/.git" exists and is a directory
        git_dir = path / ".git"
        if git_dir.is_dir():
            return path

# Find the repo root where the script is
find_repo(__file__)

Pathlib is part of the standard library (Python 3) so there is no extra dependencies. Gitpython is overkill if this is the only thing you need from it.

6

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.

def find_vcs_root(test, dirs=(".git",), default=None):
    import os
    prev, test = None, os.path.abspath(test)
    while prev != test:
        if any(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"))
2
  • 1
    Thanks, exactly what I was looking for since I can't install packages where I run my scripts
    – RonK
    Aug 9, 2017 at 14:35
  • Great. easy implemented.
    – Hillborn
    Apr 1, 2020 at 6:29
0

I do not know much about python, but I think you could keep going down a directory with

os.path.abspath(os.path.join(dir, '..'))

Until you detect a .git directory (os.walk might help)

2
  • Thanks, but the file is deep inside the git repository, so the walk (at least as it is) would fail, and simply going up many levels and running the walk again is not guaranteed to find the closest .git ancestor. Feb 27, 2014 at 21:57
  • You'll have to walk from the bottom and up. Look for a .git directory in the current directory, if not chop off the last directory component and try again. Do so recursively until you hit a boundary (e.g. the file system's root directory) Feb 27, 2014 at 22:02

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.