Local .gitignore files
February 2024
When I work with git, I find it beneficial to keep the .gitignore
patterns as close as possible to the files or directories they ignore. So instead of having all ignore patterns in a single .gitignore
file at the root of the repository, I prefer to split it into multiple local .gitignore
files. Here's why: when renaming directories, the ignore patterns don't need to be updated. It may seem like a minor benefit, but it's one less thing to worry about.
Let's see an example. Suppose we ignore the file backend/results.txt
and decide to rename the directory backend
to api
.
With only a single .gitignore
file at the root, the ignore pattern is expressed as an absolute path (well, relative from the root of the repository):
$ cat .gitignore
backend/results.txt
So when we rename backend
to api
, we must remember to update the .gitignore
file to reflect the renaming:
$ cat .gitignore
api/results.txt
However, by using a local .gitignore
file in the backend
directory, where the ignore pattern is expressed as a relative path to the current directory:
$ cat backend/.gitignore
results.txt
The .gitignore
file in the backend
directory automatically adapts to the renaming, eliminating the need for a manual update.
Call it laziness if you will, but I appreciate having one less thing to worry about, regardless of its magnitude.
Moreover, in the context of a git repository serving as a monorepo with dozens or hundreds of projects, maintaining local .gitignore
files will not only save a few edits when renaming directories but will reduce the risk of accidentally including files that should be ignored. Additionally, it helps keep the .gitignore
at the root of the repository relatively small, making it more manageable in the long run.
Like this article? Get notified of new ones: