gpt4 book ai didi

git - 让 Git 在提交之前自动删除尾随空格

转载 作者:IT王子 更新时间:2023-10-29 01:15:09 27 4
gpt4 key购买 nike

我和我的团队一起使用 Git,我想从我的差异、日志、 merge 等中删除空白更改。我假设最简单的方法是让 Git 自动删除尾随的空白(和其他空白错误)来自所有提交的应用。

我尝试将以下内容添加到 ~/.gitconfig 文件中,但是当我提交时它没有做任何事情。也许它是为不同的东西而设计的。解决方案是什么?

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

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

最佳答案

这些设置(core.whitespaceapply.whitespace)不是用来删除尾随空格的,而是用来:

  • core.whitespace:检测它们并引发错误
  • apply.whitespace:并剥离它们,但仅在打补丁期间,而不是“始终自动”

我相信 git hook pre-commit 会做得更好(包括删除尾随空格)


请注意,在任何给定时间您都可以选择不运行 pre-commit Hook :

  • 暂时:git commit --no-verify .
  • 永久:cd .git/hooks/; chmod -x 预提交

警告:默认情况下,pre-commit 脚本(如 this one )不是“删除尾随”功能,而是“警告”功能,例如:

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

然而,您可以 build a better pre-commit hook ,尤其是当您考虑到这一点时:

Committing in Git with only some changes added to the staging area still results in an “atomic” revision that may never have existed as a working copy and may not work.


例如,oldman 提出了 in another answer 检测和删除空格的 pre-commit hook
由于该 Hook 获取每个文件的文件名,我建议对某些类型的文件要小心:您不想删除 .md ( Markdown )文件中的尾随空格!


hakrethe comments 中建议的另一种方法:

You can have two spaces at end of line in markdown and not have it as trailing whitespace by adding "\" before \n.

然后是内容过滤驱动:

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

关于git - 让 Git 在提交之前自动删除尾随空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/591923/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com