我让我的文本编辑器在保存文件时自动修剪尾随空格,而且我正在为一个开源项目做贡献,该项目在尾随空格方面存在严重问题。
每次我尝试提交一个补丁时,我必须首先手动忽略所有只有空白的更改,只选择相关信息。不仅如此,当我运行git rebase时,我通常会遇到一些问题。
因此,我希望能够仅向索引添加非空白的更改,以类似于git add -p的方式,但不必自己选择所有更改。
有人知道怎么做吗?
编辑:我不能改变项目的工作方式,他们在邮件列表上讨论后决定忽略这一点。
我让我的文本编辑器在保存文件时自动修剪尾随空格,而且我正在为一个开源项目做贡献,该项目在尾随空格方面存在严重问题。
每次我尝试提交一个补丁时,我必须首先手动忽略所有只有空白的更改,只选择相关信息。不仅如此,当我运行git rebase时,我通常会遇到一些问题。
因此,我希望能够仅向索引添加非空白的更改,以类似于git add -p的方式,但不必自己选择所有更改。
有人知道怎么做吗?
编辑:我不能改变项目的工作方式,他们在邮件列表上讨论后决定忽略这一点。
当前回答
在你的.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 '\"$@\"' -
其他回答
下面这个怎么样:
git add `git diff -w --ignore-submodules |grep "^[+][+][+]" |cut -c7-`
反引号内的命令获取有非空格更改的文件名。
这对我来说很管用:
如果你想藏点,这招管用
git stash && git stash apply && git diff -w > foo.patch && git checkout . && git apply foo.patch && rm foo.patch
我不喜欢存储,但我在git + cygwin中遇到了一个错误,我失去了变化,所以为了确保东西去了reflog,至少我设置了以下内容:
git add . && git commit -am 'tmp' && git reset HEAD^ && git diff -w > foo.patch && git checkout . && git apply foo.patch && rm foo.patch
基本上,我们创建了一个不包括空格更改的diff,还原所有更改,然后应用diff。
我发现了一个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"
done
exit
创建一个只包含真正更改的补丁文件(不包括只有空白更改的行),然后清理工作空间并应用该补丁文件:
Git diff >备份 Git diff -w >变化 Git重置——很难 补丁<更改
检查剩余的差异,然后像往常一样添加和提交。
Mercurial的等效功能是这样做的:
Hg diff > backup Hg diff -w >变化 Hg回复——全部 Hg导入——不提交更改
这是我的黑客。
git diff -w | grep "diff --git a/*" | sed -r 's#diff --git a/(.*) b(.*)#\1#g' | xargs git add
Git diff -w只显示没有空格的文件,