Home > Back-end >  Is there a way to disallow creating a git branch with a particular name, locally?
Is there a way to disallow creating a git branch with a particular name, locally?

Time:10-03

I have some projects which use "master" and others which use "main" and I am constantly accidentally checking out one or the other. The big problem is when on a project that uses "main" and also heroku, which uses "master", so git checkout master succeeds and seems normal.

Is there a way to configure something locally so that creating this branch will blow up?

CodePudding user response:

Here's what I came up with in .git/hooks/post-checkout

if [ `git branch --show-current` == "master" ]; then
  echo "DO NOT USE MASTER"
  git checkout main
  git branch -d master
fi

CodePudding user response:

I don't know of a way integrated to git to do that.

You may write post-checkout hook, that would either prevent switch automatically to the other branch, or write a warning big enough on your screen when it detects you are on the "bad" branch ; plus a pre-push hook that would prevent to push the "bad" branch to the remote.


Two quick and dirty hacks :

  • create an empty file under .git/refs/heads, and make that file read only :
# under linux :
touch .git/refs/heads/main
chmod a-rwx .git/refs/heads/main

The file seems to stay there even when git pack-refs runs, but I haven't checked if it would be kept in all scenarios.

  • create a branch main/dontcreate in your local repository

In its current implementation, git doesn't allow to have both a branch named main and branches named main/something -- git still wants to be able to create files under .git/refs/heads to represent branches, and this would create both a file and a directory with the same name.


Note that both these hacks rely on the current implementation of git (git v2.33 at the moment), which could change in a future version.

  •  Tags:  
  • git
  • Related