6

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?

John Bachir
  • 22,495
  • 29
  • 154
  • 227
  • 2
    How would this help you if you have a project which uses both `main` and `master` already, and your problem is that you are accidentally checking out the wrong one? (If that's not what your problem is I didn't understand your scenario) – mkrieger1 Sep 28 '21 at 22:21
  • Also what's the big deal? No law requires _you_ to have a local `master` ever, no matter what the remote has. – matt Sep 28 '21 at 22:34
  • Although I don't understand exactly what your problem is, have you looked into git hooks? – Marcello Romani Sep 28 '21 at 23:53
  • You could make a symlink (or symbolic ref) one to the other within your `.git/refs/heads` directory. Then regardless of which name you use, it will always refer to the same branch effectively. – Jeff Mercado Sep 29 '21 at 08:12
  • See https://stackoverflow.com/questions/549920/is-it-possible-to-alias-a-branch-in-git for what @JeffMercado suggested. – mkrieger1 Sep 29 '21 at 09:20

2 Answers2

3

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
John Bachir
  • 22,495
  • 29
  • 154
  • 227
  • branch names are purely repo-local, you can also `git checkout -tb master origin/main; git symbolic-ref refs/heads/{master,main}` and now your master and main branches are the same thing. – jthill Oct 02 '21 at 15:17
1

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.

LeGEC
  • 46,477
  • 5
  • 57
  • 104