关于换行符
每次按下键盘上的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=auto
Git 将以其认为最佳的方式处理文件。这是一个不错的默认选项。 -
text eol=crlf
Git 将始终在检出时将换行符转换为CRLF
。对于必须保留CRLF
结尾的文件,即使在 OSX 或 Linux 上也应该使用此设置。 -
text eol=lf
Git 将始终在检出时将换行符转换为LF
。对于必须保留 LF 结尾的文件,即使在 Windows 上也应该使用此设置。 -
binary
Git 将理解指定的文件不是文本文件,并且不应该尝试更改它们。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"