[GitHub Actions] 指定のBranchの存在チェックをする(git-fetchコマンド)

2022.05.30

この記事は公開されてから1年以上経過しています。情報が古い可能性がありますので、ご注意ください。

こんにちは、CX事業本部 IoT事業部の若槻です。

GitHub ActionsでBranchを作成する処理を実装する際に、作成前に対象のBranchが作成済みであるかチェックする必要が生じました。

そこで今回は、GitHub Actionsで指定のBranchの存在チェックをする方法を確認してみました。

確認してみた

色々模索したのですが、結論としてgit-fetchコマンドに落ち着きました。

git-fetchの仕様

git-fetchは、リモートなどのRepositoryからrefやobjectをダウンロードできるコマンドです。(普段Gitで開発をする人には馴染み深いコマンドかと思います。)

このgit-fetchコマンドを実行した際に、指定したBranchが対象のRepository上に存在していればExit Codeは0、存在していなければ128が返ります。

$ git fetch origin existing_branch
remote: Enumerating objects: 8, done.
remote: Counting objects: 100% (8/8), done.
remote: Compressing objects: 100% (3/3), done.
Unpacking objects: 100% (5/5), 762 bytes | 95.00 KiB/s, done.
remote: Total 5 (delta 2), reused 1 (delta 0), pack-reused 0
From github.com:cm-rwakatsuki/devio
 * branch              existing_branch -> FETCH_HEAD
 * [new branch]        existing_branch -> origin/existing_branch

$ echo $?                            
0

$ git fetch origin no_existing_branch
fatal: couldn't find remote ref no_existing_branch

$ echo $?                            
128

よって、このgit-fetchコマンドのExit Codeに応じて後続の処理を分岐させられます。

git-fetchの使用例

次のようにすれば、対象のBranchが存在しなければactionをFailさせられます。

.github/workflows/workflow.yml

    steps:
      - name: Checkout
        uses: actions/checkout@v3
      - name: Fail if the branch is not existing
        run: |
          git fetch origin ${BRANCH_NAME}

また次のようにBranchの存在有無を環境変数に格納して、後続のStepのif構文で使うこともできます。

.github/workflows/workflow.yml

    steps:
      - name: Checkout
        uses: actions/checkout@v3
      - name: Set whether the branch is already existing to GITHUB_ENV
        run: |
          branch_is_existing=$(
            git fetch origin ${NEW_BRANCH_NAME} &&
            echo true ||
            echo false
          )
          echo "BRANCH_IS_EXISTING=${branch_is_existing}" >> $GITHUB_ENV

      - name: Create branch
        if: env.BRANCH_IS_EXISTING == 'false'
        uses: EndBug/add-and-commit@v9
        with:
          new_branch: ${{ env.NEW_BRANCH_NAME }}

できそうで出来なかった方法

git-rev-parseコマンドを次のように使うと、指定したBranchが対象のRepository上に存在していればExit Codeは0、存在していなければ1が返ります。

$ git rev-parse --verify --quiet origin/existing_branch
488a19530c23dd53cf0a908d74458b7bc59abb58
$ echo $?                                              
0

$ git rev-parse --verify --quiet origin/no_existing_branch
$ echo $?                                              
1

チェックがしたいだけなら不要なダウンロードも走らないのでgit-rev-parseコマンドの方が良さそうですが、GitHub Actions上で使用すると、Branchの存在の有無に関わらずExit Codeが1になってしまうという動作となってしまいました。

この問題の解決はできず、結局git-fetchコマンドを採用するに至りました。

おわりに

GitHub Actionsで指定のBranchの存在チェックしてみました。

Exit Codeを意識するとGitHub Actionsで出来ることの幅がグッと広がりますね。

参考

以上