我正在和我的团队一起使用Git,并希望从我的差异、日志、合并等中删除空白更改。我假设做到这一点最简单的方法是Git在应用所有提交时自动删除尾随空白(和其他空白错误)。

我已经尝试将以下内容添加到~/。gitconfig文件,但是当我提交时它什么也不做。也许它是为别的东西设计的。解决方案是什么?

[core]
    whitespace = trailing-space,space-before-tab
[apply]
    whitespace = fix

我使用Ruby,以防有人对Ruby有任何具体的想法。在提交之前自动格式化代码将是下一步,但这是一个困难的问题,并不是真正造成大问题。


当前回答

在Vim中打开文件。要用空格替换制表符,在Vim命令行中输入以下命令:

:%s#\t#    #gc

以消除其他尾随空白

:%s#\s##gc

这对我来说很管用。如果你有很多文件要编辑,那就很乏味了。但我发现它比预提交钩子和使用多个文本编辑器更容易。

其他回答

我今天一直在想这个问题。这就是我最终为一个Java项目所做的一切:

egrep -rl ' $' --include *.java *  | xargs sed -i 's/\s\+$//g'

我发现了一个Git预提交钩子,它删除了尾随空白。

#!/bin/sh

if git-rev-parse --verify HEAD >/dev/null 2>&1 ; then
   against=HEAD
else
   # Initial commit: diff against an empty tree object
   against=4b825dc642cb6eb9a060e54bf8d69288fbee4904
fi
# Find files with trailing whitespace
for FILE in `exec git diff-index --check --cached $against -- | sed '/^[+-]/d' | sed -r 's/:[0-9]+:.*//' | uniq` ; do
   # Fix them!
   sed -i 's/[[:space:]]*$//' "$FILE"
   git add "$FILE"
done
exit

请试试我的预提交钩子。它可以自动检测尾随空白并删除它。

它可以在Git Bash (Windows), Mac OS X和Linux下工作!


快照:

$ git commit -am "test"
auto remove trailing whitespace in foobar/main.m!
auto remove trailing whitespace in foobar/AppDelegate.m!
[master 80c11fe] test
1 file changed, 2 insertions(+), 2 deletions(-)

崇高的文本用户。

在“设置-用户”配置中正确设置以下内容。

"trim_trailing_white_space_on_save": true

这不会在提交前自动删除空白,但很容易实现。我把下面的Perl脚本放在一个名为Git -wsf (Git空白修复)的文件中,在$PATH目录下,所以我可以:

git wsf | sh

而且它只删除Git报告为diff的文件行中的所有空白。

#! /bin/sh
git diff --check | perl -x $0
exit

#! /usr/bin/perl

use strict;

my %stuff;
while (<>) {
    if (/trailing whitespace./) {
        my ($file,$line) = split(/:/);
        push @{$stuff{$file}},$line;
    }
}

while (my ($file, $line) = each %stuff) {
    printf "ex %s <<EOT\n", $file;
    for (@$line) {
        printf '%ds/ *$//'."\n", $_;
    }
    print "wq\nEOT\n";
}