```.gitignore 默认忽略所有文件```
.gitignore Everything by Default

原始链接: https://packagemain.tech/p/gitignore-everything-by-default

作者建议摒弃在巨大的 `.gitignore` 文件中列出所有忽略项的传统做法,转而采用相反的工作流:**默认忽略所有内容,仅显式添加需要追踪的文件。** 这种“白名单”方法可以防止意外提交 `.DS_Store`、`node_modules` 或敏感环境变量等垃圾文件。通过使用严格的 `.gitignore` 配置,开发者能够确保只有必要的文件进入存储库,从而避免复杂项目中常见的臃肿问题。 虽然这种方法并不适用于所有工作流,但它为管理冗长、多行的忽略文件提供了一种更简洁的替代方案。针对此配置的排查,作者建议使用 `git check-ignore` 来验证哪些路径已被排除。文章最后推荐将 *lazygit* 作为管理此类 Git 工作流的必备工具。

Hacker News 上关于 Git 仓库“默认忽略所有文件”这一提议的讨论,揭示了开发者理念上的严重分歧。 支持“白名单”方案的人认为,这可以作为一种安全保障,防止意外提交密钥、二进制文件或“垃圾”文件。他们将其比作网络安全(默认阻止所有端口),并认为这能促使开发者更好地整理文件,避免配置臃肿。 然而,许多资深开发者强烈反对这一做法,称其为“糟糕的建议”。他们的主要论点包括: * **可见性降低:** 忽略所有文件会掩盖未追踪的文件,导致开发者容易遗忘必要的项目资产,或在切换分支时丢失工作成果。 * **工作流摩擦:** 这迫使开发者必须为每种新文件类型不断更新忽略规则,产生不必要的开销。 * **“更好的方法”:** 批评者认为,问题不在于 Git 本身,而在于懒惰的习惯(例如盲目使用 `git add .`)。他们建议使用全局 `~/.gitignore` 文件来处理操作系统产生的垃圾文件(如 `.DS_Store`),利用交互式暂存(`git add -p`),并依靠代码审查和 CI/CD 流水线来捕获错误。 目前的共识倾向于保持良好的工作习惯——即关注所暂存的内容,而不是实施全局性的限制默认值。
相关文章

原文

I think we’ve all been there. You’re working on a project, making commits, and then suddenly realize you’ve been committing .DS_Store files, node_modules, IDE configuration files, or other junk (CLAUDE.md for example) that shouldn’t be in your repository. Or even worse - environment variables. Then comes the embarrassing cleanup: adding these files to .gitignore, removing them from the repository history, and hoping that no one has noticed.

What if we flipped this approach entirely? Instead of allowing everything by default and selectively ignoring files, what if we ignored everything by default and only allowed specific files?

Here’s what this could look like in practice for a simple Go project:

This .gitignore file does exactly that:

But not these files...

  • !.gitignore - the gitignore file itself

  • !*.go - Go source files

  • !go.mod - Go module file

  • !go.sum - Go dependencies file

  • anything else you wish to include

With this setup, only the files you explicitly allow will be tracked by Git. No more accidental commits of unintended local files.

The technique isn’t necessarily the right choice for every repository or developer, but is an alternative to explore.

Nowadays, I see that projects have so much crap locally, like various agentic docs or subfolders, so it may seem easier to just ignore everything at first.

Just look at this 207-lines .gitignore from typescript-go.

p.s. if you want to check if the path is ignored by git, you can run this command:

This can save a lot of head-scratching when a file you expected to track doesn’t appear in Git.

p.s. have you heard of lazygit? The best Git TUI out there, check it out.

Discuss this post on Hacker News.

联系我们 contact @ memedata.com