Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to disallow creating a git branch with a particular name, locally?

Tags:

git

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?

like image 957
John Bachir Avatar asked Sep 28 '21 22:09

John Bachir


2 Answers

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
like image 84
John Bachir Avatar answered Oct 24 '22 13:10

John Bachir


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.

like image 42
LeGEC Avatar answered Oct 24 '22 13:10

LeGEC