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

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

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

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


当前回答

同样的结果。

import subprocess                                                                 
                                                                              
def get_trailing_lines():                                                         
                                                                              
    result = subprocess.run([                                                     
                            'git',                                            
                            'diff',                                           
                            '--check'                                         
                        ], capture_output=True)                               
                                                                              
    return result.stdout.decode().split('\n')                                     
                                                                              
                                                                              
def modify_line(file_path, l_num):                                                
                                                                              
    f_lines = open(file_path).readlines()                                         
    f_lines[l_num] = f_lines[l_num].rstrip()+'\n'\                                
                     if '\n' in f_lines[l_num] else f_lines[l_num].rstrip()    
                                                                              
    with open(file_path, "w") as w_fp:                                            
        w_fp.writelines(f_lines)                                                  
                                                                              
                                                                              
if __name__ == '__main__':                                                        
                                                                              
    l = get_trailing_lines()                                                      
    for m, d in zip(l[::2], l[1::2]):                                             
        f_path, l_no, *_ = m.split(":")                                           
        modify_line(f_path, int(l_no)-1)                                          

其他回答

这不会在提交前自动删除空白,但很容易实现。我把下面的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";
}

这些设置(核心。空格和apply.whitespace)不是用来移除尾随空格的,而是用来:

核心。空格:检测它们,并引发错误 适用。空格:并删除它们,但只在补丁期间,而不是“总是自动”

我相信git钩子预提交会做得更好(包括删除尾随空格)


注意,在任何给定的时间,你都可以选择不运行pre-commit钩子:

暂时:git提交——no-verify。 CD .git/hooks/;Chmod -x预提交

警告:默认情况下,预提交脚本(就像这个脚本)没有“移除尾随”功能,而是“警告”功能,比如:

if (/\s$/) {
    bad_line("trailing whitespace", $_);
}

然而,你可以构建一个更好的预提交钩子,特别是当你考虑到:

在Git中提交时,只向暂存区添加了一些更改,仍然会导致“原子”修订,该修订可能从未作为工作副本存在过,也可能无法工作。


例如,oldman在另一个答案中提出了一个预提交钩子,它可以检测并删除空白。 由于该钩子获取每个文件的文件名,我建议对某些类型的文件要小心:你不希望删除.md (markdown)文件中的尾随空格!


hakre在评论中建议的另一种方法是:

你可以在markdown中在行末有两个空格,而不是在\n前添加“\”作为尾随空格。

然后是内容过滤器驱动程序:

git config --global filter.space-removal-at-eol.clean 'sed -e "s/ \+$//"'
# register in .gitattributes 
*.md filter=space-removal-at-eol

要删除文件中行尾的空格,使用ed:

test -s file &&
   printf '%s\n' H ',g/[[:space:]]*$/s///' 'wq' | ed -s file

文件的for循环使用$IFS shell变量。 在给定的脚本中,包含$ ifs变量中的字符的文件名将被视为for循环中的两个不同文件。

这个脚本修复了它:sed手册中给出的多行模式修饰符似乎在我的Ubuntu盒子上默认不工作,所以我寻找了一个不同的实现,并发现了一个迭代标签,本质上它只会在文件的最后一行开始替换,如果我正确理解它。

#!/bin/sh
#

# A Git hook script to find and fix trailing white space
# in your commits. Bypass it with the --no-verify option
# to git-commit
#

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

SAVEIFS="$IFS"
# only use new-line character as separator, introduces EOL-bug?
IFS='
'
# Find files with trailing white space
for FILE in $(
    git diff-index --check --cached $against -- \
    | sed '/^[+-]/d' \
    | ( sed -r 's/:[0-9]+:.*//' || sed -E 's/:[0-9]+:.*//' ) \
    | uniq \
)
do
# replace whitespace-characters with nothing
# if first execution of sed-command fails, try second one (Mac OS X version)
    (
        sed -i ':a;N;$!ba;s/\n\+$//' "$FILE" > /dev/null 2>&1 \
        || \
        sed -i '' -E ':a;N;$!ba;s/\n\+$//' "$FILE" \
    ) \
    && \
# (re-)add files that have been altered to Git commit-tree
#   when change was a [:space:]-character @EOL|EOF git-history becomes weird...
    git add "$FILE"
done
# restore $IFS
IFS="$SAVEIFS"

# Exit script with the exit-code of git's check for white space characters
exec git diff-index --check --cached $against --

如何使用sed替换换行符(\n) ?

我宁愿把这个任务留给你最喜欢的编辑。

只需设置一个命令,在保存时删除尾随空格。