🐡

GitHub Actions でデフォルトブランチを取得する

2021/03/05に公開

デフォルトブランチの取得

ワークフロー内でデフォルトブランチを取得する方法を 3 種類紹介します。

github コンテキスト

push イベントや pull_request イベントでは github コンテキスト が使えます。
${{ github.event.repository.default_branch }} を参照します。

.github/workflows/default-branch.yml
name: Default branch

on:
  push:
    paths:
      - .github/workflows/default-branch.yml

jobs:
  build:
    runs-on: ubuntu-latest

    steps:
      - run: echo ${{ github.event.repository.default_branch }}

GitHub API

octokit/request-action を使用して API 経由で取得します。
他のリポジトリも取得可能です。

.github/workflows/default-branch.yml
      - uses: octokit/request-action@v2.x
        id: repository
        with:
          route: GET /repos/${{ github.repository }}
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} # or ${{ github.token }}
      - run: echo ${{ fromJson(steps.repository.outputs.data).default_branch }}

Git コマンド

actions/checkoutref を指定しなければデフォルトブランチでチェックアウトされます。
一度チェックアウトして git rev-parse コマンドで取得します。
他のリポジトリも取得可能です。

.github/workflows/default-branch.yml
      - uses: actions/checkout@v2
      - run: git rev-parse --abbrev-ref HEAD

Discussion