Git excludesfile for a branch

Git does not support per-branch excludes files

You’re trying to achieve something that Git does not support. The blog post is the original source of this hoax that the Stack Overflow answer only parroted. As noted in comments under that answer, even the original blog post contains a discussion that brings out that the solution does not work and it links to a newer blog post that mentions that even the author is unable to reproduce the behavior.

Why it does not work? If you read man gitignore and man git-config, you’ll find just core.excludesfile referenced. No branch.<name>.excludesfile there. The core.excludesfile is meant to enable you to exclude e.g. Vim .swp files or other temporary stuff your software uses.

core.excludesfile

In addition to .gitignore (per-directory) and .git/info/exclude, Git looks into this file for patterns of files which are not meant to be tracked. “~/” is expanded to the value of $HOME and “~user/” to the specified user’s home directory. Its default value is $XDG_CONFIG_HOME/git/ignore. If $XDG_CONFIG_HOME is either not set or empty, $HOME/.config/git/ignore is used instead. See gitignore(5).

Workaround

I believe that the best approximation of a per-branch excludes file is achieved using the post-checkout hook and that rewrites the contents of .gitignore in the working tree.*

Each branch would have e.g. a .gitignores directory with files named after the corresponding branches. Then there would be a .gitignores/__default file that would be used by default. The .gitignore would be excluded by all the excludes files and would be created by the post-checkout hook as a copy of the corresponding file in .gitignores.

If you don’t want to track the excludes files, you may do the same with .git/info/exclude file as a copy of .git/info/excludes/__default etc.

*: Side note: I used to recommend making .gitignore a symlink updated by the hook to point to the right content, but .gitignore cannot be symlink since Git v2.32.0. Now, when editing the .gitignore, the changes are lost when switching branches, instead of being made to the branch’s custom excludes file.

Leave a Comment

tech