【发布时间】:2013-06-01 19:44:30
【问题描述】:
例子:
$ cd lib
$ git absolute-path test.c # how to do this?
lib/test.c
【问题讨论】:
-
“绝对路径”和“相对于回购”似乎相互矛盾?
例子:
$ cd lib
$ git absolute-path test.c # how to do this?
lib/test.c
【问题讨论】:
至少从 git 1.6.0 开始,使用 ls-files:
$ cd lib
$ git ls-files --full-name test.c
lib/test.c
对于较旧的 git,请使用 git ls-tree:
$ cd lib
$ git ls-tree --full-name --name-only HEAD test.c
lib/test.c
这仅适用于已提交到 repo 的文件,但总比没有好。
【讨论】:
test.c 是相对于当前工作目录的路径。因此,它们适用于当您已经知道文件的位置,但您想将路径转换为相对于 repo 根目录的“绝对”路径时。如果您尝试搜索整个存储库以查找名为test.c 的文件,我建议运行cd "$(git rev-parse --show-toplevel)"; git ls-files --full-name '*/test.c' 'test.c'。请注意引号以防止您的 shell 插入星号。
无论“test.c”当前是否存在,都可以将以下内容粘贴到您的 bash 终端中。您可以将 git-absolute-path 函数复制到您的 .bashrc 文件中以方便日后使用。
git-absolute-path () {
fullpath=$([[ $1 = /* ]] && echo "$1" || echo "$PWD/${1#./}")
gitroot="$(git rev-parse --show-toplevel)" || return 1
[[ "$fullpath" =~ "$gitroot" ]] && echo "${fullpath/$gitroot\//}"
}
git-absolute-path test.c
【讨论】:
为了获取当前目录的路径,相对于 git root,我最终这样做了:
if gitroot=$(git rev-parse --show-toplevel 2>/dev/null); then
directory=$(realpath --relative-to="$gitroot" .)
fi
(我假设是 Bash,但我不知道它的便携性。)
【讨论】: