Skip to content

Instantly share code, notes, and snippets.

@mislav
Last active April 24, 2022 10:02
Show Gist options
  • Save mislav/5ac69530acbe1b4ca909e272caabfdba to your computer and use it in GitHub Desktop.
Save mislav/5ac69530acbe1b4ca909e272caabfdba to your computer and use it in GitHub Desktop.
Rename the default branch of a repository using GitHub CLI https://github.com/cli/cli/releases/tag/v0.10.0
#!/bin/bash
# Usage: gh-rename-master <newbranch> [<remote>]
#
# Renames the "master" branch of the current repository both locally and on GitHub.
#
# dependencies: GitHub CLI v0.10
set -e
newbranch="${1?}"
remote="${2:-origin}"
git fetch "$remote" master
git checkout -b "$newbranch" "${remote}/master" --no-track
git push -u "$remote" "$newbranch"
git remote set-head "$remote" "$newbranch"
# update the default branch
gh api -XPATCH "repos/:owner/:repo" -f default_branch="$newbranch" >/dev/null
# update the base branch of all open pull requests
for num in `gh pr list -B master -L999 | cut -f1`; do
gh api -XPATCH "repos/:owner/:repo/pulls/${num}" -f base="$newbranch" >/dev/null
echo -n .
done
printf '\nDone!\n'
@TiloGit
Copy link

TiloGit commented Mar 30, 2022

Hi @mislav ,

any tip how to use this in gh workflow/action?

I tried like this

      - name: Update Default Branch of GH rep
        run: |
          gh api -XPATCH "repos/$GITHUB_REPOSITORY" -f default_branch="$cpAppVersion" >/dev/null
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

and got:
gh: Resource not accessible by integration (HTTP 403)

@TiloGit
Copy link

TiloGit commented Mar 30, 2022

was due to limited access of default GITHUB_TOKEN. Need to use PAT.
Not sure what scope I need to set on PAT but "repo" seems to be enough.

so this worked (defined MYPTAGHTOKEN under Action secrets on repo with PAT)

      - name: Update Default Branch of GH rep
        run: |
          gh api -XPATCH "repos/$GITHUB_REPOSITORY" -f default_branch="$cpAppVersion" >/dev/null
        env:
          GITHUB_TOKEN: ${{ secrets.MYPTAGHTOKEN }}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment