Read more

How to make your git aliases work with both master and main

Michael Leimstädtner
January 24, 2023Software engineer at makandra GmbH

The linked article Show archive.org snapshot found a simple way to rewrite legacy git aliases to make them work with differently named default branches

  • Step 1: Decide which is the most common default branch name of your projects, e.g. master. Define it as the global init.defaultBranch git configuration :
git config --global init.defaultBranch master
  • Step 2: Overwrite the value in each project directory that uses different defaults
# cd /path/to/project, then run:
git config --local init.defaultBranch main
  • Step 3: Adjust your ~/.gitconfig aliases to use the defaultBranch variable, e.g.:
[alias]
  merge_request = push origin HEAD -o merge_request.create -o merge_request.target=master -o merge_request.draft
Illustration web development

Do you need DevOps-experts?

Your development team has a full backlog? No time for infrastructure architecture? Our DevOps team is ready to support you!

  • We build reliable cloud solutions with Infrastructure as code
  • We are experts in security, Linux and databases
  • We support your dev team to perform
Read more Show archive.org snapshot

becomes

[alias]
  merge_request = !git push origin HEAD -o merge_request.create -o merge_request.target="$(git config init.defaultBranch)" -o merge_request.draft
  • Step 3: Adjust your ~/.bashrc aliases to use the defaultBranch variable
alias gdm='git diff --color-moved=dimmed_zebra master'

becomes

alias gdm="git diff --color-moved=dimmed_zebra $(git config init.defaultBranch)"

Caveat

Aliases are evaluated only once whenever you open a new terminal. This means that you cannot expect these aliases to adjust when you cd from one project into another. You need to open a new shell in this case (or source the ~/.bashrc).

You can work around this by evaluating the expression every time the command runs:

alias gdm="git config init.defaultBranch | xargs git diff --color-moved=dimmed_zebra"

If you want to use other aliases (like gd for git diff) and other argument positioning for the default branch name, you may use this monstrosity:

alias diff-stats-for-default-branch="git config init.defaultBranch | xargs -i ${BASH_ALIASES[gd]} {} --stat"
Posted by Michael Leimstädtner to makandra dev (2023-01-24 14:53)