如何在Git中规范化工作树行结尾?

use*_*171 57 git line-endings gitattributes

我克隆了一个存在不一致行结尾的存储库.我添加了一个.gitattributes为我想要规范化的文件设置text属性.现在,当我提交更改时,我收到消息:

warning: CRLF will be replaced by LF in FILE.
The file will have its original line endings in your working directory.
Run Code Online (Sandbox Code Playgroud)

如何让git为我标准化我的文件的工作副本?我希望git能够规范化整个工作树.

Joh*_*ter 87

gitattributes的文档提供了答案:

git add --renormalize .  # Update index with renormalized files
git status               # Show the files that will be normalized
git commit -m "Introduce end-of-line normalization"
Run Code Online (Sandbox Code Playgroud)

编辑后执行此序列.gitattributes.

更新

似乎有些用户在使用上述说明时遇到了问题.更新的gitattributes文档显示了一组新的指令(在编辑.gitattributes文件之后):

rm .git/index     # Remove the index to force git to
git reset         # re-scan the working directory
git status        # Show files that will be normalized
git add -u
git add .gitattributes
git commit -m "Introduce end-of-line normalization"
Run Code Online (Sandbox Code Playgroud)

感谢@ vossad01指出这一点.

此外,使用任一解决方案,工作副本中的文件仍保留其旧行结尾.如果要更新它们,请确保您的工作树是干净的并使用:

git read-tree --empty   # Clean index, force re-scan of working directory
git add .
git status        # Show files that will be normalized
git commit -m "Introduce end-of-line normalization"
Run Code Online (Sandbox Code Playgroud)

现在,行结尾在您的工作树中是正确的.

  • 这在第一次添加`.gitattributes`或更改设置时有效,但如果工作树具有不同的EOL(至少与MsysGit没有),则它不起作用.为此,似乎`git rm --cached -r .`然后`git reset --hard`工作(警告:破坏你的工作树).来自https://help.github.com/articles/dealing-with-line-endings. (10认同)
  • 谨慎使用`git read-tree --empty; git add .` variant.使用它时,将删除.gitignore将忽略的任何跟踪文件.文档现在推荐`git add --renormalize .` (3认同)

phi*_*ppn 64

使用Git客户端2.16及更高版本,现在有一种更简单的方法可以做到这一点.只是用__CODE__

  • 我刚刚在 Windows 版 Git Bash 上尝试了这个,它会暂存 repo 中的每个文件以进行提交。 (5认同)
  • 这对我来说根本没有任何作用。:-/ (5认同)
  • @cja“清理工作区”,如下所示:命令“git status”返回类似“没有任何内容可提交,工作树干净”之类的内容 (4认同)
  • 不起作用。投反对票 (2认同)
  • 对于那些阅读答案的前 4 个单词而不仅仅是复制粘贴命令的人来说,@wilmol 的作用就像一个魅力。拥有最新版本的 git 会很有帮助。 (2认同)

gav*_*koa 7

替代方法(仅在使用的命令中有所不同)

确保存储库中没有任何挂起的更改:

$ git status
$ git stash
Run Code Online (Sandbox Code Playgroud)

修改.gitattributes以便更改CRLF解释:

$ echo "*.txt  text" >>.gitattributes
$ git commit -m "Made .txt files a subject to CRLF normalization." -- .gitattributes
Run Code Online (Sandbox Code Playgroud)

从索引中删除数据并刷新工作目录:

$ git rm --cached -r .
$ git reset --hard
Run Code Online (Sandbox Code Playgroud)

查看Git提出的CRLF修复:

$ git ls-files --eol
$ git status
$ git diff
Run Code Online (Sandbox Code Playgroud)

同意Git的决定:

$ git add -u
$ git commit -m "Normalized CRLF for .txt files"
Run Code Online (Sandbox Code Playgroud)

重新加载更改,就像完成了clean clone一样:

$ git rm --cached -r .
$ git reset --hard
Run Code Online (Sandbox Code Playgroud)

  • `git ls-files --eol` 有助于验证所有文件中的行结尾是否符合预期,谢谢! (2认同)