我让我的文本编辑器在保存文件时自动修剪尾随空格,而且我正在为一个开源项目做贡献,该项目在尾随空格方面存在严重问题。

每次我尝试提交一个补丁时,我必须首先手动忽略所有只有空白的更改,只选择相关信息。不仅如此,当我运行git rebase时,我通常会遇到一些问题。

因此,我希望能够仅向索引添加非空白的更改,以类似于git add -p的方式,但不必自己选择所有更改。

有人知道怎么做吗?

编辑:我不能改变项目的工作方式,他们在邮件列表上讨论后决定忽略这一点。


当前回答

类似于@void。指针的答案,但修复最近的提交。

git reset --mixed HEAD^
git diff -U0 -w --no-color | git apply --cached --ignore-whitespace --unidiff-zero -

这将使空白更改不进行,而其余更改将进行。

其他回答

这对我来说很管用:

git config apply.whitespace fix

在每次提交使用命令之前:

git add -up .

创建一个只包含真正更改的补丁文件(不包括只有空白更改的行),然后清理工作空间并应用该补丁文件:

Git diff >备份 Git diff -w >变化 Git重置——很难 补丁<更改

检查剩余的差异,然后像往常一样添加和提交。

Mercurial的等效功能是这样做的:

Hg diff > backup Hg diff -w >变化 Hg回复——全部 Hg导入——不提交更改

我让我的文本编辑器在保存文件时自动修剪尾随空格

你的编辑器没有proj / dir特定的设置吗?可以禁用此项目的空白首选项。似乎是一个更简单的解决方案…

在你的.gitconfig中添加以下内容:

anw = !git diff -U0 -w --no-color -- \"$@\" | git apply --cached --ignore-whitespace --unidiff-zero "#"

感谢@Colin Herbert的回答给了我灵感。

语法解释

The final # must be quoted so it's not treated it as a comment inside the .gitconfig, but instead gets passed through and is treated as a comment inside the shell - it is inserted between the end of the git apply and the user-supplied arguments that git automatically places at the end of the command line. These arguments aren't wanted here - we don't want git apply to consume them, hence the preceding comment character. You may want to run this command as GIT_TRACE=1 git anw to see this in action.

——表示参数的结束,并允许你有一个名为-w或类似于git diff开关的文件。

需要在$@周围转义双引号来保存用户提供的引号参数。如果' '字符没有转义,它将被.gitconfig解析器使用,而不会到达shell。

注意:.gitconfig别名解析不识别任何特殊的单引号-它唯一的特殊字符是“,\,\n,和;(在引号字符串之外)。这就是为什么“必须总是转义,即使它看起来像是在单引号字符串中(git完全不知道这一点)。

这很重要。如果您有一个方便的别名,可以在工作树的根中执行bash命令。不正确的说法是:

sh = !bash -c '"$@"' -

而正确的答案是:

sh = !bash -c '\"$@\"' -

类似于@void。指针的答案,但修复最近的提交。

git reset --mixed HEAD^
git diff -U0 -w --no-color | git apply --cached --ignore-whitespace --unidiff-zero -

这将使空白更改不进行,而其余更改将进行。