I work on a bunch of different repos - many of them use master
, and many of them use main
.
I also have various shell aliases set up for git commands, e.g. gcm
for git checkout master
.
The problem is that I cannot use these aliases on repos where master
doesn't exist. It's obviously not a big deal, because I just need to type out the command manually in that case, but it's slightly annoying.
I am wondering if there's a way I can "alias" branches in git, so when I say git push origin master
it can just automatically replace that with main.
CodePudding user response:
You could use git show-ref -q
to check if the branch exists:
alias gcm='git show-ref -q --heads main && git checkout main || git checkout master'
You could write a shell function to return the default branch name:
default_branch_name() {
git show-ref -q --heads main && echo main || echo master
}
alias gcm="git checkout $(default_branch_name)"
That probably simplifies writing additional aliases.
The above assumes only two possible names for the primary branch. You could of course check for more:
default_branch_name() {
for name in master trunk main; do
git show-ref -q --heads $name && break
done
echo $name
}
CodePudding user response:
Your alias could be this:
alias gcm='git chheckout $(git config init.defaultBranch || echo master)'
Another idea is: HEAD
actualle is like an alias:
> cat .git/HEAD
ref: refs/heads/master
So perhaps this mechanism can be repurposed for a master
/ main
alias too. But this alias must be set up in each repository. So my choice would be the shell alias.
CodePudding user response:
In a repository that has main
, but not master
, the simplest is to create a branch alias master
that points to main
:
git symbolic-ref refs/heads/master refs/heads/main
This gives the following list of branches (for example):
$ git branch -a
* main
master -> main
side
Now everytime your commands reference master
they apply to main
. Even when you push master
, the actual target is main
:
$ git push origin master
Enumerating objects: 5, done.
Counting objects: 100% (5/5), done.
Writing objects: 100% (3/3), 241 bytes | 241.00 KiB/s, done.
Total 3 (delta 0), reused 0 (delta 0), pack-reused 0
To ../gitupstream
f57e131..15c1aad master -> main