### Install Dependencies with npm Source: https://github.com/actions/github-script/blob/main/docs/development.md Execute this command to install all necessary project dependencies. It's recommended to run this before building the action. ```shell npm install ``` -------------------------------- ### Use npm Packages with github-script Source: https://github.com/actions/github-script/blob/main/README.md Integrate npm packages into your scripts. Ensure Node.js is set up and packages are installed (e.g., via `npm ci` or `npm install`). This example uses the `execa` package to run a shell command. ```yaml on: push jobs: echo-input: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 with: node-version: '20.x' - run: npm ci # or one-off: - run: npm install execa - uses: actions/github-script@v9 with: script: | const execa = require('execa') const { stdout } = await execa('echo', ['hello', 'world']) console.log(stdout) ``` -------------------------------- ### Install @actions/github-script with JSDoc support Source: https://github.com/actions/github-script/blob/main/README.md Install the @actions/github-script package with type declarations for JSDoc support. This command adds the package as a development dependency. ```sh $ npm i -D @actions/github-script@github:actions/github-script ``` -------------------------------- ### Multiple clients for cross-org workflows Source: https://github.com/actions/github-script/blob/main/README.md Shows how to create multiple Octokit clients using `getOctokit` with different tokens for accessing repositories across multiple organizations. This example fetches repository data from two different organizations. ```yaml - uses: actions/github-script@v9 env: ORG_A_TOKEN: ${{ secrets.ORG_A_PAT }} ORG_B_TOKEN: ${{ secrets.ORG_B_PAT }} with: script: | const orgA = getOctokit(process.env.ORG_A_TOKEN) const orgB = getOctokit(process.env.ORG_B_TOKEN) const [repoA, repoB] = await Promise.all([ orgA.rest.repos.get({ owner: 'org-a', repo: 'service' }), orgB.rest.repos.get({ owner: 'org-b', repo: 'service' }) ]) console.log(`Org A: ${repoA.data.full_name}`) console.log(`Org B: ${repoB.data.full_name}`) ``` -------------------------------- ### Run Custom GraphQL Queries with github-script Source: https://github.com/actions/github-script/blob/main/README.md Utilize the `github.graphql` method to execute custom GraphQL queries against the GitHub API. This example fetches issue IDs for a specific label. ```yaml jobs: list-issues: runs-on: ubuntu-latest steps: - uses: actions/github-script@v9 with: 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) ``` -------------------------------- ### Custom Octokit options for GitHub Enterprise Server Source: https://github.com/actions/github-script/blob/main/README.md Demonstrates how to configure a custom Octokit client using `getOctokit` with specific options, such as `baseUrl` for connecting to a GitHub Enterprise Server (GHES) instance. This example lists repositories within a specified organization on GHES. ```yaml - uses: actions/github-script@v9 env: GHES_TOKEN: ${{ secrets.GHES_PAT }} with: script: | const ghes = getOctokit(process.env.GHES_TOKEN, { baseUrl: 'https://github.example.com/api/v3' }) const { data } = await ghes.rest.repos.listForOrg({ org: 'internal' }) console.log(`Found ${data.length} repos on GHES`) ``` -------------------------------- ### Get Command Output with @actions/exec Source: https://github.com/actions/github-script/blob/main/README.md Utilize the `exec.getExecOutput` function to execute a command and capture its exit code, standard output (stdout), and standard error (stderr). This is ideal when you need to process the results of a command. ```yaml on: push jobs: use-get-exec-output: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: actions/github-script@v9 with: script: | const { exitCode, stdout, stderr } = await exec.getExecOutput('echo', ['hello']); console.log(exitCode, stdout, stderr) ``` -------------------------------- ### Execute Command with @actions/exec Source: https://github.com/actions/github-script/blob/main/README.md Use the `exec.exec` function to run a command and get its exit code. This is useful for simple command execution where only the success or failure status is needed. ```yaml on: push jobs: use-exec: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: actions/github-script@v9 with: script: | const exitCode = await exec.exec('echo', ['hello']) console.log(exitCode) ``` -------------------------------- ### Download Data from URL with github-script Source: https://github.com/actions/github-script/blob/main/README.md Use the `github.request` method to fetch data from a URL. This example retrieves pull request diff data. Note that this works for public URLs; private URLs require API authentication. ```yaml on: pull_request jobs: diff: runs-on: ubuntu-latest steps: - uses: actions/github-script@v9 with: script: | const diff_url = context.payload.pull_request.diff_url const result = await github.request(diff_url) console.log(result) ``` -------------------------------- ### Enable JSDoc for GitHub Script Source: https://github.com/actions/github-script/blob/main/README.md Add a JSDoc comment to enable type checking and autocompletion for your GitHub script. This requires the @actions/github-script types to be installed. ```js // @ts-check /** @param {import('@actions/github-script').AsyncFunctionArguments} AsyncFunctionArguments */ export default async ({core, context}) => { core.debug('Running something at the moment') return context.actor } ``` -------------------------------- ### Use ESM import with github-script Source: https://github.com/actions/github-script/blob/main/README.md Import an ECMAScript module (ESM) by referencing its absolute path. A `package.json` file with `"type": "module"` is required. This example imports and executes a default export function. ```js export default function printStuff() { console.log('stuff') } ``` ```yaml on: push jobs: print-stuff: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: actions/github-script@v9 with: script: | const { default: printStuff } = await import('${{ github.workspace }}/src/print-stuff.js') await printStuff() ``` -------------------------------- ### Basic usage with primary and secondary tokens Source: https://github.com/actions/github-script/blob/main/README.md Demonstrates using the default `github` client (scoped to the current repository) and a secondary client created with `getOctokit` using a provided `APP_TOKEN`. ```yaml - uses: actions/github-script@v9 env: APP_TOKEN: ${{ secrets.MY_APP_TOKEN }} with: github-token: ${{ secrets.GITHUB_TOKEN }} script: | // `github` uses GITHUB_TOKEN (scoped to this repo) await github.rest.issues.addLabels({ issue_number: context.issue.number, owner: context.repo.owner, repo: context.repo.repo, labels: ['triage'] }) // `getOctokit` creates a second client with a different token const appOctokit = getOctokit(process.env.APP_TOKEN) await appOctokit.rest.repos.createDispatchEvent({ owner: 'my-org', repo: 'another-repo', event_type: 'trigger-deploy' }) ``` -------------------------------- ### Build the Action with npm Source: https://github.com/actions/github-script/blob/main/docs/development.md Run this command to compile the action's TypeScript code into JavaScript. This is a required step before using or testing the action. ```shell npm run build ``` -------------------------------- ### Run a Separate JavaScript File Source: https://github.com/actions/github-script/blob/main/README.md Execute a separate JavaScript module from your repository. Ensure the `actions/checkout` action is used to make the file available. The `github` and `context` objects are passed as arguments to the exported function. ```yaml on: push jobs: echo-input: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: actions/github-script@v9 with: script: | const script = require('./path/to/script.js') console.log(script({github, context})) ``` ```javascript module.exports = ({github, context}) => { return context.payload.client_payload.value } ``` -------------------------------- ### Run a Separate Async JavaScript File Source: https://github.com/actions/github-script/blob/main/README.md Execute an asynchronous JavaScript module. Use `await` in the inline script to handle the async function. The `github`, `context`, and `core` objects are passed as arguments. ```yaml on: push jobs: echo-input: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: actions/github-script@v9 env: SHA: '${{env.parentSHA}}' with: script: | const script = require('./path/to/script.js') await script({github, context, core}) ``` ```javascript module.exports = async ({github, context, core}) => { const {SHA} = process.env const commit = await github.rest.repos.getCommit ({ owner: context.repo.owner, repo: context.repo.repo, ref: `${SHA}` }) core.exportVariable('author', commit.data.commit.author.email) } ``` -------------------------------- ### Create additional Octokit clients with getOctokit Source: https://github.com/actions/github-script/blob/main/README.md Use the `getOctokit` function within a GitHub script to create authenticated Octokit clients. This is useful for interacting with the GitHub API using tokens other than the default `GITHUB_TOKEN`, such as PATs or GitHub App tokens. ```js getOctokit(token) getOctokit(token, opts) ``` -------------------------------- ### Welcome a First-Time Contributor Source: https://github.com/actions/github-script/blob/main/README.md Check if a pull request author is a first-time contributor by listing their issues and creating a welcome comment if they haven't contributed before. Uses `github.paginate` for handling API responses. ```javascript on: pull_request_target jobs: welcome: runs-on: ubuntu-latest steps: - uses: actions/github-script@v9 with: 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.rest.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.rest.issues.createComment({ issue_number: context.issue.number, owner: context.repo.owner, repo: context.repo.repo, body: `**Welcome**, new contributor! Please make sure you've read our [contributing guide](CONTRIBUTING.md) and we look forward to reviewing your Pull request shortly ✨` }) ``` -------------------------------- ### Read Step Results as Output Source: https://github.com/actions/github-script/blob/main/README.md The return value of the script is available in the step's outputs under the 'result' key. You can control the encoding of this output using the `result-encoding` input. ```yaml uses: actions/github-script@v9 id: set-result with: script: return "Hello!" result-encoding: string - name: Get result run: echo "${{steps.set-result.outputs.result}}" ``` -------------------------------- ### Pass Inputs via Environment Variables Source: https://github.com/actions/github-script/blob/main/README.md Pass inputs to the script by setting environment variables on the action step and referencing them using `process.env` in your script. This method helps prevent script injection vulnerabilities and syntax errors. ```yaml uses: actions/github-script@v9 env: TITLE: ${{ github.event.pull_request.title }} with: script: | const title = process.env.TITLE; if (title.startsWith('octocat')) { console.log("PR title starts with 'octocat'"); } else { console.error("PR title did not start with 'octocat'"); } ``` -------------------------------- ### Configure Request Retries Source: https://github.com/actions/github-script/blob/main/README.md Set the number of times requests made with the `github` instance should be retried upon failure. Default is no retries. ```yaml - uses: actions/github-script@v9 id: my-script with: result-encoding: string retries: 3 script: | github.rest.issues.get({ issue_number: context.issue.number, owner: context.repo.owner, repo: context.repo.repo, }) ``` -------------------------------- ### View Context Attributes Source: https://github.com/actions/github-script/blob/main/README.md Log all available attributes of the `context` object to the workflow run logs. Useful for exploring available information. ```yaml - name: View context attributes uses: actions/github-script@v9 with: script: console.log(context) ``` -------------------------------- ### Set Result Encoding to String Source: https://github.com/actions/github-script/blob/main/README.md Configure the action to return the script's output as a string instead of JSON. This is useful when the script's return value is not intended to be a JSON object. ```yaml - uses: actions/github-script@v9 id: my-script with: result-encoding: string script: return "I will be string (not JSON) encoded!" ``` -------------------------------- ### Version Bumping with npm Source: https://github.com/actions/github-script/blob/main/docs/development.md Use this command to update version numbers in package.json and package-lock.json without creating a Git tag. This allows for manual commit and tagging. ```shell npm version {major,minor,patch} --no-git-tag-version ``` -------------------------------- ### Configure Retry Exempt Status Codes Source: https://github.com/actions/github-script/blob/main/README.md Specify HTTP status codes that should not trigger a retry. By default, 400, 401, 403, 404, and 422 are exempt. ```yaml - uses: actions/github-script@v9 id: my-script with: result-encoding: string retries: 3 retry-exempt-status-codes: 400,401 script: | github.rest.issues.get({ issue_number: context.issue.number, owner: context.repo.owner, repo: context.repo.repo, }) ``` -------------------------------- ### Apply a Label to an Issue Source: https://github.com/actions/github-script/blob/main/README.md Add a label to a GitHub issue using the `github.rest.issues.addLabels` API. Requires the `issues` scope for the workflow token. ```yaml on: issues: types: [opened] jobs: apply-label: runs-on: ubuntu-latest steps: - uses: actions/github-script@v9 with: script: | github.rest.issues.addLabels({ issue_number: context.issue.number, owner: context.repo.owner, repo: context.repo.repo, labels: ['Triage'] }) ``` -------------------------------- ### Comment on an Issue Source: https://github.com/actions/github-script/blob/main/README.md Create a comment on a GitHub issue using the `github.rest.issues.createComment` API. Requires the `issues` scope for the workflow token. ```yaml on: issues: types: [opened] jobs: comment: runs-on: ubuntu-latest steps: - uses: actions/github-script@v9 with: script: | github.rest.issues.createComment({ issue_number: context.issue.number, owner: context.repo.owner, repo: context.repo.repo, body: '👋 Thanks for reporting!' }) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.