LoginSignup
16
3

More than 3 years have passed since last update.

GitHub Actionsでブランチ名を扱う方法

Last updated at Posted at 2021-01-29

イベント別解説

起点とするイベントによって方法が異なるため、イベント別に解説します。
全ての例でechoコマンドでブランチ名を出力しています。

プルリクエストの時

on:
  pull_request:
    types: [opened, closed]

jobs:
  debug:
    runs-on: ubuntu-20.04
    timeout-minutes: 3
    steps:
      - name: Print branch name
        env:
          BRANCH_NAME: ${{github.head_ref}}
        run: echo $BRANCH_NAME
  • 以下2つの変数はプルリクエストを起点としたときだけ使用可能です。
    • マージするブランチ名は ${{github.head_ref}}
    • マージ先のブランチ名は ${{github.base_ref}}
  • typesを指定することで対応するアクティビティを指定できます。詳しくはこちら
  • 「プルリクエストがマージされた時」というアクティビティは存在しませんが、対応は可能です。詳しくはこちら

プッシュされた時

on: push

jobs:
  print:
    runs-on: ubuntu-20.04
    timeout-minutes: 3

    steps:
      - name: Extract branch name
        shell: bash
        run: echo "::set-output name=branch::${GITHUB_REF#refs/heads/}"
        id: extract_branch

      - name: Print branch name
        env:
          BRANCH_NAME: ${{ steps.extract_branch.outputs.branch }}
        run: echo $BRANCH_NAME

https://stackoverflow.com/questions/58033366/how-to-get-current-branch-within-github-actions から引用、一部改変

  • ブランチ名は環境変数 GITHUB_REF から抽出する必要があります。
  • ::set-output name=branch:: の記法はGitHub Actionsのメタデータ構文です。詳しくはこちら
  • ${GITHUB_REF#refs/heads/} の記法はShell Parameter Expantionを使ったものです。
  • 使える環境変数についてはこちら

ブランチが削除された時

  • リポジトリのデフォルトブランチ(main)しか取れないので省略します。

もともとやりたかったこと

  • こちらの記事を元に、
    • GitHubへのプッシュ時に、S3にブランチ名でprefixを分けてファイル配置
    • GitHubでプルリクエストのクローズ時に、プッシュ時に配置したファイルを削除
16
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
16
3