Update GitLab Repository Default Branch from Master to Main

Posted on Jan 3, 2021
  1. Create a new branch called main
  2. Set main as the default branch
  3. Add protections to the main branch
  4. Update any GitLab CI to use main
  5. Unprotect the master branch
  6. Delete the master branch

Create main Branch

In the Web User Interface

  1. Navigate to the GitLab repository you want to update.
  2. Click the + dropdown menu.
  3. Click New branch
  4. Enter main as the Branch name
  5. Ensure Create from is set to master
  6. Click Create branch

In the Command Line

  1. git checkout master - switch to the master branch
  2. git pull - make sure the master branch is up to date
  3. git checkout -b main - create the main branch
  4. git push --set-upstream origin main - push the branch to GitLab

Set main as the Default Branch

  1. In your GitLab repository select Settings » Repository
  2. Expand the Default Branch section
  3. In the Detault Branch dropdown select main
  4. Ensure the Auto-close referenced issues on default branch checkbox is checked. This will close all open merge requests to the master branch because they will need to bo recreated against the main branch.
  5. Save changes

Protect the main Branch

  1. In your GitLab repository select Settings » Repository
  2. Expand the Protected Branches section
  3. Fill out the Protect a branch form
    1. Branch = main
    2. Allowed to merge = Maintaners, or whatever was set for the master branch. You can see the master branch settings below the form.
    3. Allowed to push = No one, or whatever was set for the master branch. I prefer not to let anyone to push directly to the default branch.
  4. Click Protect

Update CI

If you have a .gitlab-ci.yml file some of the continuous integration may revolve around the master branch. This will need to be updated to reference the main branch instead of master.

  1. Create a new branch git checkout -b fix/main-ci
  2. Edit your .gitlab-ci.yml file and update all occurrences of master with main.
    • If you are using vim you could accomplish this with :%s/master/main/g
    • Otherwise use the find replace functionality of your editor.
  3. Add, commit and push the changes.
    • git add *
    • git commit -m "updated ci to use main instead of master"
    • git push --set-upstream origin fix/main-ci
  4. Merge the changes into the main branch.

Unprotect the master Branch

  1. In your GitLab repository select Settings » Repository
  2. Expand the Protected Branches section
  3. In the protected branch listing at the bottom of the section click unprotect on the master row.

Delete the master branch

  1. In your GitLab repository select Repository » Branches
  2. Click the red trashcan icon on the master branch row.