LoginSignup
0
0
この記事誰得? 私しか得しないニッチな技術で記事投稿!
Qiita Engineer Festa20242024年7月17日まで開催中!

[GitHub Actions] 特定の文字列を含むブランチ名にエラーを突きつける

Last updated at Posted at 2024-06-29

この記事が役立つかもしれない人

  • 特定の文字列を含むブランチ名を使って欲しくない場合
    • ビルド時の都合でブランチ名に特定の文字列を含めず作成して欲しい! 等
  • Rulesets を使いたかったけど何らかの理由で使えないので代替手段が知りたい人

結論

ワークフローファイルとシェルスクリプトを作成し、push されたブランチ名が禁止リストにあるパターンを含んでいるかどうかをチェックします。

ディレクトリ構造
.
└── 📁 .github
    └── 📁 workflows
        ├── 📄 check-branch-name.yml
        └── 📁 scripts
            └── 📄 check-prohibited-branch-name.sh
check-branch-name.yml
name: Check Branch Name
on: [push]
jobs:
  check-prohibited-branch-name:
    runs-on: ubuntu-latest
    strategy:
      fail-fast: false
      matrix:
        prohibition:
          - pattern: "{ここに禁止したい文字列を入力}"
    steps:
      - name: Check out the repository
        uses: actions/checkout@v4

      - name: Validate branch (not include "${{ matrix.prohibition.pattern }}")
        run: |
          chmod +x .github/workflows/scripts/check-prohibited-branch-name.sh
          .github/workflows/scripts/check-prohibited-branch-name.sh ${{ github.ref_name }} ${{ matrix.prohibition.pattern }}
check-prohibited-branch-name.sh
#!/bin/sh

# 引数で受け取ったブランチ名と禁止パターンを変数に格納
branch_name=$1
prohibited_name=$2

echo "Checking branch name: $branch_name"

# ブランチ名に禁止パターンが含まれているかチェック
if echo "$branch_name" | grep -qE "$prohibited_name"; then
  echo "Error: branch name cannot include '$prohibited_name'."
  exit 1
fi

echo "Branch name is valid."

実行結果

prohibition-word という文字列を禁止パターンとして設定した上で、prohibition-word というブランチを作成すると Actions にエラーが出力されます。

prohibition-word という文字列を禁止パターンとして設定した上で prohibition-word というブランチを作成して push した様子

なお判定は禁止パターンを含んでいるか?で行っているため、ブランチ名が prohibition-word-hoge の場合でも同様にエラーが出力されます。

解説

GitHub Actions お馴染みの yaml ファイルからシェルスクリプトを呼び出しています。

run: |
  # check-branch-name.sh が実行できるように権限を付与
  chmod +x .github/workflows/scripts/check-branch-name.sh
  # 実行
  .github/workflows/scripts/check-branch-name.sh ${{ github.ref_name }} ${{ matrix.prohibition.pattern }}

シェルスクリプトには github.ref_namematrix.prohibition.pattern という値を渡しています。

それぞれ github.ref_name には push されたブランチ名、matrix.prohibition.pattern には matrix で指定した禁止したい文字列が入っています。

これらを用いて push されたブランチ名が禁止されたパターンを含むかどうか判定し、もし github.ref_namematrix.prohibition.pattern が含まれていた場合はスクリプトを停止してエラーを返します。

複数の禁止名を設定する方法

複数の禁止名を設定したい場合は matrix で複数定義することが可能です。

matrix:
  prohibition:
    - pattern: "sample1"
    - pattern: "sample2"
    - pattern: "sample3"

これによりチェック対象のブランチ名が複数の禁止パターンのいずれかに一致した場合にエラーを返します。


GitHub Actions を使用して特定の文字列を含むブランチ名を禁止する方法を解説しました。
この記事が役に立ったら 🩷 を頂けると嬉しいです!

0
0
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
0
0