我克隆了一个存在不一致行结尾的存储库。我添加了一个.gitattributes
,它为我想要规范化的文件设置text属性。现在,当我提交更改时,我收到消息:
warning: CRLF will be replaced by LF in FILE.
The file will have its original line endings in your working directory.
如何让git为我标准化我的文件的工作副本?我希望git能够规范化整个工作树。
使用Git客户端2.16及更高版本,现在有一种更简单的方法可以做到这一点。只需使用git add --renormalize .
对于使用v2.16或更高版本的用户,您可以简单地使用:
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"
这些方向直接来自gitattributes。对于旧版本,docs(在v2.12之前)提供了不同的答案:
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"
编辑.gitattributes
后执行此序列。
似乎有些用户在使用上述说明时遇到了问题。更新的gitattributes文档(2.12到2.14)显示了一组新的指令(在编辑.gitattributes文件之后):
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"
感谢@vossad01指出这一点。
此外,使用任一解决方案,工作副本中的文件仍保留其旧行结尾。如果要更新它们,请确保您的工作树是干净的并使用:
git rm --cached -r .
git reset --hard
现在,行结尾在您的工作树中是正确的。
确保存储库中没有任何挂起的更改:
$ git status
$ git stash
修改.gitattributes
以便更改CRLF解释:
$ echo "*.txt text" >>.gitattributes
$ git commit -m "Made .txt files a subject to CRLF normalization." -- .gitattributes
从索引中删除数据并刷新工作目录:
$ git rm --cached -r .
$ git reset --hard
查看Git提出的CRLF修复:
$ git ls-files --eol
$ git status
$ git diff
同意Git的决定:
$ git add -u
$ git commit -m "Normalized CRLF for .txt files"
重新加载更改,就像完成了clean clone一样:
$ git rm --cached -r .
$ git reset --hard
.gitattributes
设置只会影响新提交。如果此存储库没有发布历史记录(没有其他内容依赖于它),您可能希望浏览整个历史记录。在Unix / Linux中,您可以使用dos2unix(1)
将所有文件与find(1)
结合使用,并使用filter-branch
的历史重写(请参阅git书中的discussion),您甚至可以清理项目的完整历史记录。
在新鲜的克隆上使用时要特别小心。与任何可能有克隆的人联系,并告诉他们你想做什么。
.gitattributes中的* text = auto选项使Git存储库处于“非法状态”,如果它包含带有CRLF(Windows)行结尾的文件,现在标记为文本(请参阅https://marc.info/?l=git&m=154484903528621&w=2)。标准重新规范化选项无法与LFS过滤器一起正常工作,因此其他答案或例如https://help.github.com/en/articles/dealing-with-line-endings中的说明无法正常工作。相反,这些步骤对我们有用:
情况: