Find the root of the git repository where the file lives
git, python
Solution
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")
Problem
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?