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

时间:2011-04-06 23:31:09

标签: git git-diff

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

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

4 个答案:

答案 0 :(得分:24)

Git在1.7.2(2010年7月21日)中学习了tab-in-indent空白类别 来自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"

或者,您可以为单个命令设置它(git -c也来自1.7.2):

git -c core.whitespace=tab-in-indent diff --check

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

答案 1 :(得分:11)

使用标签找到行:

git grep -n --cached 'LITERAL TAB HERE'

在bash或zsh中,您可以使用 Ctrl-V Ctrl-I 输入文字标签。该命令将显示所有文件+带标签的行。

如果要通过阻止使用标签提交来强制执行您的策略,请将其放在.git/hooks/pre-commit中并将其标记为可执行文件(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

*行的'git diff --cached | egrep之间有一个文字标签。您可以使用 Ctrl-V Ctrl-I 或使用 Cq Ci 的Emacs在Vim中获取此信息。

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

我把这个钩子放在github上here

答案 2 :(得分:0)

我做了一个预提交钩子,阻止你提交标签缩进代码https://github.com/martinjoiner/portable-code-pre-commit-hook它看起来像这样......

enter image description here

我现在经常在我的所有项目中使用它。随意使用它。

我在一个团队中工作,该团队在Mac,Windows和Linux环境中编写代码,并通过Github网站在浏览器中查看代码。团队非常乐意帮助检查他们的代码,使其在所有这些地方看起来一致。

如果您发现任何问题,请告诉我,我希望有机会改善任何弱点。感谢。

答案 3 :(得分:0)

使制表字符可见的一种方法是用明显的东西替换它们,例如.       (这是一个点后跟七个空格)。这可以通过在配置中替换pager来添加sed的调用来实现。像这样:

[core]
    pager = sed 's/\t/.       /g' | less -R

示例

没有自定义寻呼机:

         for (int i = 0; i < 3; ++i) {
-        for (int h = 0; h < 4; ++h) {
+                for (int h = 0; h < 4; ++h) {
                         for (int k = 0; k < 4; ++k) {

使用自定义寻呼机:

 .       for (int i = 0; i < 3; ++i) {
-        for (int h = 0; h < 4; ++h) {
+.       .       for (int h = 0; h < 4; ++h) {
 .       .       .       for (int k = 0; k < 4; ++k) {