Working with a Git Branch Alias


Many of use prefer not to use “master” as the name of a Git branch, and have opted for something else (for example main) instead.

So we see that while the word master doesn’t always connote slave, for many, it’s evocative via basic word-association and they just don’t want to look at the word on their prompt all day. Choice is cool.

Scott Hanselman

For this reason all my various Git installations are configured to use a default of main and so are my cloud providers (in this case GitLab and GitHub). So far so hoopy, but sometimes I want to track an upstream that still follows the legacy convention.

Note that renaming an existing branch in a public repo that has been forked or cloned many times, is next to impossible, and there are legitimate reasons why a project maintainer cannot rename the master branch.

Just to make life fun for this demo I am hosting the upstream repo on GitHub and my “Downstream” repo on GitLab. I have the glab and gh CLI tools installed so I can do everything from the command line.

  1. Create an example upstream repo on GitHub and push some content:

    mkdir upstream
    cd upstream
    echo "I am the original repo that uses a master branch" > README.txt
    git init --initial-branch=master
    git config "" # Set email address
    git add .
    git commit -m "Initial Commit"
    git status
    gh repo create --public --source . --push
    cd ..

    Now we have a remote upstream repo on GitHub

  2. Now let’s create a repo that uses main and is hosted on GitLab:

    mkdir mybranchismain
    cd mybranchismain
    git init # Will use main by default
    git config "" # Set email address
    glab repo create --public # This will be my repo that uses main
  3. Now the clever bit. Set an alias so that the master branch points to main (assuming main is your default branch):

    # alias -> real branch
    git symbolic-ref refs/heads/master refs/heads/main

    Thanks to David Walsh for this tip

  4. Add the upstream remote:

    git remote add upstream
    git remote -v
  5. Pull the upstream content into you new empty repo:

    git pull upstream master
    git status
  6. Now push the pristine upstream content into your personal remote repo, using the main branch:

    git push origin main
  7. Add a change:

    echo "A Change added via a local main branch" >> README.txt
    git commit -am "A change on the main branch"
    git branch -vv
    git branch --track

    Notice that both main and master refer to the same commit.

    git push origin

There is a final corner case, which should probably not happen in real life because you will always deliver upstream changes via merge or pull request on a feature branch. But in case you do want to push to the upstream master branch you can do this.

git push upstream main:master
comments powered by Disqus