找到文件所在的git存储库的根目录 [英] Find the root of the git repository where the file lives

查看:595
本文介绍了找到文件所在的git存储库的根目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python中工作(例如运行脚本)时,如何才能找到脚本所在的git存储库根目录?

到目前为止,我知道我可以得到当前路径:

$ p $ path_to_containing_folder = os.path.dirname(os.path.realpath(__ file__))

然后我怎么才能知道git仓库在哪里?

解决方案

使用GitPython模块 http:// gitpython.readthedocs.io/en/stable/

  pip install gitpython 
/path/to/.git
处有一个本地Git仓库。下面的例子接收到 / path / to / your / file 作为输入,它将Git根正确地返回为 / path / to /

  import git 

def get_git_root(路径):

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)


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?

解决方案

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

这篇关于找到文件所在的git存储库的根目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆