action/github-script を使って、ワークフローのコンテキスト内で JavaScript を実行する

Today I Learned

action/github-script は、GitHub ワークフローのコンテキスト内で GitHub API をかんたんに実行できるアクションである。
このアクションでは Node.js の実行環境を提供しているので、シェル芸をせずに JavaScript で処理を書くことができる。

example.yml
jobs:
  say-hello:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/github-[email protected]
        with:
          script: |
            console.log("Hello world!");

actions/github-script の前のステップで npm install をすれば npm パッケージを利用できる。

example.yml
jobs:
  use-execa:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/setup-[email protected]
        with:
          node-version: 16
      - run: npm ci
      - uses: actions/github-[email protected]
        with:
          script: |
            const execa = require("execa");
            const { stdout } = await execa("echo", ["hello", "world"]);

リポジトリ内のファイルにアクセスするには、${{ github.workspace }} で始まるパスを書く。

example.yml
jobs:
  print-stuff:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/[email protected]
      - uses: actions/github-[email protected]
        with:
          script: |
            const json = require("${{ github.workspace }}/assets/data.json");
            console.log(JSON.stringify(json));