### Install @actions/http-client Source: https://github.com/actions/toolkit/blob/main/packages/http-client/README.md Install the package using npm. This is a prerequisite for using the HTTP client in your actions. ```bash npm install @actions/http-client --save ``` -------------------------------- ### TypeScript Action Setup Source: https://github.com/actions/toolkit/blob/main/README.md Basic structure for a TypeScript Action, including importing 'core' and defining an async 'run' function to handle logic. Ensure '@actions/core' is installed. ```typescript import * as core from '@actions/core'; async function run() { try { const ms = core.getInput('milliseconds'); console.log(`Waiting ${ms} milliseconds ...`) ... ``` -------------------------------- ### Get Input and Log Message (JavaScript Action) Source: https://github.com/actions/toolkit/blob/main/README.md Example of how to retrieve an input and log a message in a JavaScript Action. Ensure 'core' is imported. ```javascript const nameToGreet = core.getInput('who-to-greet'); console.log(`Hello ${nameToGreet}!`); ``` -------------------------------- ### Install @actions/http-client Source: https://github.com/actions/toolkit/blob/main/README.md Installs the @actions/http-client package, a lightweight HTTP client optimized for building GitHub Actions. ```bash npm install @actions/http-client ``` -------------------------------- ### Install @actions/tool-cache Source: https://github.com/actions/toolkit/blob/main/README.md Installs the @actions/tool-cache package for downloading and caching tools, commonly used in setup-* actions. ```bash npm install @actions/tool-cache ``` -------------------------------- ### Install Dependencies Source: https://github.com/actions/toolkit/blob/main/packages/http-client/README.md Install project dependencies using npm. This command is typically run before building or testing. ```bash npm install ``` -------------------------------- ### YAML Example for Node.js Testing Strategy Source: https://github.com/actions/toolkit/blob/main/docs/action-types.md This YAML configuration demonstrates how to use a matrix strategy to test a Node.js application across different Node.js versions and operating systems. It includes steps for setting up Node.js, installing dependencies, running tests, and using a custom action. ```yaml on: push jobs: build: strategy: matrix: node: [8.x, 10.x] os: [ubuntu-16.04, windows-2019] runs-on: ${{matrix.os}} actions: - uses: actions/setup-node@v5 with: version: ${{matrix.node}} - run: | npm install - run: | npm test - uses: actions/custom-action@v1 ``` -------------------------------- ### Container Action with Toolkit and Context Source: https://github.com/actions/toolkit/blob/main/README.md Example of a container action using the Actions Toolkit to get input and access GitHub context. Ensure '@actions/core' and '@actions/github' are installed. ```javascript const myInput = core.getInput('myInput'); core.debug(`Hello ${myInput} from inside a container`); const context = github.context; console.log(`We can even get context data, like the repo: ${context.repo.repo}`) ``` -------------------------------- ### Toolkit Usage Example Source: https://github.com/actions/toolkit/blob/main/docs/adrs/0381-glob-module.md Example demonstrating how to use the glob module within an action, specifically opting out of following symbolic links. ```APIDOC ```js const patterns = core.getInput('path') const globber = glob.create(patterns, {followSymbolicLinks: false}) const files = globber.glob() ``` ``` -------------------------------- ### Install @actions/github Source: https://github.com/actions/toolkit/blob/main/README.md Installs the @actions/github package, which provides an Octokit client pre-configured with the current action's context. ```bash npm install @actions/github ``` -------------------------------- ### Complete Action Code Example Source: https://github.com/actions/toolkit/blob/main/docs/github-package.md This is a complete example of an action that sends a welcome message as a comment to an opened issue or pull request. It handles inputs, context, and API calls. ```typescript import * as core from '@actions/core'; import * as github from '@actions/github'; export async function run() { try { const welcomeMessage: string = core.getInput('welcome-message', {required: true}); const repoToken: string = core.getInput('repo-token', {required: true}); const issue: {owner: string; repo: string; number: number} = github.context.issue; if (github.context.payload.action !== 'opened') { console.log('No issue or pull request was opened, skipping'); return; } const client: github.GitHub = new github.GitHub(repoToken); await client.issues.createComment({ owner: issue.owner, repo: issue.repo, issue_number: issue.number, body: welcomeMessage }); } catch (error) { core.setFailed(error.message); throw error; } } run(); ``` -------------------------------- ### Initializing Octokit Client Source: https://github.com/actions/toolkit/blob/main/packages/github/README.md Demonstrates how to get an authenticated Octokit client using a GitHub token. It also shows how to pass additional options like a user agent. ```APIDOC ## Initialize Octokit Client ### Description Get an authenticated Octokit client to interact with the GitHub API. ### Method `getOctokit(token, options?) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript import * as github from '@actions/github'; import * as core from '@actions/core'; async function run() { const myToken = core.getInput('myToken'); const octokit = github.getOctokit(myToken); // Or with options: // const octokit = github.getOctokit(myToken, { userAgent: 'MyActionVersion1' }); // ... rest of your code } run(); ``` ### Response #### Success Response (200) An authenticated Octokit client instance. #### Response Example ```json { "data": "Octokit Client Instance" } ``` ``` -------------------------------- ### Install @actions/artifact Source: https://github.com/actions/toolkit/blob/main/README.md Installs the @actions/artifact package, enabling interaction with GitHub Actions artifacts. ```bash npm install @actions/artifact ``` -------------------------------- ### Importing Octokit with Dynamic Import Source: https://github.com/actions/toolkit/blob/main/packages/github/RELEASES.md This example shows how to use dynamic import for the Octokit client, which is necessary for ESM-only packages. ```javascript import {Octokit} from "@actions/github" ``` -------------------------------- ### Install @actions/io Source: https://github.com/actions/toolkit/blob/main/README.md Installs the @actions/io package, providing essential disk I/O functions such as copy, move, and remove recursively. ```bash npm install @actions/io ``` -------------------------------- ### Install @actions/core Source: https://github.com/actions/toolkit/blob/main/README.md Installs the @actions/core package, which provides functions for inputs, outputs, results, logging, secrets, and variables. ```bash npm install @actions/core ``` -------------------------------- ### Install @actions/glob Source: https://github.com/actions/toolkit/blob/main/README.md Installs the @actions/glob package, which enables searching for files that match specified glob patterns. ```bash npm install @actions/glob ``` -------------------------------- ### Toolkit Iterator Usage Example Source: https://github.com/actions/toolkit/blob/main/docs/adrs/0381-glob-module.md Example demonstrating the use of the `globGenerator` for iterating over matched files. ```APIDOC ```js const patterns = core.getInput('path') const globber = glob.create(patterns) for await (const file of this.globGenerator()) { console.log(file) } ``` ``` -------------------------------- ### Create Storage Record Example Source: https://github.com/actions/toolkit/blob/main/packages/attest/README.md Demonstrates how to use the `createStorageRecord` function to persist artifact metadata. Requires a GitHub token with repository write permissions. ```javascript const { createStorageRecord } = require('@actions/attest'); const core = require('@actions/core'); async function run() { // In order to persist attestations to the repo, this should be a token with // repository write permissions. const ghToken = core.getInput('gh-token'); const record = await createStorageRecord( artifactOptions: { name: 'my-artifact-name', digest: { 'sha256': '36ab4667...'}, version: "v1.0.0" }, packageRegistryOptions: { registryUrl: "https://my-fave-pkg-registry.com" }, token: ghToken ); console.log(record); } run(); ``` -------------------------------- ### HashFiles Function: Opt-in Symbolic Links Source: https://github.com/actions/toolkit/blob/main/docs/adrs/0381-glob-module.md YAML example demonstrating how to opt-in to following symbolic links for the `hashFiles` function. By default, `hashFiles` does not follow symbolic links. ```yaml jobs: build: steps: - uses: actions/cache@v1 with: hash: ${{ hashFiles('--follow-symbolic-links', '**/package-lock.json') }} ``` -------------------------------- ### Install and Import @actions/artifact Source: https://github.com/actions/toolkit/blob/main/packages/artifact/README.md Install the package using npm and import the DefaultArtifactClient for use in your project. Supports both ES6 modules and CommonJS. ```bash npm i @actions/artifact ``` ```javascript // ES6 module import {DefaultArtifactClient} from '@actions/artifact' // CommonJS const {DefaultArtifactClient} = require('@actions/artifact') const artifact = new DefaultArtifactClient() ``` -------------------------------- ### Install @actions/attest Source: https://github.com/actions/toolkit/blob/main/README.md Installs the @actions/attest package, which provides functions for generating attestations for workflow artifacts. ```bash npm install @actions/attest ``` -------------------------------- ### Mock Octokit Client Call Source: https://github.com/actions/toolkit/blob/main/docs/github-package.md Example of mocking a client.issues.createComment call using nock for testing purposes. Ensure nock is installed as a dev dependency. ```typescript client.issues.createComment({ owner: 'foo', repo: 'bar', issue_number: 10, body: 'you posted your first issue' }); ``` -------------------------------- ### Install @actions/cache Source: https://github.com/actions/toolkit/blob/main/README.md Installs the @actions/cache package for caching dependencies and build outputs to speed up workflow execution. ```bash npm install @actions/cache ``` -------------------------------- ### Install @actions/exec Source: https://github.com/actions/toolkit/blob/main/README.md Installs the @actions/exec package, used for executing CLI tools and processing their output within actions. ```bash npm install @actions/exec ``` -------------------------------- ### Referencing Actions with Versioning Source: https://github.com/actions/toolkit/blob/main/docs/action-versioning.md Examples of how to reference actions using different versioning strategies: major version tags, specific release versions, and commit SHAs. ```yaml steps: - uses: actions/javascript-action@v1 # recommended. starter workflows use this - uses: actions/javascript-action@v1.0.0 # if an action offers specific releases - uses: actions/javascript-action@41775a4da8ffae865553a738ab8ac1cd5a3c0044 # sha ``` -------------------------------- ### cacheDir Source: https://github.com/actions/toolkit/blob/main/docs/specs/package-specs.md Caches a directory and installs it into the tool cache. Requires source directory, tool name, version, and optionally architecture. ```APIDOC ## cacheDir ### Description Cache a directory and installs it into the tool cache directory. ### Parameters #### Path Parameters - **sourceDir** (string) - Required - The directory to cache. - **tool** (string) - Required - The name of the tool. - **version** (string) - Required - The version of the tool in semver format. - **arch** (string) - Optional - The architecture of the tool. Defaults to the machine architecture. ### Returns - **string** - The path to the cached tool directory. ``` -------------------------------- ### Platform Helper Source: https://github.com/actions/toolkit/blob/main/packages/core/README.md Offers utilities to get information about the operating system and architecture the Action is running on. Includes properties for platform name, architecture, and boolean flags for common OS types, as well as a method to get detailed platform information. ```APIDOC #### Platform helper Provides shorthands for getting information about platform action is running on. ```js import { platform } from '@actions/core' /* equals to a call of os.platform() */ platform.platform // 'win32' | 'darwin' | 'linux' | 'freebsd' | 'openbsd' | 'android' | 'cygwin' | 'sunos' /* equals to a call of os.arch() */ platform.arch // 'x64' | 'arm' | 'arm64' | 'ia32' | 'mips' | 'mipsel' | 'ppc' | 'ppc64' | 'riscv64' | 's390' | 's390x' /* common shorthands for platform-specific logic */ platform.isWindows // true platform.isMacOS // false platform.isLinux // false /* run platform-specific script to get more details about the exact platform, works on Windows, MacOS and Linux */ const { name, // Microsoft Windows 11 Enterprise version, // 10.0.22621 } = await platform.getDetails() ``` ``` -------------------------------- ### Test Results Summary Source: https://github.com/actions/toolkit/blob/main/README.md Example output showing test results, indicating passed tests and suites. ```text PASS ./index.test.js ✓ throws invalid number ✓ wait 500 ms ✓ test runs Test Suites: 1 passed, 1 total Tests: 3 passed, 3 total ``` -------------------------------- ### Wait and Log Message (JavaScript Action) Source: https://github.com/actions/toolkit/blob/main/README.md Demonstrates how to get an input for milliseconds, log a waiting message, and use asynchronous operations in a JavaScript Action. Ensure 'core' is imported. ```javascript async function run() { try { const ms = core.getInput('milliseconds'); console.log(`Waiting ${ms} milliseconds ...`) ... ``` -------------------------------- ### find Source: https://github.com/actions/toolkit/blob/main/docs/specs/package-specs.md Finds the path to a tool in the local installed tool cache based on name, version specification, and optional architecture. ```APIDOC ## find ### Description Find the path to a tool in the local installed tool cache. ### Parameters #### Path Parameters - **toolName** (string) - Required - The name of the tool to find. - **versionSpec** (string) - Required - The version specification of the tool. - **arch** (string) - Optional - The architecture of the tool. Defaults to the architecture of the computer. ### Returns - **string** - The path to the found tool. ``` -------------------------------- ### Dockerfile for Node.js Container Action Source: https://github.com/actions/toolkit/blob/main/README.md Dockerfile for a Node.js based action. It installs dependencies and sets the entrypoint to run the main JavaScript file. ```docker FROM node:slim COPY . . RUN npm install --production ENTRYPOINT ["node", "/lib/main.js"] ``` -------------------------------- ### Get platform and architecture information Source: https://github.com/actions/toolkit/blob/main/packages/core/README.md Import and use the `platform` object from `@actions/core` to access details about the runner environment. This includes the OS platform, architecture, and specific system details obtained via `getDetails()`. ```javascript import { platform } from '@actions/core' /* equals to a call of os.platform() */ platform.platform // 'win32' | 'darwin' | 'linux' | 'freebsd' | 'openbsd' | 'android' | 'cygwin' | 'sunos' /* equals to a call of os.arch() */ platform.arch // 'x64' | 'arm' | 'arm64' | 'ia32' | 'mips' | 'mipsel' | 'ppc' | 'ppc64' | 'riscv64' | 's390' | 's390x' /* common shorthands for platform-specific logic */ platform.isWindows // true platform.isMacOS // false platform.isLinux // false /* run platform-specific script to get more details about the exact platform, works on Windows, MacOS and Linux */ const { name, // Microsoft Windows 11 Enterprise version, // 10.0.22621 } = await platform.getDetails() ``` -------------------------------- ### Toolkit Usage: Glob Iterator Source: https://github.com/actions/toolkit/blob/main/docs/adrs/0381-glob-module.md Example demonstrating the use of `globGenerator` to iterate over matched files asynchronously. This is efficient for large numbers of files. ```javascript const patterns = core.getInput('path') const globber = glob.create(patterns) for await (const file of this.globGenerator()) { console.log(file) } ``` -------------------------------- ### Action Usage: Opt-out of Symbolic Links Source: https://github.com/actions/toolkit/blob/main/docs/adrs/0381-glob-module.md YAML example showing how to opt-out of following symbolic links in an action. By default, actions follow symbolic links. ```yaml jobs: build: steps: - uses: actions/upload-artifact@v1 with: path: | **/*.tar.gz **/*.pkg follow-symbolic-links: false # opt out, should default to true ``` -------------------------------- ### Run Jest Unit Tests for @actions/artifact Source: https://github.com/actions/toolkit/blob/main/packages/artifact/CONTRIBUTIONS.md To run unit tests for the @actions/artifact package, first clone the actions/toolkit repository, install dependencies, navigate to the packages/artifact directory, and then execute the jest tests. ```bash npm bootstrap cd packages/artifact npm run test ``` -------------------------------- ### constructor Source: https://github.com/actions/toolkit/blob/main/packages/artifact/docs/generated/classes/DefaultArtifactClient.md Initializes a new instance of the DefaultArtifactClient. ```APIDOC ## constructor ### Description Initializes a new instance of the DefaultArtifactClient. ### Returns - `DefaultArtifactClient`: A new instance of the DefaultArtifactClient. ### Defined in [src/internal/client.ts:248](https://github.com/actions/toolkit/blob/f522fdf/packages/artifact/src/internal/client.ts#L248) ``` -------------------------------- ### IO Make Directory Source: https://github.com/actions/toolkit/blob/main/docs/specs/package-specs.md Creates a directory, including any necessary parent directories. ```typescript /** * Make a directory. Creates the full path with folders in between * * @param p path to create * @returns Promise */ export function mkdirP(p: string): Promise ``` -------------------------------- ### Initialize Action Logic with Core and GitHub Packages Source: https://github.com/actions/toolkit/blob/main/docs/github-package.md Import and initialize the '@actions/core' and '@actions/github' packages for action functionality and GitHub API access. This forms the basic structure for your action's main logic. ```typescript import * as core from '@actions/core'; import * as github from '@actions/github'; export async function run() { try { const welcomeMessage: string = core.getInput('welcome-message'); // TODO - Get context data // TODO - make request to the GitHub API to comment on the issue } catch (error) { core.setFailed(error.message); throw error; } } run(); ``` -------------------------------- ### Define Action Inputs in action.yml Source: https://github.com/actions/toolkit/blob/main/docs/github-package.md Define 'welcome-message' and 'repo-token' as inputs in your action.yml metadata file. The 'repo-token' is required and can be passed using {{ secrets.GITHUB_TOKEN }}. ```yaml name: "Welcome" description: "A basic welcome action" author: "GitHub" inputs: welcome-message: description: "Message to display when a user opens an issue or PR" default: "Thanks for opening an issue! Make sure you've followed CONTRIBUTING.md" repo-token: description: "Token for the repo. Can be passed in using {{ secrets.GITHUB_TOKEN }}" required: true runs: using: "node12" main: "lib/main.js" ``` -------------------------------- ### Get Artifact Source: https://github.com/actions/toolkit/blob/main/packages/artifact/README.md Retrieves artifact information. Supports specifying `findBy` options to get artifacts from other repositories or workflow runs. ```APIDOC ## Get Artifact Retrieves artifact information. Supports specifying `findBy` options to get artifacts from other repositories or workflow runs. ### Method Signature ```typescript artifact.getArtifact(name: string, options?: { findBy: { token: string, workflowRunId?: number, repositoryOwner?: string, repositoryName?: string } }): Promise ``` ### Parameters - **name** (string) - Required - The name of the artifact to retrieve. - **options** (object) - Optional - Options for retrieving artifacts from other repositories or runs. - **findBy** (object) - Required if options are provided - Specifies the target repository and run. - **token** (string) - Required - A GitHub token with `actions:read` permission on the target repository. - **workflowRunId** (number) - Optional - The ID of the workflow run from which to get the artifact. - **repositoryOwner** (string) - Optional - The owner of the target repository. - **repositoryName** (string) - Optional - The name of the target repository. ### Request Example ```typescript const findBy = { token: process.env['GITHUB_TOKEN'], workflowRunId: 123, repositoryOwner: 'actions', repositoryName: 'toolkit' } await artifact.getArtifact('my-artifact', { findBy }) ``` ``` -------------------------------- ### Download a Tool Source: https://github.com/actions/toolkit/blob/main/packages/tool-cache/README.md Use this to download tools or other files from a given URL. Ensure the URL points to a downloadable resource. ```javascript const tc = require('@actions/tool-cache'); const node12Path = await tc.downloadTool('https://nodejs.org/dist/v12.7.0/node-v12.7.0-linux-x64.tar.gz'); ``` -------------------------------- ### Execute a Basic Command Source: https://github.com/actions/toolkit/blob/main/packages/exec/README.md Use this to run a simple command. Ensure the command is in the system's PATH. ```javascript const exec = require('@actions/exec'); await exec.exec('node index.js'); ``` -------------------------------- ### Get Job Summary as String Source: https://github.com/actions/toolkit/blob/main/packages/core/README.md Returns the current content of the summary buffer as a string. ```typescript // Returns the current summary buffer as a string core.summary.stringify() ``` -------------------------------- ### Complete Action Logic with Context and Inputs Source: https://github.com/actions/toolkit/blob/main/docs/github-package.md Integrate input retrieval and context data access into the action's main function. This version includes fetching the 'welcome-message' and 'repo-token' inputs and the issue context. ```typescript import * as core from '@actions/core'; import * as github from '@actions/github'; export async function run() { try { const welcomeMessage: string = core.getInput('welcome-message', {required: true}); const repoToken: string = core.getInput('repo-token', {required: true}); const issue: {owner: string; repo: string; number: number} = github.context.issue; if (github.context.payload.action !== 'opened') { console.log('No issue or pull request was opened, skipping'); return; } // TODO - make request to the GitHub API to comment on the issue } catch (error) { core.setFailed(error.message); throw error; } } run(); ``` -------------------------------- ### Get Action Inputs Source: https://github.com/actions/toolkit/blob/main/packages/core/README.md Retrieve string, boolean, or multiline inputs from action.yml. Ensure required inputs have a default value if not provided. ```javascript const myInput = core.getInput('inputName', { required: true }); const myBooleanInput = core.getBooleanInput('booleanInputName', { required: true }); const myMultilineInput = core.getMultilineInput('multilineInputName', { required: true }); core.setOutput('outputKey', 'outputVal'); ``` -------------------------------- ### Making GraphQL API Calls Source: https://github.com/actions/toolkit/blob/main/packages/github/README.md Illustrates how to execute GraphQL queries using the Octokit client. ```APIDOC ## Making GraphQL API Calls ### Description Execute GraphQL queries against the GitHub API. ### Method `octokit.graphql(query, variables?) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript const query = `{ repository(owner: "octokit", name: "rest.js") { description } }`; const variables = {}; const result = await octokit.graphql(query, variables); console.log(result); ``` ### Response #### Success Response (200) Data returned from the GraphQL query. #### Response Example ```json { "data": { "repository": { "description": "GitHub REST API client for JavaScript" } } } ``` ``` -------------------------------- ### Extending Octokit with Plugins Source: https://github.com/actions/toolkit/blob/main/packages/github/README.md Shows how to extend the Octokit instance with plugins, such as for accessing enterprise admin APIs. ```APIDOC ## Extending Octokit with Plugins ### Description Extend the GitHub Octokit instance using the plugin architecture from `@octokit/core`. ### Method `GitHub.plugin(...plugins)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript import { GitHub, getOctokitOptions } from '@actions/github/lib/utils' import { enterpriseServer220Admin } from '@octokit/plugin-enterprise-server' const octokit = GitHub.plugin(enterpriseServer220Admin) // Or override defaults: // const octokit = GitHub.plugin(enterpriseServer220Admin).defaults({ userAgent: 'MyNewUserAgent' }) const myToken = core.getInput('myToken'); const myOctokit = new octokit(getOctokitOptions(myToken)) // Example usage with the plugin: myOctokit.rest.enterpriseAdmin.createUser({ login: "testuser", email: "testuser@test.com", }); ``` ### Response #### Success Response (200) An extended Octokit client instance with the applied plugins. #### Response Example ```json { "data": "Extended Octokit Client Instance" } ``` ``` -------------------------------- ### Toolkit Usage: Disable Symbolic Links Source: https://github.com/actions/toolkit/blob/main/docs/adrs/0381-glob-module.md Example of creating a globber that does not follow symbolic links. This is useful for operations where symbolic links should not be traversed. ```javascript const patterns = core.getInput('path') const globber = glob.create(patterns, {followSymbolicLinks: false}) const files = globber.glob() ``` -------------------------------- ### Publishing a Docker Action Source: https://github.com/actions/toolkit/blob/main/docs/container-action.md Push your action's code to the repository to publish it. The runner builds the Docker container at runtime. ```bash $ git push ``` -------------------------------- ### Type-safe Webhook Payloads Source: https://github.com/actions/toolkit/blob/main/packages/github/README.md Utilize type definitions from '@octokit/webhooks-definitions' for webhook payloads. Install the package and assert the payload type based on the eventName for better type information. ```typescript import * as core from '@actions/core' import * as github from '@actions/github' import {PushEvent} from '@octokit/webhooks-definitions/schema' if (github.context.eventName === 'push') { const pushPayload = github.context.payload as PushEvent core.info(`The head commit is: ${pushPayload.head_commit}`) } ``` -------------------------------- ### Action input configuration for symbolic links Source: https://github.com/actions/toolkit/blob/main/packages/glob/README.md Define inputs in action.yml and consume them in the toolkit to allow users to toggle symbolic link following. ```yaml inputs: files: description: 'Files to print' required: true follow-symbolic-links: description: 'Indicates whether to follow symbolic links' default: true ``` ```js const core = require('@actions/core') const glob = require('@actions/glob') const globOptions = { followSymbolicLinks: core.getInput('follow-symbolic-links').toUpper() !== 'FALSE' } const globber = glob.create(core.getInput('files'), globOptions) for await (const file of globber.globGenerator()) { console.log(file) } ``` -------------------------------- ### Run All Tests Source: https://github.com/actions/toolkit/blob/main/packages/http-client/README.md Execute all tests for the project using npm. This command ensures the package is functioning as expected. ```bash npm test ``` -------------------------------- ### Globber Interface Source: https://github.com/actions/toolkit/blob/main/docs/adrs/0381-glob-module.md Defines the interface for a globber object, including methods to get search paths and match files. This interface outlines the capabilities for file and directory matching. ```typescript /** * Used to match files and directories */ export interface Globber { /** * Returns the search path preceding the first glob segment, from each pattern. * Duplicates and descendants of other paths are filtered out. * * Example 1: The patterns `/foo/*` and `/bar/*` returns `/foo` and `/bar`. * * Example 2: The patterns `/foo/*` and `/foo/bar/*` returns `/foo`. */ getSearchPaths(): string[] /** * Returns files and directories matching the glob patterns. * * Order of the results is not guaranteed. */ glob(): Promise /** * Returns files and directories matching the glob patterns. * * Order of the results is not guaranteed. */ globGenerator(): AsyncGenerator } ``` -------------------------------- ### Build Project Source: https://github.com/actions/toolkit/blob/main/packages/http-client/README.md Build the project using npm. This command compiles the TypeScript code and prepares the package for use. ```bash npm run build ``` -------------------------------- ### Set Multiline Environment Variable with Heredoc Source: https://github.com/actions/toolkit/blob/main/docs/commands.md For multiline environment variables, use a heredoc syntax. This example sets a JSON response from a curl command to the JSON_RESPONSE environment variable. ```shell echo 'JSON_RESPONSE<> $GITHUB_ENV curl https://httpbin.org/json >> $GITHUB_ENV echo 'EOF' >> $GITHUB_ENV ``` -------------------------------- ### Create Directory Recursively with mkdirP Source: https://github.com/actions/toolkit/blob/main/packages/io/README.md Use `mkdirP` to recursively create a directory. It follows the rules of `man mkdir -p`. ```javascript const io = require('@actions/io'); await io.mkdirP('path/to/make'); ``` -------------------------------- ### Webhook Payload Interfaces Source: https://github.com/actions/toolkit/blob/main/docs/specs/github-package.md Defines the structure for webhook payloads, including repository, issue, pull request, sender, and installation details. Useful for type-checking and accessing specific event data. ```typescript /* * Interfaces */ export interface PayloadRepository { [key: string]: any full_name?: string name: string owner: { [key: string]: any login: string name?: string } html_url?: string } export interface WebhookPayloadWithRepository { [key: string]: any repository?: PayloadRepository issue?: { [key: string]: any number: number html_url?: string body?: string } pull_request?: { [key: string]: any number: number html_url?: string body?: string } sender?: { [key: string]: any type: string } action?: string installation?: { id: number [key: string]: any } } ``` -------------------------------- ### Find Tool in Cache Source: https://github.com/actions/toolkit/blob/main/docs/specs/package-specs.md Locates the path to a tool within the local installed tool cache based on its name, version specification, and optional architecture. Defaults to the computer's architecture if not specified. ```typescript /** * finds the path to a tool in the local installed tool cache * * @param toolName name of the tool * @param versionSpec version of the tool * @param arch optional arch. defaults to arch of computer */ export function find(toolName: string, versionSpec: string, arch?: string): string ``` -------------------------------- ### Mock GitHub Action Inputs Source: https://github.com/actions/toolkit/blob/main/docs/github-package.md Demonstrates how to mock action inputs for testing by setting environment variables. Inputs are prefixed with 'INPUT_' and converted to uppercase. ```typescript const nock = require('nock'); const path = require('path'); describe('action test suite', () => { it('It posts a comment on an opened issue', async () => { const welcomeMessage = 'hello'; const repoToken = 'token'; process.env['INPUT_WELCOME-MESSAGE'] = welcomeMessage; process.env['INPUT_REPO-TOKEN'] = repoToken; // TODO }); }); ``` -------------------------------- ### Use ansi-styles module for complex styling Source: https://github.com/actions/toolkit/blob/main/packages/core/README.md Leverage third-party modules like `ansi-styles` for easier generation of complex ANSI escape codes. This example shows how to use the module to apply hex-colored text. ```javascript const style = require('ansi-styles'); core.info(style.color.ansi16m.hex('#abcdef') + 'Hello world!') ``` -------------------------------- ### Define Container Action Metadata Source: https://github.com/actions/toolkit/blob/main/docs/container-action.md Define the action's name, description, author, inputs, and how it runs using Docker. Inputs are mapped to arguments passed to the container. ```yaml name: 'My Container Action' description: 'Get started with Container actions' author: 'GitHub' inputs: myInput: description: 'Input to use' default: 'world' uns: using: 'docker' image: 'Dockerfile' args: - ${{ inputs.myInput }} ``` -------------------------------- ### Get GitHub OIDC ID Token Source: https://github.com/actions/toolkit/blob/main/packages/core/README.md Obtain a JSON Web Token (JWT) from the GitHub OIDC provider to authenticate with third-party cloud services. The `getIDToken` method can optionally accept an audience parameter. ```javascript const core = require('@actions/core'); async function getIDTokenAction(): Promise { const audience = core.getInput('audience', {required: false}) const id_token1 = await core.getIDToken() // ID Token with default audience const id_token2 = await core.getIDToken(audience) // ID token with custom audience // this id_token can be used to get access token from third party cloud providers } getIDTokenAction() ``` ```yaml name: 'GetIDToken' description: 'Get ID token from Github OIDC provider' inputs: audience: description: 'Audience for which the ID token is intended for' required: false outputs: id_token1: description: 'ID token obtained from OIDC provider' id_token2: description: 'ID token obtained from OIDC provider' uns: using: 'node12' main: 'dist/index.js' ``` -------------------------------- ### Dockerfile for Alpine-based Action Source: https://github.com/actions/toolkit/blob/main/README.md A Dockerfile to create an action using an Alpine base image. It copies necessary files and sets an entrypoint script. ```docker FROM alpine:3.10 COPY LICENSE README.md / COPY entrypoint.sh /entrypoint.sh ENTRYPOINT ["/entrypoint.sh"] ``` -------------------------------- ### Log colored output with ANSI escape codes Source: https://github.com/actions/toolkit/blob/main/packages/core/README.md Use ANSI escape codes to style text in Action logs. Supports 3/4 bit, 8 bit, and 24 bit colors for foreground and background, as well as special styles like bold, italic, and underline. Codes reset at the start of each line. ```javascript core.info('\u001b[35mThis foreground will be magenta') ``` ```javascript core.info('\u001b[38;5;6mThis foreground will be cyan') ``` ```javascript core.info('\u001b[38;2;255;0;0mThis foreground will be bright red') ``` ```javascript core.info('\u001b[43mThis background will be yellow'); ``` ```javascript core.info('\u001b[48;5;6mThis background will be cyan') ``` ```javascript core.info('\u001b[48;2;255;0;0mThis background will be bright red') ``` ```javascript core.info('\u001b[1mBold text') ``` ```javascript core.info('\u001b[3mItalic text') ``` ```javascript core.info('\u001b[4mUnderlined text') ``` ```javascript core.info('\u001b[31;46mRed foreground with a cyan background and \u001b[1mbold text at the end'); ``` ```javascript core.info('\u001b[35mThis foreground will be magenta') core.info('This foreground will reset to the default') ``` -------------------------------- ### Capture Command Output and Options Source: https://github.com/actions/toolkit/blob/main/packages/exec/README.md Capture stdout and stderr, or specify other execution options like the current working directory. Refer to the toolkit interfaces for all available options. ```javascript const exec = require('@actions/exec'); let myOutput = ''; let myError = ''; const options = {}; options.listeners = { stdout: (data: Buffer) => { myOutput += data.toString(); }, stderr: (data: Buffer) => { myError += data.toString(); } }; options.cwd = './lib'; await exec.exec('node', ['index.js', 'foo=bar'], options); ``` -------------------------------- ### Basic file search with glob patterns Source: https://github.com/actions/toolkit/blob/main/packages/glob/README.md Use glob.create to search for files using relative or absolute paths. ```js const glob = require('@actions/glob'); const patterns = ['**/tar.gz', '**/tar.bz'] const globber = await glob.create(patterns.join('\n')) const files = await globber.glob() ``` -------------------------------- ### Download Tool from URL Source: https://github.com/actions/toolkit/blob/main/docs/specs/package-specs.md Use this function to download a tool from a given URL. It streams the content directly into a file. ```typescript /** * Download a tool from an url and stream it into a file * * @param url url of tool to download * @returns path to downloaded tool */ export async function downloadTool(url: string): Promise ``` -------------------------------- ### Execute Command with Arguments Source: https://github.com/actions/toolkit/blob/main/packages/exec/README.md Pass arguments to a command as an array. This is useful for commands that accept multiple parameters. ```javascript const exec = require('@actions/exec'); await exec.exec('node', ['index.js', 'foo=bar']); ``` -------------------------------- ### Download Tool Source: https://github.com/actions/toolkit/blob/main/packages/tool-cache/README.md Downloads a tool or file from a given URL. This is the first step before extracting or caching. ```APIDOC ## downloadTool ### Description Downloads a tool or file from a specified URL. ### Parameters #### Path Parameters - **url** (string) - Required - The URL of the tool or file to download. ### Returns - **Promise** - A promise that resolves to the local path of the downloaded file. ``` -------------------------------- ### Convert file paths between OS formats Source: https://github.com/actions/toolkit/blob/main/packages/core/README.md Utilize `toPosixPath`, `toWin32Path`, and `toPlatformPath` to ensure file path compatibility across different operating systems. These functions normalize paths to Posix, Windows, or the runner's native format. ```javascript toPosixPath('\\foo\\bar') // => /foo/bar toWin32Path('/foo/bar') // => \\foo\\bar ``` ```javascript // On a Windows runner. toPlatformPath('/foo/bar') // => \\foo\\bar // On a Linux runner. toPlatformPath('\\foo\\bar') // => /foo/bar ``` -------------------------------- ### Creating a Globber Source: https://github.com/actions/toolkit/blob/main/docs/adrs/0381-glob-module.md Use the `create` function to construct a Globber instance from one or more glob patterns and optional configuration. ```APIDOC ## create ### Description Constructs a globber from patterns. ### Signature ```js export function create(patterns: string, options?: GlobOptions): Promise ``` ### Parameters #### Path Parameters - **patterns** (string) - Required - Patterns separated by newlines. - **options** (GlobOptions) - Optional - Glob options. ### Returns - **Promise** - A promise that resolves to a Globber instance. ``` -------------------------------- ### Basic Action Unit Test Structure Source: https://github.com/actions/toolkit/blob/main/docs/github-package.md Sets up a basic Jest test suite for an action. This includes importing necessary mocking libraries and defining a test case for posting a comment on an opened issue. ```typescript const nock = require('nock'); const path = require('path'); describe('action test suite', () => { it('It posts a comment on an opened issue', async () => { // TODO }); }); ``` -------------------------------- ### Upload and Download Artifact Source: https://github.com/actions/toolkit/blob/main/packages/artifact/README.md Uploads files to an artifact and then downloads it using the artifact ID. The upload returns the artifact ID and size, while the download specifies a destination path. ```javascript const {id, size} = await artifact.uploadArtifact( // name of the artifact 'my-artifact', // files to include (supports absolute and relative paths) ['/absolute/path/file1.txt', './relative/file2.txt'], { // optional: how long to retain the artifact // if unspecified, defaults to repository/org retention settings (the limit of this value) retentionDays: 10 } ) console.log(`Created artifact with id: ${id} (bytes: ${size}`) const {downloadPath} = await artifact.downloadArtifact(id, { // optional: download destination path. otherwise defaults to $GITHUB_WORKSPACE path: '/tmp/dst/path', }) console.log(`Downloaded artifact ${id} to: ${downloadPath}`) ``` -------------------------------- ### Compile and Link Local @actions/artifact Changes Source: https://github.com/actions/toolkit/blob/main/packages/artifact/CONTRIBUTIONS.md Compile your local changes to the @actions/artifact package using 'npm run tsc' and then create a symbolic link to your package using 'npm link'. This prepares your changes for testing within other actions. ```bash cd packages/artifact npm run tsc npm link ``` -------------------------------- ### Mock GitHub Context Environment Variables Source: https://github.com/actions/toolkit/blob/main/docs/github-package.md Configures the test environment by mocking GitHub context-related environment variables. This includes setting GITHUB_REPOSITORY and GITHUB_EVENT_PATH to simulate a GitHub event. ```typescript const nock = require('nock'); const path = require('path'); describe('action test suite', () => { it('It posts a comment on an opened issue', async () => { const welcomeMessage = 'hello'; const repoToken = 'token'; process.env['INPUT_WELCOME-MESSAGE'] = welcomeMessage; process.env['INPUT_REPO-TOKEN'] = repoToken; process.env['GITHUB_REPOSITORY'] = 'foo/bar'; process.env['GITHUB_EVENT_PATH'] = path.join(__dirname, 'payload.json'); // TODO }); }); ``` -------------------------------- ### glob.create(patterns, options) Source: https://github.com/actions/toolkit/blob/main/packages/glob/README.md Creates a globber instance to search for files matching the provided patterns. ```APIDOC ## glob.create(patterns, options) ### Description Creates a globber instance that can be used to search for files matching the specified glob patterns. Relative paths are rooted against the current working directory. ### Parameters - **patterns** (string) - Required - A newline-separated string of glob patterns. - **options** (object) - Optional - Configuration options. - **followSymbolicLinks** (boolean) - Optional - Whether to follow symbolic links. Defaults to true. ### Returns - **Globber** - An instance with methods `glob()` (returns all files) and `globGenerator()` (returns an async iterator). ``` -------------------------------- ### Container Action Entrypoint Script Source: https://github.com/actions/toolkit/blob/main/docs/container-action.md The `entrypoint.sh` script is the main executable for the Docker action. It receives arguments passed from the workflow. ```bash #!/bin/sh -l echo "hello $1" ``` -------------------------------- ### downloadTool Source: https://github.com/actions/toolkit/blob/main/docs/specs/package-specs.md Downloads a tool from a given URL and streams it into a file. Returns the path to the downloaded tool. ```APIDOC ## downloadTool ### Description Download a tool from an url and stream it into a file. ### Parameters #### Path Parameters - **url** (string) - Required - The URL of the tool to download. ### Returns - **string** - The path to the downloaded tool. ``` -------------------------------- ### glob.hashFiles(patterns, workspacePath, options) Source: https://github.com/actions/toolkit/blob/main/packages/glob/README.md Computes a hash of files matched by glob patterns, with security checks for file paths. ```APIDOC ## glob.hashFiles(patterns, workspacePath, options) ### Description Computes a hash of files matched by glob patterns. By default, only files under the workspace are eligible to be hashed to prevent symbolic link traversal outside the allowed root paths. ### Parameters - **patterns** (string) - Required - Glob patterns to match files. - **workspacePath** (string) - Required - The base workspace path. - **options** (object) - Optional - Configuration options. - **roots** (string[]) - Optional - Allowlist of root paths. Defaults to [GITHUB_WORKSPACE]. - **allowFilesOutsideWorkspace** (boolean) - Optional - Explicit opt-in to include files outside the specified root path(s). Defaults to false. - **exclude** (string[]) - Optional - Glob patterns to exclude from hashing. Defaults to []. ### Returns - **Promise** - A promise that resolves to the computed hash string, or an empty string if no eligible files are found. ``` -------------------------------- ### Making REST API Calls Source: https://github.com/actions/toolkit/blob/main/packages/github/README.md Shows how to make a REST API call to retrieve pull request data using the Octokit client. ```APIDOC ## Making REST API Calls ### Description Use the `octokit.rest` object to make calls to the GitHub REST API. ### Method `octokit.rest..({ ...options }) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript const { data: pullRequest } = await octokit.rest.pulls.get({ owner: 'octokit', repo: 'rest.js', pull_number: 123, mediaType: { format: 'diff' } }); console.log(pullRequest); ``` ### Response #### Success Response (200) Data returned from the specific REST API endpoint. #### Response Example ```json { "data": "Pull Request Data" } ``` ``` -------------------------------- ### Upload and Download Artifact Source: https://github.com/actions/toolkit/blob/main/packages/artifact/README.md Demonstrates the basic usage of uploading one or more files to an artifact and then downloading it using its ID. The uploadArtifact method returns the artifact ID and size, while downloadArtifact allows specifying a destination path. ```APIDOC ## Upload and Download Artifact ### Description This example shows how to upload files to an artifact and then download it using the artifact's ID. The `uploadArtifact` method returns the ID and size of the created artifact. The `downloadArtifact` method allows downloading the artifact to a specified path. ### Method ```javascript artifact.uploadArtifact(name: string, files: string[], options?: UploadArtifactOptions) artifact.downloadArtifact(artifactId: string, options?: DownloadArtifactOptions) ``` ### Parameters #### `uploadArtifact` Parameters - **name** (string) - Required - The name of the artifact. - **files** (string[]) - Required - An array of file paths (absolute or relative) to include in the artifact. - **options** (object) - Optional - Configuration options for the upload. - **retentionDays** (number) - Optional - How long to retain the artifact. Defaults to repository/org retention settings. #### `downloadArtifact` Parameters - **artifactId** (string) - Required - The ID of the artifact to download. - **options** (object) - Optional - Configuration options for the download. - **path** (string) - Optional - The destination path for the download. Defaults to `$GITHUB_WORKSPACE`. ### Request Example (Upload) ```javascript const {id, size} = await artifact.uploadArtifact( 'my-artifact', ['/absolute/path/file1.txt', './relative/file2.txt'], { retentionDays: 10 } ) console.log(`Created artifact with id: ${id} (bytes: ${size}`) ``` ### Response Example (Upload) ```json { "id": "artifact-id-string", "size": 12345 } ``` ### Request Example (Download) ```javascript const {downloadPath} = await artifact.downloadArtifact(id, { path: '/tmp/dst/path' }) console.log(`Downloaded artifact ${id} to: ${downloadPath}`) ``` ### Response Example (Download) ```json { "downloadPath": "/tmp/dst/path" } ``` ```