关于换行符
每次您在键盘上按下 return 键时,都会插入一个称为换行符的不可见字符。不同的操作系统对换行符的处理方式不同。
当您使用 Git 和 GitHub 协作处理项目时,如果例如您在 Windows 机器上工作,而您的合作者在 macOS 上进行了更改,则 Git 可能会产生意外的结果。
您可以配置 Git 自动处理行尾,以便您可以与使用不同操作系统的用户有效协作。
行尾的全局设置
git config core.autocrlf 命令用于更改 Git 处理行尾的方式。它接受单个参数。
在 macOS 上,您只需将 input 传递给配置。例如
$ git config --global core.autocrlf input
# Configure Git to ensure line endings in files you checkout are correct for macOS
在 Windows 上,您只需将 true 传递给配置。例如
$ git config --global core.autocrlf true
# Configure Git to ensure line endings in files you checkout are correct for Windows.
# For compatibility, line endings are converted to Unix style when you commit files.
在 Linux 上,您只需将 input 传递给配置。例如
$ git config --global core.autocrlf input
# Configure Git to ensure line endings in files you checkout are correct for Linux
每个仓库的设置
可选地,您可以配置一个 .gitattributes 文件来管理 Git 如何读取特定仓库中的行尾。当您将此文件提交到仓库时,它会覆盖所有仓库贡献者的 core.autocrlf 设置。这确保了所有用户的一致行为,无论他们的 Git 设置和环境如何。
.gitattributes 文件必须创建在仓库的根目录中,并像任何其他文件一样提交。
.gitattributes 文件看起来像一个有两列的表格
- 左侧是 Git 要匹配的文件名。
- 右侧是 Git 应该为这些文件使用的行尾配置。
示例
这是一个 .gitattributes 文件的示例。您可以将其用作仓库的模板
# Set the default behavior, in case people don't have core.autocrlf set.
* text=auto
# Explicitly declare text files you want to always be normalized and converted
# to native line endings on checkout.
*.c text
*.h text
# Declare files that will always have CRLF line endings on checkout.
*.sln text eol=crlf
# Denote all files that are truly binary and should not be modified.
*.png binary
*.jpg binary
您会注意到文件是如何匹配的——*.c、*.sln、*.png——,用空格分隔,然后给出一个设置——text、text eol=crlf、binary。我们将在下面介绍一些可能的设置。
-
text=autoGit 将以它认为最佳的方式处理文件。这是一个很好的默认选项。 -
text eol=crlfGit 将始终在检出时将行尾转换为CRLF。对于必须保留CRLF行尾的文件,即使在 OSX 或 Linux 上也应该使用此设置。 -
text eol=lfGit 将始终在检出时将行尾转换为LF。对于必须保留 LF 行尾的文件,即使在 Windows 上也应该使用此设置。 -
binaryGit 将理解指定的文件不是文本文件,并且不应该尝试更改它们。binary设置也是-text -diff的别名。
更改行尾后刷新仓库
设置 core.autocrlf 选项或提交 .gitattributes 文件后,Git 会自动更改行尾以匹配您的新配置。您可能会发现 Git 报告了您未修改的文件的更改。
为了确保仓库中的所有行尾都与您的新配置匹配,请使用 Git 备份您的文件,然后删除并恢复所有文件以规范化行尾。
-
在添加或提交任何更改之前,请验证 Git 是否已正确应用配置。例如,Git 会自动确定仓库中的文件是文本文件还是二进制文件。为了避免损坏仓库中的二进制文件,我们建议您在
.gitattributes中明确将文件标记为二进制文件。有关更多信息,请参阅 Git 文档中的 gitattributes - Defining attributes per path。 -
为了避免丢失对仓库中文件的任何本地更改,请通过运行以下命令添加和提交任何未完成的更改。
Shell git add . -u git commit -m "Saving files before refreshing line endings"
git add . -u git commit -m "Saving files before refreshing line endings" -
要更新当前分支上的所有文件以反映新的配置,请运行以下命令。
Shell git rm -rf --cached . git reset --hard HEAD
git rm -rf --cached . git reset --hard HEAD -
要显示重写后的规范化文件,请运行以下命令。
Shell git status
git status -
可选地,要提交仓库中任何未完成的更改,请运行以下命令。
Shell git commit -m "Normalize all the line endings"
git commit -m "Normalize all the line endings"