シェルでGithubリポジトリのmasterブランチの名前をmainブランチに変更する
はじめに
随分前のことですが、新規に作成される Github リポジトリのデフォルトブランチ名が master から main に変更となりました。
ところが既存の Github リポジトリは当然 master というブランチ名のままです。
機会があれば昨今の風潮にのって一括修正しようかなぁ、と思っていましたが、ブログネタについでにシェルでブランチ名の変更を行ってみました。
大量に Github リポジトリを持っている組織などでも利用できるのではないでしょうか。
検証環境
今回利用するツール
今回は以下のツールを利用します。
git: Gitgh: GitHub CLI
作成したシェルスクリプト
コマンドを 1 つ 1 つ解説していこうかと思いましたが、作ってしまってそれをお見せしたほうが良いかと思いました。
作成したシェルスクリプトを掲載します。
master2main.sh
使い方
使い方は簡単です。
master ブランチを持っている Github ワークディレクトリ ( git clone したディレクトリのこと。 .git ディレクトリがあるはずですね。 ) で、スクリプトを実行するだけです。
複数の Github リポジトリを一括更新する
対象となる Git ワークディレクトリの一覧があれば、ループで回して一括更新できるはずです。
main ブランチへのリネーム後にメンバが実施する作業
以下のコマンドを実行し、 リモートリポジトリの main ブランチ、master ブランチへの修正をワークディレクトリに反映します。
せっかくなので Gist に公開しました
こちらはコメントが英語なので、苦手な方はエントリのコードを参照ください。
| #!/usr/bin/env bash | |
| # Magic | |
| set -o errexit | |
| set -o nounset | |
| type gh >/dev/null 2>&1 || { | |
| echo "[ERROR] gh command is not installed." >&2 | |
| exit 100 | |
| } | |
| # Assuming that the directory running the script is managed by .git | |
| [[ -d ./.git ]] || { | |
| echo "[ERROR] Run the script in your Git working directory." >&2 | |
| exit 101 | |
| } | |
| echo "=== START ===" | |
| REPO=$(git remote get-url origin | grep -o '[^/:]\+/[^/:]\+$' | sed 's/\.git$//') | |
| # Please change whether it is an upstream repository as appropriate | |
| REMOTE=origin | |
| # First, get the latest master information of Git's remote repository | |
| git fetch "${REMOTE}" master | |
| # Branch the main branch from the master branch | |
| git checkout -b main "${REMOTE}/master" \ | |
| --no-track | |
| # Push main branch to remote | |
| git push -u "${REMOTE}" main | |
| # Switch the HEAD of the repository to the main branch | |
| git remote set-head "${REMOTE}" main | |
| # Switch the default branch on Github to the main branch | |
| gh api -XPATCH "repos/${REPO}" -f default_branch=main >/dev/null | |
| # Switch the base of all pull requests on Github to the main branch | |
| for NUM in $( | |
| gh pr list -B master -L999 \ | |
| | cut -f 1 | |
| ); do | |
| gh api -XPATCH "repos/${REPO}/pulls/${NUM}" -f base=main >/dev/null | |
| done | |
| # Removed master branch from Github's remote repository | |
| git push \ | |
| --delete origin master | |
| # Delete local master branch | |
| git branch -D master | |
| # You can also open a web page in the Github repository for confirmation | |
| # gh repo view --web | |
| echo "=== FINISH ===" |
ひとこと
実際、これだけでは済まないですよね。
修正が必要だろうと思いつくものを上げると
- CI/CD パイプライン周り
- GitHub Actions
- Cloud Build
- CircleCI
- AWS や GCP の検証環境(もしブランチ名に依存していれば)
- Docker Hub
- Ansible Galaxy
- Slack 連携
1 リポジトリずつ、段階的に実施となるでしょう。









ディスカッション
コメント一覧
まだ、コメントがありません