当我输入git diff时,我希望看到一个并排的diff,就像用diff -y一样,或者像在kdiff3这样的交互式diff工具中显示diff。如何做到这一点呢?


当前回答

在这个帖子里有很多很好的答案。对于这个问题,我的解决方案是编写一个脚本。

将其命名为“git-scriptname”(并使其可执行并将其放在您的PATH中,就像任何脚本一样),您可以像正常的git命令一样通过运行调用它

$ git scriptname

实际的功能在最后一行。来源如下:

#!/usr/bin/env zsh
#
#   Show a side-by-side diff of a particular file how it currently exists between:
#       * the file system
#       * in HEAD (latest committed changes)

function usage() {
    cat <<-HERE
    USAGE

    $(basename $1) <file>

    Show a side-by-side diff of a particular file between the current versions:

        * on the file system (latest edited changes)
        * in HEAD (latest committed changes)

HERE
}

if [[ $# = 0 ]]; then
    usage $0
    exit
fi

file=$1
diff -y =(git show HEAD:$file) $file | pygmentize -g | less -R

其他回答

当我在寻找一种使用git内置方式来定位差异的快速方法时,这个问题出现了。我的解决方案标准:

快速启动,需要内置选项 可以处理多种格式,xml,不同的编程语言 快速识别大文本文件中的小代码更改

我找到这个答案是为了给git上色。

为了获得并排diff而不是行diff,我调整了mb14在这个问题上的优秀答案,使用以下参数:

$ git diff --word-diff-regex="[A-Za-z0-9. ]|[^[:space:]]"

如果你不喜欢额外的[-或{+选项——word-diff=color可以使用。

$ git diff --word-diff-regex="[A-Za-z0-9. ]|[^[:space:]]" --word-diff=color

这有助于与json和xml文本以及java代码进行适当的比较。

总之,——word-diff-regex选项与颜色设置一起具有非常有用的可见性,与标准行差异相比,当浏览带有小行更改的大文件时,可以获得彩色的并排源代码体验。

在这个帖子里有很多很好的答案。对于这个问题,我的解决方案是编写一个脚本。

将其命名为“git-scriptname”(并使其可执行并将其放在您的PATH中,就像任何脚本一样),您可以像正常的git命令一样通过运行调用它

$ git scriptname

实际的功能在最后一行。来源如下:

#!/usr/bin/env zsh
#
#   Show a side-by-side diff of a particular file how it currently exists between:
#       * the file system
#       * in HEAD (latest committed changes)

function usage() {
    cat <<-HERE
    USAGE

    $(basename $1) <file>

    Show a side-by-side diff of a particular file between the current versions:

        * on the file system (latest edited changes)
        * in HEAD (latest committed changes)

HERE
}

if [[ $# = 0 ]]; then
    usage $0
    exit
fi

file=$1
diff -y =(git show HEAD:$file) $file | pygmentize -g | less -R

我用色差。

在Mac OS X上,使用

$ sudo port install colordiff

在Linux上可能会安装colordiff或类似的东西,这取决于你的发行版。

然后:

$ git difftool --extcmd="colordiff -ydw" HEAD^ HEAD

或者创建别名

$ git alias diffy "difftool --extcmd=\"colordiff -ydw\""

然后你就可以使用它了

$ git diffy HEAD^ HEAD

我称它为“diffy”,因为diff -y是unix中并排的diff。Colordiff还添加了更好的颜色。 在选项-ydw中,y表示并排,w表示忽略空白,d表示产生最小的diff(通常作为diff会得到更好的结果)

这里有一个方法。如果管道通过less, xterm宽度设置为80,这不是很热。但是如果继续执行命令,例如COLS=210,则可以使用扩展的xterm。

gitdiff()
{
    local width=${COLS:-$(tput cols)}
    GIT_EXTERNAL_DIFF="diff -yW$width \$2 \$5; echo >/dev/null" git diff "$@"
}

对于unix,只组合git和内置的diff:

git show HEAD:path/to/file | diff -y - path/to/file

当然,您可以用任何其他git引用替换HEAD,并且您可能希望在diff命令中添加-W 170之类的东西。

这里假设您只是将您的目录内容与过去的提交进行比较。两个提交之间的比较比较复杂。如果你的shell是bash,你可以使用“进程替换”:

diff -y -W 170 <(git show REF1:path/to/file) <(git show REF2:path/to/file)

其中REF1和REF2是git引用-标签,分支或哈希。