使Git在提交之前自动删除结尾的空白 [英] Make Git automatically remove trailing white space before committing

查看:86
本文介绍了使Git在提交之前自动删除结尾的空白的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在与团队一起使用Git,并希望从差异,日志,合并等中删除空白更改.我假设最简单的方法是让Git自动删除结尾的空白(以及其他空白错误)来自所有提交时的应用.

I'm using Git with my team and would like to remove white space changes from my diffs, logs, merges, etc. I'm assuming that the easiest way to do this would be for Git to automatically remove trailing white space (and other white space errors) from all commits as they are applied.

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

I have tried to add the following to the ~/.gitconfig file, but it doesn't do anything when I commit. Maybe it's designed for something different. What's the solution?

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

我正在使用Ruby,以防有人对Ruby有任何特定的想法.下一步是提交之前自动进行代码格式化,但这是一个难题,并且并没有真正引起大问题.

I'm using Ruby in case anyone has any Ruby specific ideas. Automatic code formatting before committing would be the next step, but that's a hard problem and is not really causing a big problem.

推荐答案

这些设置( core.whitespace apply.whitespace )不存在,用于删除结尾的空格,但是到:

Those settings (core.whitespace and apply.whitespace) are not there to remove trailing whitespace but to:

  • core.whitespace :检测到它们并引发错误
  • apply.whitespace :并剥离它们,但仅在修补过程中,而不是始终自动"
  • core.whitespace: detect them, and raise errors
  • apply.whitespace: and strip them, but only during patch, not "always automatically"

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

I believe the git hook pre-commit would do a better job for that (includes removing trailing whitespace)

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

Note that at any given time you can choose to not run the pre-commit hook:

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

警告:默认情况下,预提交脚本(例如

Warning: by default, a pre-commit script (like this one), has not a "remove trailing" feature", but a "warning" feature like:

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

不过,您可以

You could however build a better pre-commit hook, especially when you consider that:

在Git中进行调试,只对登台区域进行了一些更改,仍然会导致原子"修订,可能永远不会作为工作副本存在,并且可能无法正常工作.

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 建议 pre-提交钩子,它可以检测并删除空格.
由于该钩子获取了每个文件的文件名,因此我建议对某些类型的文件要格外小心:您不想删除 .md (markdown)文件中的尾随空格!


For instance, oldman proposes in another answer a pre-commit hook which detects and remove whitespace.
Since that hook get the file name of each file, I would recommend to be careful for certain type of files: you don't want to remove trailing whitespace in .md (markdown) files!

这篇关于使Git在提交之前自动删除结尾的空白的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆