关于换行符
每次在键盘上按下 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 - 按路径定义属性。 -
为避免丢失对仓库中文件的任何本地更改,请运行以下命令将所有未完成的更改添加并提交。
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 add --renormalize .
git add --renormalize . -
要显示已重写、已规范化的文件,请运行以下命令。
Shell git status
git status -
可选地,要在仓库中提交任何未完成的更改,请运行以下命令。
Shell git commit -m "Normalize all the line endings"
git commit -m "Normalize all the line endings"
延伸阅读
- 自定义 Git - Git 属性(《Pro Git》一书)
- git-config(Git 手册页)
- 入门 - 第一次 Git 设置(《Pro Git》一书)
- 注意行尾,作者 Tim Clem