如何获取文件相对于 Git 存储库根目录的路径?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16951267/
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
How to get the path of a file relative to the Git repository root?
提问by Jo Liss
Example:
例子:
$ cd lib
$ git absolute-path test.c # how to do this?
lib/test.c
采纳答案by Jo Liss
As of at least git 1.6.0, use ls-files
:
至少从 git 1.6.0 开始,使用ls-files
:
$ cd lib
$ git ls-files --full-name test.c
lib/test.c
For older git, use git ls-tree
:
对于较旧的 git,请使用git ls-tree
:
$ cd lib
$ git ls-tree --full-name --name-only HEAD test.c
lib/test.c
This only works for files that have been committed into the repo, but it's better than nothing.
这仅适用于已提交到 repo 中的文件,但总比没有好。
回答by gmatht
Pasting the following into your bash terminal will work, regardless of whether "test.c" currently exists or not. You can copy the git-absolute-path function into your .bashrc file for future convenience.
无论“test.c”当前是否存在,将以下内容粘贴到您的 bash 终端都将起作用。您可以将 git-absolute-path 函数复制到您的 .bashrc 文件中以方便日后使用。
git-absolute-path () {
fullpath=$([[ = /* ]] && echo "" || echo "$PWD/${1#./}")
gitroot="$(git rev-parse --show-toplevel)" || return 1
[[ "$fullpath" =~ "$gitroot" ]] && echo "${fullpath/$gitroot\//}"
}
git-absolute-path test.c