找到文件所在的 git 存储库的根目录
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22081209/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Find the root of the git repository where the file lives
提问by Amelio Vazquez-Reina
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?
在 Python 中工作(例如运行脚本)时,如何找到脚本所在的 git 存储库根目录的路径?
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 存储库所在的位置?
采纳答案by quat
Use the GitPython module http://gitpython.readthedocs.io/en/stable/.
使用 GitPython 模块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/
.
假设您在/path/to/.git
. 下面的示例接收/path/to/your/file
作为输入,它正确地将 Git 根返回为/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")
回答by michas
Looking for a .git
directory will not work in all cases. The correct git command is:
查找.git
目录并非在所有情况下都有效。正确的 git 命令是:
git rev-parse --show-toplevel
回答by CivFan
回答by MaxNoe
I just wrote a small python module for this task: https://github.com/MaxNoe/python-gitpath
我刚刚为这个任务写了一个小的 python 模块:https: //github.com/MaxNoe/python-gitpath
Install with pip install git+https://github.com/maxnoe/python-gitpath
安装 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.
gitpath.abspath(relative_path)
将返回您机器上相对于 git 存储库根目录给出的路径的绝对路径。
The code to get the root is partially derived from Ryne Everetts comment:
获取根的代码部分源自 Ryne Everetts 的评论:
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
)
缓存对root()
ca进行第二次调用。快 3500 倍(用ipython
和测量%%timeit
)
回答by ideasman42
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.
这个函数是通用的(不依赖于外部模块或调用git
命令)。它从给定的路径向上搜索以找到第一个包含.git
目录的路径。
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"))
回答by rouble
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')
回答by PlasmaPower
I do not know much about python, but I think you could keep going down a directory with
我对 python 了解不多,但我认为你可以继续浏览一个目录
os.path.abspath(os.path.join(dir, '..'))
Until you detect a .git
directory (os.walk
might help)
直到您检测到.git
目录(os.walk
可能会有所帮助)