【问题标题】:How to show relative paths in git diff command?如何在 git diff 命令中显示相对路径?
【发布时间】:2017-07-14 15:19:57
【问题描述】:

它是这样工作的:

MYPC /d/home/project/some/path (master)
$ git diff --name-only --cached
root.txt
some/path/relative.txt

即它显示了来自 GIT 根目录的路径,但我需要来自当前目录的相对路径。

预期结果:

$ git diff --name-only --cached --AND_SOME_OPTION
../../root.txt
relative.txt

按照常识,它应该像git status 一样工作。

附言 --relative 选项不起作用,因为它将显示此目录中的文件。 在我们的示例中,它将仅显示 relative.txt

附言

使用--git-dir 也不行:

$ git --git-dir=$(git rev-parse --show-toplevel)/.git  diff --cached --name-only
root.txt
some/path/relative.txt

【问题讨论】:

标签: git git-diff


【解决方案1】:

git status -s 已经输出了可以轻松隔离的相对路径。

如果你需要使用git diff,你可以通过管道输出到realpath,如果有的话:

$ git diff --name-only | \
    xargs -I '{}' realpath --relative-to=. $(git rev-parse --show-toplevel)/'{}'
../../root.txt
relative.txt

【讨论】:

  • 是的,我绝对需要git-diff,因为有一个适合我的选项--cached。感谢您的帖子!
【解决方案2】:

到目前为止,我还没有找到通过使用git-diff 来使用相对路径的方法。

对我有用的唯一方法:

$ git status -s | awk '{print $2}'
../../root.txt
relative.txt

或者

$ git status -s | cut -c4-

How can I run "git status" and just get the filenames 中解释的最后一种方法。 .第一个很相似。 :)

但最好找到非管道方式。看来,没有办法避免使用--cached。 所以,大多数情况下这不是一个答案。

【讨论】:

    【解决方案3】:

    Joao Delgadosuggestion above 的基础上使用realpath,您可以使用--src-prefix--dst-prefix 诱使Git 做您想做的事情:

    $ rel=$(realpath --relative-to=. $(git rev-parse --show-toplevel))
    $ git diff --src-prefix=a/$rel/ --dst-prefix=b/$rel/
    ../../root.txt
    ../../some/path/relative.txt
    

    这将显示所有修改过的文件(不仅仅是当前工作目录中的文件),并且它还将在输出中使用相对路径(尽管对于所有文件)。

    请注意,在顶层,这将输出带有前导 ./ 的路径:

    ./root.txt
    ./some/path/relative.txt
    

    这里是配置df别名的方法:

    $ git config --global alias.df '!f() { : git diff ; rel=$(realpath --relative-to="$PWD/$GIT_PREFIX" "$PWD"); git diff --src-prefix="a/$rel/" --dst-prefix="b/$rel/" "$@"; }; f'
    $ git df
    ../../root.txt
    ../../some/path/relative.txt
    

    (这使用空命令: 来启用git diff 此别名的Bash 补全(参见https://github.com/git/git/blob/1a4874565fa3b6668042216189551b98b4dc0b1b/contrib/completion/git-completion.bash#L26-L30

    【讨论】:

      猜你喜欢
      • 2014-05-24
      • 1970-01-01
      • 2012-05-14
      • 2015-07-26
      • 1970-01-01
      • 2018-03-12
      • 2014-06-22
      • 2017-04-20
      • 1970-01-01
      相关资源
      最近更新 更多