在一个差异中使git突出显示制表符?

jon*_*rry 21 git git-diff

我试图确保我不提交使用制表符进行缩进的代码.这是一个软约束,我正在申请我自己的提交(现在我们没有缩进字符的标准,但我想使用空格,因为空间的宽度没有分歧,但有些人们使用宽度为4的选项卡而不是宽度为8的选项卡.

检查这些约束的最简单方法通常是每次要提交时查看git diff的实际输出,看看是否有任何问题.例如,对我来说,默认情况下,尾随空格会突出显示,并且窗口换行也会在差异中显示,所以如果我不小心提交带有尾随空格的代码,我会收到警告.有没有办法让标签字符也显示在git diff中?

Chr*_*sen 25

Git tab-in-indent在1.7.2(2010年7月21日)中学习了空白类别.
Documentation/RelNotes/1.7.2.txt:

  • "git apply --whitespace"和"git diff"中使用的空白规则在该系列中获得了一个新成员(tab-in-indent),以帮助具有策略的项目仅使用空格缩进.

它的控制和使用方式与其他空格检查选项相同.

突出显示git diff与其他空白错误相同.
检查可用git diff --check.
等等.

添加配置变量tab-in-indent的值core.whitespace以启用它(可能在一个或多个特定存储库中或在"全局"(按使用)配置中).

set-show-tabs() {
    global=
    test "$1" = -g || test "$1" = --global && global=--global
    cws=$(git config $global core.whitespace)
    case "$cws" in
        tab-in-indent,*|*,tab-in-indent|*,tab-in-indent,*) ;;
        *) git config $global core.whitespace "$cws"${cws:+,}tab-in-indent ;;
    esac
}
set-show-tabs           # only in local repository
set-show-tabs --global  # for all your Git activities
# or just edit it manually with "git config [--global] --edit"
Run Code Online (Sandbox Code Playgroud)

或者,您可以为单个命令设置它(git -c也是从1.7.2开始):

git -c core.whitespace=tab-in-indent diff --check
Run Code Online (Sandbox Code Playgroud)

您可以在pre-commit钩子中使用类似的东西来检查选项卡,而不必在任何实际的存储库配置文件中使用它.

  • @ rr-:使用单一颜色进行空白错误突出显示可能是设计决策,以保持简单.关于从不突出显示选项卡的部分(即使使用`-tab-in-indent`;以及带有`-space-before-tab`的选项卡之前的空格)可能是一个错误或只是一个实现细节.Git 2.5.0将有[`--ws-error-highlight = none`](https://github.com/git/git/blob/7ecec52d42a964c4a8e9f6ca41bb0b5ce00049b4/Documentation/RelNotes/2.5.0.txt#L12)禁用空白错误突出显示,将这些选项卡(以及选项卡前的空格)的颜色与"新"和"旧"行的其余部分完全相同. (2认同)

Mat*_*tis 12

要使用制表符找到行:

git grep -n --cached 'LITERAL TAB HERE'
Run Code Online (Sandbox Code Playgroud)

在bash或zsh中,您可以输入文字选项卡Ctrl-V Ctrl-I.该命令将显示所有文件+带有选项卡的行.

如果要通过阻止使用选项卡进行提交来强制执行策略,请将其放入.git/hooks/pre-commit并标记为executable(chmod +x):

#!/bin/sh
allowtabs=$(git config hooks.allowtabs)
if [ "$allowtabs" != "true" ] &&
   git diff --cached | egrep '^\+.* '>/dev/null
then
   cat<<END;
Error: This commit would contain a tab, which is against this repo's policy.

If you know what you are doing you can force this commit with:

  git commit --no-verify

Or change the repo policy like so:

  git config hooks.allowtabs true
END
  exit 1
fi
Run Code Online (Sandbox Code Playgroud)

还有的之间的文字标签*'git diff --cached | egrep线.您可以在Vim中使用Ctrl-V Ctrl-I,或者使用Emacs C-q C-i.

它的作用是在diff中找到一个新行(以"+"开头),其中包含一个制表符.git grep如果要在挂钩中显示有问题的选项卡,可以将该行放在错误消息中.

我把这个钩子放在github 这里.