【问题标题】:How to get the path of a file relative to the Git repository root?如何获取相对于 Git 存储库根目录的文件路径?
【发布时间】:2013-06-01 19:44:30
【问题描述】:

例子:

$ cd lib
$ git absolute-path test.c # how to do this?
lib/test.c

【问题讨论】:

  • “绝对路径”和“相对于回购”似乎相互矛盾?

标签: git path


【解决方案1】:

至少从 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 的文件,但总比没有好。

【讨论】:

  • 我必须使用通配符,否则找不到文件,除非它位于 repo 的根目录中。使用 $ git ls-files --full-name *test.c
  • @PedroGarcíaMedina 我发布的两个命令都期望test.c 是相对于当前工作目录的路径。因此,它们适用于当您已经知道文件的位置,但您想将路径转换为相对于 repo 根目录的“绝对”路径时。如果您尝试搜索整个存储库以查找名为test.c 的文件,我建议运行cd "$(git rev-parse --show-toplevel)"; git ls-files --full-name '*/test.c' 'test.c'。请注意引号以防止您的 shell 插入星号。
【解决方案2】:

无论“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

【讨论】:

  • Mac OS X "readlink" 没有 -f (我认为是 *BSD)。关于便携方式的建议?
【解决方案3】:

为了获取当前目录的路径,相对于 git root,我最终这样做了:

if gitroot=$(git rev-parse --show-toplevel 2>/dev/null); then
    directory=$(realpath --relative-to="$gitroot" .)
fi

(我假设是 Bash,但我不知道它的便携性。)

【讨论】:

    猜你喜欢
    • 2017-02-16
    • 2019-11-30
    • 1970-01-01
    • 2015-04-07
    • 2012-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多