Git 属性配置和生效
.gitattributes
文件用于为特定文件或文件类型定义 Git 属性设置。本文档介绍了如何创建、更新 .gitattributes
文件,以及如何确保它生效。
创建和更新 .gitattributes
文件
- 在项目根目录下创建一个名为
.gitattributes
的文件(如果尚未创建)。
# 设置默认行为,以防用户没有设置 core.autocrlf。
* text=auto
# 明确声明始终要规范化并在检出时转换为本机行尾的文本文件。
*.cs text diff=csharp
*.cginc text
*.shader text
# 声明在检出时始终具有 CRLF 行尾的文件。
*.sln text eol=crlf
# 标明所有真正的二进制文件,不应修改。
*.png binary
*.jpg binary
*.jpeg binary
*.tga binary
*.psd binary
*.bmp binary
*.fbx binary
*.ogg binary
*.aif binary
*.wav binary
*.a binary
*.pdf binary
*.zip binary
*.dll binary
*.so binary
*.a binary
*.dylib binary
*.unitypackage binary
# Unity 文件
*.meta text merge=unityyamlmerge eol=lf
*.unity text merge=unityyamlmerge eol=lf
*.asset text merge=unityyamlmerge eol=lf
*.anim text merge=unityyamlmerge eol=lf
*.prefab text merge=unityyamlmerge eol=lf
*.mat text merge=unityyamlmerge eol=lf
*.controller text merge=unityyamlmerge eol=lf
*.shadergraph text eol=lf
*.dwlt text eol=lf
*.json text eol=lf
*.txt text eol=lf
- 在
.gitattributes
文件中,为每种文件类型添加一行设置。例如,要确保所有.txt
文件使用 LF 行尾符,添加以下一行:
*.txt text eol=lf
对于特定文件,您可以使用文件名和路径。例如:
ProjectSettings/ProjectVersion.txt text eol=lf
-
将
.gitattributes
文件添加到 Git:
git add .gitattributes -
提交更改:
git commit -m “Update .gitattributes settings”
确保 .gitattributes
文件生效
如果已经提交了 .gitattributes
文件,但想确保它生效,可以按照以下步骤操作:
-
首先,确保
.gitattributes
文件包含适当的设置。 -
然后,运行以下命令,以使 Git 重新检查已提交的所有文件:
git rm --cached -r .
这将从 Git 跟踪的文件中删除所有文件,但不会从工作目录中删除它们。这样可以确保 Git 重新检查这些文件,并遵循 .gitattributes
中的设置。
- 接下来,添加所有文件回 Git:
git add .
这将重新添加所有文件,使用 .gitattributes
中定义的设置。
- 最后,提交这些更改:
git commit -m “Apply .gitattributes settings”
完成这些步骤后,.gitattributes
文件中的设置将应用于您的项目。请注意,在这个过程中,您可能需要解决一些合并冲突。
检查 .gitattributes
文件是否生效
-
检查文件的行尾符:针对一个或多个文件检查行尾符,以确保它们符合
.gitattributes
文件中的设置。您可以使用文本编辑器或命令行工具(如cat -e
或od -c
)查看文件的行尾符。 -
使用
git diff
:当.gitattributes
生效时,将不再显示行尾符差异。运行git diff
查看任何更改。如果您没有看到与行尾符相关的差异(例如,整个文件被更改),那么.gitattributes
可能已生效。 -
检查 Git 转换:您还可以通过添加一个新文件来检查 Git 是否正确执行了转换。在
.gitattributes
中添加一个规则,如*.txt text eol=lf
,然后创建一个具有 CRLF 行
尾符的文本文件。接下来,将该文件添加到 Git,并使用文本编辑器检查提交后的行尾符。如果行尾符已更改为 LF,则 .gitattributes 文件生效。
请注意,如果 .gitattributes 文件不起作用,您可能需要重新执行前面的答案中所述的步骤。确保您正确地创建和更新了 .gitattributes 文件,并且已将其添加到 Git。
总结
.gitattributes 文件是一个非常有用的工具,用于控制 Git 如何处理特定文件类型的属性。通过遵循本文档中的说明,您可以更好地控制项目中的文件设置,确保 .gitattributes 文件正确生效。