🙏 请将 .gitattributes 添加到您的 Git 存储库什么是 .gitattributes?

2025-05-24

🙏 请将 .gitattributes 添加到你的 Git 存储库

什么是 .gitattributes?

什么是 .gitattributes?

.gitattributes文件允许您指定执行 git 操作时应该使用的文件和路径属性,例如git commit等。

换句话说,每次创建或保存文件时,git 都会根据指定的属性自动保存文件。

这些属性之一是eol(行尾),用于配置文件的行尾。本文将深入探讨如何配置行尾,以便每个开发人员在存储库中使用不同的机器/操作系统时使用相同的值。

为什么是 .gitattributes(Developers At War ⚔️)?

并非所有开发人员都一样,仅仅因为您使用 Visual Studio Code 在 Windows 机器上进行开发,不要期望下一个拉取请求使用相同的开发环境(使用 Sublime Text 2 的 MacOS 机器)实现。

如上所述,由于开发人员使用的操作系统(Windows 和 MacOS)不同,行尾的默认设置也有所不同。在 Windows 系统中,行尾的默认设置是回车符 ( CRLF ),而在 Linux/MacOS 系统中,行尾的默认设置是换行符 ( LF )。

肉眼看来,内容都是一样的,所以我们为什么要费心呢???

好吧,如果您启用了 Prettier 并且将endOfLine属性设置为lf



{
  "endOfLine": "lf"
}


Enter fullscreen mode Exit fullscreen mode

在 Windows 机器上,开发人员会遇到 Prettier 的 linting 问题,如下所示。

带有 Prettier Linting 错误的代码文件 - .gitattributes

包含 Prettier Linting 错误的代码文件

这时 .gitattributes 就可以发挥作用并挽救局面了🦸!

新建存储库(Repo)

要将 .gitattributes 添加到 repo,首先需要在 repo 的根文件夹中创建一个名为 .gitattributes 的文件。

以下是 .gitattributes 文件内容的示例。



*.js    eol=lf
*.jsx   eol=lf
*.json  eol=lf



Enter fullscreen mode Exit fullscreen mode

将此文件提交到 repo 并将更改推送到服务器。



git add .
git commit -m "Added .gitattributes to repo"
git push


Enter fullscreen mode Exit fullscreen mode

现在,当任何人从 repo 获取代码时,在创建和修改文件时,将通过 git 自动使用默认的正确行尾。

添加到现有的 Git 存储库 (Repo)

按照新建仓库 (Repo)的步骤创建 .gitattributes 文件。将文件推送到 git 服务器后,请确保本地仓库是干净的,没有任何需要提交的内容。使用此命令git status可以确定你的仓库是否干净。



git status


Enter fullscreen mode Exit fullscreen mode

注意:如果您仍有文件需要推送或提交,请确保在执行下一个命令之前执行这些操作或存储文件。

GitAttributes 重置



git rm --cached -r .
git reset --hard


Enter fullscreen mode Exit fullscreen mode

上述命令现在将使用 .gitattributes 中指定的新定义的行结尾来更新 repo 的文件。

任何更改或新更改都将自动使用为该文件类型指定的行尾。

下一步是通知任何队友或合作者运行GitAttributes Reset命令。

现在 Prettier 不会再抱怨 CR,所有开发者都可以安心生活了!☮️

没有 Linting 错误的代码文件 - .gitattributes

没有 Prettier Linting 错误的代码文件
文章来源:https://dev.to/deadlybyte/please-add-gitattributes-to-your-git-repository-1jld
PREV
25 年的编程生涯,我才刚刚开始
NEXT
停止使用“data”作为变量名