How to let git reject any eol style change?

一曲冷凌霜 提交于 2020-01-02 07:31:16

问题


Sometimes people inadvertently change the eol style when committing codes. How to let git stop them from doing that? I've searched this topic and found out that most answers focused on how to turn files into a specific eol style. But I don't want this behavior. I just want committers to comply with the eol style of the original files, either \n or \r\n. Can git do that?


回答1:


I just need to force committers to comply with the original eol style that the author has chosen. That is to say, neither converting \n to \r\n, nor converting \r\n to \n is allowed. But I don't care what the original eol style is

If you have core.autocrlf set to false, git won't try to convert anything at anytime.

But that also means the user editor can change the eol without Git knowing anything about it: Git doesn't memorize the eol during checkout.
That means that it will checkin whatever has been modified by the user (including eol changes).

You could try a post-checkout hook which would be in charge of memorizing that information for you, but that seems a bit overkill.
I prefer registering a normalization for certain types of files in .gitattributes files, as the next section of this answer illustrates.


Orginal Answer, illustrating what Git can enforce at commit time:

You can register the eol you want (for specific types of files) in .gitattributes files, with eol directives:

text

This attribute enables and controls end-of-line normalization.
When a text file is normalized, its line endings are converted to LF in the repository.
To control what line ending style is used in the working directory, use the eol attribute for a single file and the core.eol configuration variable for all text files.

eol

This attribute sets a specific line-ending style to be used in the working directory.
It enables end-of-line normalization without any content checks, effectively setting the text attribute.

Set to string value "crlf"

This setting forces Git to normalize line endings for this file on checkin and convert them to CRLF when the file is checked out.

Set to string value "lf"

This setting forces Git to normalize line endings to LF on checkin and prevents conversion to CRLF when the file is checked out.

For instance:

*.sh        eol=lf

The interest in registering those directives in a .gitattributes file is that it will be persistent across repository cloning.



来源:https://stackoverflow.com/questions/19261912/how-to-let-git-reject-any-eol-style-change

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!