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

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

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

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


当前回答

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

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

其他回答

我发现了一个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

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

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

崇高的文本用户。

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

"trim_trailing_white_space_on_save": true

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

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

在macOS(或者可能是任何BSD)上,sed命令参数必须略有不同。试试这个:

#!/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 -E 's/:[0-9]+:.*//' | uniq` ; do
    # Fix them!
    sed -i '' -E 's/[[:space:]]*$//' "$FILE"
    git add "$FILE"
done

将该文件保存为.git/hooks/pre-commit——或者寻找已经存在的文件,并将底部块粘贴到其中的某个地方。还有chmod (a+x)

或者为了全局使用(通过将git post-commit钩子应用到所有当前和未来的回购中),你可以把它放在$GIT_PREFIX/git-core/templates/hooks中(其中GIT_PREFIX是/usr或/usr/local或/usr/share或/opt/local/share),并在你现有的回购中运行git init。

根据git帮助init:

在现有的存储库中运行git init是安全的。它不会覆盖已经存在的东西。重新运行git init的主要原因是获取新添加的模板。