1. 问题是什么

  • 文本行尾分 LF 与 CRLF。混用会出现整文件只改换行的 diff,合并、比对、和 Linux/CI/容器环境都不一致。
  • 要在仓库里约定规则,并在规范里约定 Git 是否再自动改换行。

2. 仓库里写什么:.gitattributes

  • 放在仓库根,提交后所有人相同。
  • 格式:路径模式 + 属性;# 为注释;同一文件命中多行时,文件中越靠下越优先。
推荐示例(可按项目增删 binary 扩展名):
* text=auto eol=lf
*.sh text eol=lf
# *.bat text eol=crlf
*.png binary
*.jpg binary
*.jpeg binary
*.gif binary
*.ico binary
*.webp binary
*.pdf binary
*.zip binary
*.jar binary
*.war binary
*.woff binary
*.woff2 binary
*.ttf binary
*.eot binary
*.mp4 binary
*.mp3 binary
 

  

  • * text=auto eol=lf:默认文本用 LF;text=auto 先区分文本/二进制,减少误伤。
  • *.sh:所有 shell 脚本显式 LF(与默认一致,审查时更清晰)。
  • *.bat 的 eol=crlf:仅当必须在传统 Windows 工具里用 CRLF 编辑时再开。
  • binary:显式二进制,写在 后面,覆盖默认,避免图片/jar 被当文本处理。
改规则后若历史混乱:团队可协调做一次 renormalize 提交(操作细节单独文档说明)。

3. core.autocrlf 是什么

  • Git 配置项,控制:工作区与 Git 对象之间是否自动改换行(典型如 Windows 上「检出 CRLF、提交再归一」)。
  • 不在 .gitattributes 里写;随各环境 Git 配置变化,属于环境侧。

4. 建议设成什么、为什么

  • 团队约定:core.autocrlf = false。
  • 原因:
  1. 行尾已由 .gitattributes(如 eol=lf)规定,不应再靠 autocrlf 在工作区多转一道。
  1. true 易与 eol=lf、编辑器保存的 LF 叠加,产生多余或无规律 diff。
  1. true 更适合没有 .gitattributes、只在 Windows 上凑合的旧习惯;已有全仓 eol=lf 时,用 false 更一致。
(具体在哪个层级写入 false:全局/本仓库/系统,由团队《Git 环境配置》说明;规范正文只写取值与理由即可。)

5. 两者关系(一句话)

  • .gitattributes:仓库契约,谁 clone 都一样。
  • autocrlf:环境是否自动改换行;与 eol 规则并存时,以 .gitattributes 为主,故约定 false 避免重复处理。

6. 配置优先级(补充)

若同一项在多层都有:git -c → 本仓库 .git/config → 用户 ~/.gitconfig → 安装目录 etc\gitconfig。查生效值:git config --show-origin --get core.autocrlf。
posted on 2020-01-03 20:14  花开浪漫拾  阅读(11541)  评论(0)    收藏  举报