はなちるのマイノート

Unityをメインとした技術ブログ。自分らしくまったりやっていきたいと思いますー!

【Actions, PowerShell】GitHub APIを利用してpushの際に変更されたファイルの一覧を取得する(github.event.head_commit.modifiedは廃止されたので注意)

はじめに

今回はpushの際に変更されたファイルの一覧を取得する方法を紹介したいと思います。

変更されたファイルを一覧で表示している様子

github.event.head_commit.modified廃止

昔はgithub.event.head_commit.modifiedでpushイベントがトリガーされたときに変更されたファイルのリストを取得することができていたのですが、どうやら廃止されてしまったようです。
github.blog

その代用案としてGitHub APIを利用してねということでした。

# GitHub CLI api
# https://cli.github.com/manual/gh_api

gh api \
  -H "Accept: application/vnd.github+json" \
  -H "X-GitHub-Api-Version: 2022-11-28" \
  /repos/OWNER/REPO/commits/REF

docs.github.com

方針

GITHUB_EVENT_PATHを利用してトリガーされたイベントペイロードからコミットSHAとリポジトリのフルネームを取得した後、GitHub APIを利用してコミット情報を取得します。

GITHUB_EVENT_PATH
完全なイベント Webhook ペイロードを含むランナー上のファイルへのパス。 たとえば、/github/workflow/event.json のようにします。

変数に情報を格納する - GitHub Docs

コード

name: test
on:
  push:

jobs:
  enumerate-changed-files:
    runs-on: ubuntu-latest
    steps:
      - env:
          GH_HOST: github.com
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        shell: pwsh
        run: |
          # エラーがあれば即時終了させる
          $ErrorActionPreference = "Stop"
          $PSNativeCommandUseErrorActionPreference = $true

          # トレースログを有効にする
          Set-PSDebug -Trace 1

          try
          {
            # event payloadからcommit SHAとリポジトリのフルネームを取得する
            $eventPayload = Get-Content ${env:GITHUB_EVENT_PATH} | ConvertFrom-Json
            $commitSha = $eventPayload.after
            $repoFullName = $eventPayload.repository.full_name

            # GitHub APIを使ってコミット情報を取得する
            $apiResult = gh api `
              --hostname ${env:GH_HOST} `
              -H "Accept: application/vnd.github+json" `
              -H "X-GitHub-Api-Version: 2022-11-28" `
              -H "Authorization: token ${env:GH_TOKEN}" `
              /repos/${repoFullName}/commits/${commitSha}

            # 変更されたファイルの一覧を表形式で取得する
            ($apiResult | ConvertFrom-Json).files | Format-Table -AutoSize
          }
          catch
          {
            Write-Error $_
            Write-Error "エラーが発生したため、処理を中断します。"
            exit 1
          }
# 出力例
sha                                      filename
---                                      --------                              
b808d9dfec71122fd78b559dc9d8f02d21e8b10d .github/workflows/test.yml            
5e13b80bb6e300e055dc692e2d6f8cdca9a4a999 .idea/.idea.TestProject/.idea/.name   
7b08163cebc50fb3e777eea4881b68fcebc10590 .idea/.idea.TestProject/.idea/indexLa…
35eb1ddfbbc029bcab630581847471d7f238ec53 .idea/.idea.TestProject/.idea/vcs.xml 

動作確認

Actions上で動作させている様子