Write workflows scripting the GitHub API in JavaScript
Find a file
Rob Young 7dc493a321 Run script in GITHUB_WORKSPACE directory
Change to the GITHUB_WORKSPACE directory before running the script so
that callers do not have to exlicitly use the GITHUB_WORKSPACE
environment variable when requiring script files.

Workflow run steps are run within the GITHUB_WORKSPACE so this seems
like the expected default.
2021-04-08 14:14:14 +01:00
.github Fix typo from #117 2021-03-02 11:41:59 +00:00
.licenses/npm Add the @actions/glob package 2021-03-29 16:06:39 -07:00
.vscode Check in .vscode 2020-05-18 11:27:26 -04:00
__test__ Run script in GITHUB_WORKSPACE directory 2021-04-08 14:14:14 +01:00
dist Run script in GITHUB_WORKSPACE directory 2021-04-08 14:14:14 +01:00
docs Update development.md 2020-11-17 08:53:50 -05:00
src Run script in GITHUB_WORKSPACE directory 2021-04-08 14:14:14 +01:00
.eslintrc.yml Add ESLint and Prettier 2020-05-18 11:28:54 -04:00
.gitattributes Mark licenses as generated 2020-08-06 21:05:36 -04:00
.gitignore Check in .vscode 2020-05-18 11:27:26 -04:00
.licensed.yml Add production licenses with licensed 2020-08-06 20:27:06 -04:00
.prettierrc.yml Add ESLint and Prettier 2020-05-18 11:28:54 -04:00
action.yml Default to the GitHub token 2020-01-22 22:26:04 -05:00
CODEOWNERS Add CODEOWNERS 2020-12-09 15:58:34 -05:00
LICENSE.md Add license 2019-08-29 18:56:14 -04:00
package-lock.json Update version to 3.1.1 2021-03-30 14:00:42 -04:00
package.json Update version to 3.1.1 2021-03-30 14:00:42 -04:00
README.md Run script in GITHUB_WORKSPACE directory 2021-04-08 14:14:14 +01:00
tsconfig.json Add tests for the AsyncFunction 2020-02-27 17:27:49 -05:00

actions/github-script

.github/workflows/integration.yml .github/workflows/ci.yml .github/workflows/licensed.yml

This action makes it easy to quickly write a script in your workflow that uses the GitHub API and the workflow run context.

In order to use this action, a script input is provided. The value of that input should be the body of an asynchronous function call. The following arguments will be provided:

Since the script is just a function body, these values will already be defined, so you don't have to (see examples below).

See octokit/rest.js for the API client documentation.

Note This action is still a bit of an experiment—the API may change in future versions. 🙂

Development

See development.md.

Reading step results

The return value of the script will be in the step's outputs under the "result" key.

- uses: actions/github-script@v3
  id: set-result
  with:
    script: return "Hello!"
    result-encoding: string
- name: Get result
  run: echo "${{steps.set-result.outputs.result}}"

See "Result encoding" for details on how the encoding of these outputs can be changed.

Result encoding

By default, the JSON-encoded return value of the function is set as the "result" in the output of a github-script step. For some workflows, string encoding is preferred. This option can be set using the result-encoding input:

- uses: actions/github-script@v3
  id: my-script
  with:
    github-token: ${{secrets.GITHUB_TOKEN}}
    result-encoding: string
    script: return "I will be string (not JSON) encoded!"

Examples

Note that github-token is optional in this action, and the input is there in case you need to use a non-default token.

By default, github-script will use the token provided to your workflow.

Print the available attributes of context

- name: View context attributes
  uses: actions/github-script@v3
  with:
    script: console.log(context)

Comment on an issue

on:
  issues:
    types: [opened]

jobs:
  comment:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/github-script@v3
        with:
          github-token: ${{secrets.GITHUB_TOKEN}}
          script: |
            github.issues.createComment({
              issue_number: context.issue.number,
              owner: context.repo.owner,
              repo: context.repo.repo,
              body: '👋 Thanks for reporting!'
            })            

Apply a label to an issue

on:
  issues:
    types: [opened]

jobs:
  apply-label:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/github-script@v3
        with:
          github-token: ${{secrets.GITHUB_TOKEN}}
          script: |
            github.issues.addLabels({
              issue_number: context.issue.number,
              owner: context.repo.owner,
              repo: context.repo.repo,
              labels: ['Triage']
            })            

Welcome a first-time contributor

on: pull_request

jobs:
  welcome:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/github-script@v3
        with:
          github-token: ${{secrets.GITHUB_TOKEN}}
          script: |
            // Get a list of all issues created by the PR opener
            // See: https://octokit.github.io/rest.js/#pagination
            const creator = context.payload.sender.login
            const opts = github.issues.listForRepo.endpoint.merge({
              ...context.issue,
              creator,
              state: 'all'
            })
            const issues = await github.paginate(opts)

            for (const issue of issues) {
              if (issue.number === context.issue.number) {
                continue
              }

              if (issue.pull_request) {
                return // Creator is already a contributor.
              }
            }

            await github.issues.createComment({
              issue_number: context.issue.number,
              owner: context.repo.owner,
              repo: context.repo.repo,
              body: 'Welcome, new contributor!'
            })            

Download data from a URL

You can use the github object to access the Octokit API. For instance, github.request

on: pull_request

jobs:
  diff:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/github-script@v3
        with:
          github-token: ${{secrets.GITHUB_TOKEN}}
          script: |
            const diff_url = context.payload.pull_request.diff_url
            const result = await github.request(diff_url)
            console.log(result)            

(Note that this particular example only works for a public URL, where the diff URL is publicly accessible. Getting the diff for a private URL requires using the API.)

This will print the full diff object in the screen; result.data will contain the actual diff text.

Run custom GraphQL queries

You can use the github.graphql object to run custom GraphQL queries against the GitHub API.

jobs:
  list-issues:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/github-script@v3
        with:
          github-token: ${{secrets.GITHUB_TOKEN}}
          script: |
            const query = `query($owner:String!, $name:String!, $label:String!) {
              repository(owner:$owner, name:$name){
                issues(first:100, labels: [$label]) {
                  nodes {
                    id
                  }
                }
              }
            }`;
            const variables = {
              owner: context.repo.owner,
              name: context.repo.repo,
              label: 'wontfix'
            }
            const result = await github.graphql(query, variables)
            console.log(result)            

Run a separate file

If you don't want to inline your entire script that you want to run, you can use a separate JavaScript module in your repository like so:

on: push

jobs:
  echo-input:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
      - uses: actions/github-script@v3
        with:
          script: |
            const script = require(`./path/to/script.js`)
            console.log(script({github, context}))            

The script will be run within the GITHUB_WORKSPACE directory.

And then export a function from your module:

module.exports = ({github, context}) => {
  return context.payload.client_payload.value
}

You can also use async functions in this manner, as long as you await it in the inline script.

Note that because you can't require things like the GitHub context or Actions Toolkit libraries, you'll want to pass them as arguments to your external function.

Additionally, you'll want to use the checkout action to make sure your script file is available.

Use npm packages

Like importing your own files above, you can also use installed modules:

on: push

jobs:
  echo-input:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
      - uses: actions/setup-node@v2
        with:
          node-version: 14
      - run: npm ci
      # or one-off:
      - run: npm install execa
      - uses: actions/github-script@v3
        with:
          script: |
            const execa = require(`${process.env.GITHUB_WORKSPACE}/node_modules/execa`)

            const { stdout } = await execa('echo', ['hello', 'world'])

            console.log(stdout)            

Use env as input

You can set env vars to use them in your script:

on: push

jobs:
  echo-input:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/github-script@v3
        env:
          FIRST_NAME: Mona
          LAST_NAME: Octocat
        with:
          script: |
            const { FIRST_NAME, LAST_NAME } = process.env

            console.log(`Hello ${FIRST_NAME} ${LAST_NAME}`)