Reversing .gitignore: Ignore Everything by Default to Prevent Unwanted Commits
2 min read
Developers often face the issue of accidentally committing unwanted files such as .DS_Store, node_modules, or IDE configuration files into their Git repositories. This typically leads to a cleanup process involving updating .gitignore and removing those files from the repository history. An alternative approach proposes flipping this workflow: instead of tracking everything by default and selectively ignoring files, ignore all files by default and explicitly allow only specific ones.
For example, a simple .gitignore for a Go project could look like this:
*
!.gitignore
!*.go
!README.md
!go.mod
!go.sum
This configuration tells Git to ignore all files except the .gitignore itself, Go source files, the README, and Go module files. By doing so, only the files explicitly permitted are tracked, minimizing the risk of accidentally committing local or irrelevant files.
While this method may not suit every project or developer, it offers a practical alternative, especially for projects cluttered with various local files and folders. Large .gitignore files, such as the 207-line one used in typescript-go, highlight the complexity of managing ignored files in some projects.
To troubleshoot ignored files, developers can use the command 'git check-ignore -v ' to verify if a file is being ignored and by which rule. Additionally, tools like lazygit provide a user-friendly terminal interface for managing Git repositories more efficiently.
This approach encourages a more deliberate and controlled tracking of files, helping maintain cleaner repositories and reducing accidental commits of unnecessary files.