たろすの技術メモ

Jot Down the Tech

ソフトウェアエンジニアのメモ書き

GitHub ActionsのDangerでcouldn't find remote ref refs/heads/danger_base, danger_headエラー

はじめに

ある日、Pull requestを作成した時に走るDangerが表題のエラーで落ちたので解決法を調べました。

実行コマンド

$ bundle exec danger --fail-on-errors=true

エラーログ(抜粋)

fatal: couldn't find remote ref refs/heads/danger_base
fatal: couldn't find remote ref refs/heads/danger_head

...

Cannot find a merge base between danger_base and danger_head. If you are using shallow clone/fetch, try increasing the --depth (RuntimeError)

BaseブランチとHEADブランチが見つからないというエラーです。以下のようにfetch-depth: 0を指定すれば(デフォルトは1)、すべてのgit履歴を取得するのでエラーは解消されますが、毎回すべて取得するのは効率が悪いので別の手段を考えました。

uses: actions/checkout@v3
  with:
  fetch-depth: 0

Dangerコマンドの前にBaseブランチとHEADブランチをfetchする

以下のように明示的にブランチを指定するとエラーは解消されました。

- name: Fetch base and head branches
  run: |
    git fetch origin ${{ github.base_ref }}:${{ github.base_ref }}
    git fetch origin ${{ github.head_ref }}:${{ github.head_ref }}
- name: Run Danger
  run: bundle exec danger --head=${{ github.head_ref }} --base=${{ github.base_ref }} --fail-on-errors=true
  env:
    DANGER_GITHUB_API_TOKEN: ${{ secrets.GITHUB_TOKEN }}

おわりに

これがベストプラクティスかどうか分からないので知っている方いれば教えてください。