### Example Source: https://github.com/changesets/action/blob/main/_autodocs/api-reference/octokit.md Example usage of the setupOctokit function to interact with GitHub API. ```typescript import { setupOctokit } from "@changesets/action"; const token = process.env.GITHUB_TOKEN; const octokit = setupOctokit(token); // REST API: Create a pull request const pr = await octokit.rest.pulls.create({ owner: "changesets", repo: "action", title: "Version Packages", body: "Release changelog here", head: "changeset-release/main", base: "main", }); console.log(`Created PR #${pr.data.number}`); // REST API: Create a GitHub release await octokit.rest.repos.createRelease({ owner: "changesets", repo: "action", tag_name: "v1.0.0", name: "v1.0.0", body: "Release notes from CHANGELOG", }); // GraphQL: Update pull request with mutation const result = await octokit.graphql( `mutation UpdatePullRequest($id: ID!, $title: String!) { updatePullRequest(input: { pullRequestId: $id, title: $title }) { pullRequest { id } } }`, { id: pr.data.node_id, title: "Updated: Version Packages", } ); ``` -------------------------------- ### Octokit Error Handling Example Source: https://github.com/changesets/action/blob/main/_autodocs/api-reference/octokit.md Example demonstrating how to handle errors when using Octokit, including specific status codes. ```typescript const octokit = setupOctokit(token); try { const pr = await octokit.rest.pulls.create({ owner: "myorg", repo: "myrepo", title: "Test PR", head: "test-branch", base: "main", }); } catch (err) { if (err.status === 401) { console.error("Invalid token"); } else if (err.status === 404) { console.error("Repository not found"); } else if (err.status === 422) { console.error("Validation error (e.g., branch doesn't exist)"); } else { console.error("Unexpected error:", err.message); } } ``` -------------------------------- ### GitHub Actions Setup - Required Steps Source: https://github.com/changesets/action/blob/main/_autodocs/api-reference/index.md Essential steps for setting up a GitHub Actions workflow to use the Changesets Action, including checking out code, setting up Node.js, installing dependencies, and using the Changesets Action itself. ```yaml - uses: actions/checkout@v6 with: fetch-depth: 0 # Full history for changesets - uses: pnpm/action-setup@v6 # Or actions/setup-node@v4 - uses: actions/setup-node@v6 with: node-version: 24 cache: "pnpm" - run: pnpm install --frozen-lockfile - uses: changesets/action@v1 with: publish: pnpm publish # Optional version: pnpm changeset version # Optional, defaults to `changeset version` ``` -------------------------------- ### GitHub Actions (Recommended) Source: https://github.com/changesets/action/blob/main/_autodocs/api-reference/octokit.md Example of authenticating using the default GITHUB_TOKEN in GitHub Actions. ```typescript // Uses the default GITHUB_TOKEN provided by GitHub Actions const token = process.env.GITHUB_TOKEN; const octokit = setupOctokit(token); ``` -------------------------------- ### Basic REST API Usage Source: https://github.com/changesets/action/blob/main/_autodocs/api-reference/octokit.md Example of basic REST API usage with the configured Octokit client. ```typescript const octokit = setupOctokit(token); // Get repository information const repo = await octokit.rest.repos.get({ owner: "changesets", repo: "action", }); console.log(repo.data.description); // List open pull requests const prs = await octokit.rest.pulls.list({ owner: "changesets", repo: "action", state: "open", }); prs.data.forEach((pr) => { console.log(`#${pr.number}: ${pr.title}`); }); ``` -------------------------------- ### GraphQL Mutations Source: https://github.com/changesets/action/blob/main/_autodocs/api-reference/octokit.md Example of using GraphQL mutations with the configured Octokit client. ```typescript const octokit = setupOctokit(token); const mutation = ` mutation ConvertToDraft($id: ID!) { convertPullRequestToDraft(input: { pullRequestId: $id }) { pullRequest { id } } } `; await octokit.graphql(mutation, { id: pullRequest.node_id, }); ``` -------------------------------- ### Personal Access Token Source: https://github.com/changesets/action/blob/main/_autodocs/api-reference/octokit.md Example of authenticating using a personal access token. ```typescript // Create at https://github.com/settings/tokens const token = "ghp_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"; const octokit = setupOctokit(token); ``` -------------------------------- ### setupUser Method Example Source: https://github.com/changesets/action/blob/main/_autodocs/api-reference/git.md Example of configuring the git user for commits using the setupUser method. ```typescript const git = new Git({ cwd: process.cwd() }); await git.setupUser(); // git config user.name "github-actions[bot]" // git config user.email "41898282+github-actions[bot]@users.noreply.github.com" ``` -------------------------------- ### Changesets Action Usage in GitHub Actions Workflow Source: https://github.com/changesets/action/blob/main/_autodocs/api-reference/octokit.md Example of how to use the changesets/action in a GitHub Actions workflow. ```yaml - uses: changesets/action@v1 env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} ``` -------------------------------- ### prepareBranch Method Example Source: https://github.com/changesets/action/blob/main/_autodocs/api-reference/git.md Example of preparing a branch for work using the prepareBranch method. ```typescript const git = new Git({ cwd: process.cwd() }); await git.prepareBranch("changeset-release/main"); // Switches to changeset-release/main or creates it if it doesn't exist // Resets to the current commit ``` -------------------------------- ### Troubleshooting Git Installation Source: https://github.com/changesets/action/blob/main/_autodocs/errors.md Command to verify if Git is installed and accessible in the system's PATH. ```bash git --version ``` -------------------------------- ### setupOctokit() Source: https://github.com/changesets/action/blob/main/_autodocs/api-reference/octokit.md Create and configure an authenticated GitHub API client with automatic rate-limit handling. ```typescript export const setupOctokit = ( githubToken: string ): Octokit ``` -------------------------------- ### getVersionsByDirectory Example Source: https://github.com/changesets/action/blob/main/_autodocs/api-reference/utils.md Example usage of getVersionsByDirectory to retrieve package versions. ```typescript import { getVersionsByDirectory } from "@changesets/action"; const versions = await getVersionsByDirectory(process.cwd()); // Result: // Map { // '/path/to/packages/core' => '1.0.0', // '/path/to/packages/utils' => '2.1.3', // '/path/to/packages/cli' => '1.5.0' // } console.log(versions.get("/path/to/packages/core")); // "1.0.0" ``` -------------------------------- ### Example Usage of readChangesetState Source: https://github.com/changesets/action/blob/main/_autodocs/api-reference/readChangesetState.md An example demonstrating how to import and use the readChangesetState function to get the current changeset state and log relevant information. ```typescript import readChangesetState from "@changesets/action"; // Read current changeset state const state = await readChangesetState(process.cwd()); console.log("Number of changesets:", state.changesets.length); console.log("In pre-release mode:", state.preState !== undefined); if (state.preState) { console.log("Pre-release tag:", state.preState.tag); console.log("Pre-release mode:", state.preState.mode); } state.changesets.forEach((cs) => { console.log(`Changeset ${cs.id}:`, cs.releases); }); ``` -------------------------------- ### Output Setting Example Source: https://github.com/changesets/action/blob/main/_autodocs/api-reference/index.md Illustrates how the action sets its outputs using `core.setOutput()` for initial states, publishing events, and version PR creation. ```typescript // Initial (Lines 63-65) core.setOutput("published", "false"); core.setOutput("publishedPackages", "[]"); core.setOutput("hasChangesets", String(hasChangesets)); // When publishing (Lines 133-137) core.setOutput("published", "true"); core.setOutput("publishedPackages", JSON.stringify(result.publishedPackages)); // When creating version PR (Line 159) core.setOutput("pullRequestNumber", String(pullRequestNumber)); ``` -------------------------------- ### Example Usage of runVersion Source: https://github.com/changesets/action/blob/main/_autodocs/api-reference/run.md This example demonstrates how to use the `runVersion` function from `@changesets/action` to create a version pull request. It sets up the necessary parameters like GitHub token, Git client, Octokit client, working directory, PR title, commit message, publish script status, and the target branch. ```typescript import { runVersion } from "@changesets/action"; import { Git } from "@changesets/action"; import { setupOctokit } from "@changesets/action"; const token = process.env.GITHUB_TOKEN; const result = await runVersion({ githubToken: token, git: new Git({ cwd: process.cwd() }), octokit: setupOctokit(token), cwd: process.cwd(), prTitle: "Bump Versions", commitMessage: "Bump Versions", hasPublishScript: true, branch: "main", }); console.log(`Version PR created: #${result.pullRequestNumber}`); ``` -------------------------------- ### Install @changesets/cli Source: https://github.com/changesets/action/blob/main/_autodocs/errors.md Commands to install the @changesets/cli package. ```bash # Install in your project npm install --save-dev @changesets/cli # or pnpm add -D @changesets/cli ``` -------------------------------- ### runPublish() Example Source: https://github.com/changesets/action/blob/main/_autodocs/api-reference/run.md Example usage of the runPublish function. ```typescript import { runPublish } from "@changesets/action"; import { Git } from "@changesets/action"; import { setupOctokit } from "@changesets/action"; const result = await runPublish({ script: "pnpm publish", githubToken: process.env.GITHUB_TOKEN, octokit: setupOctokit(process.env.GITHUB_TOKEN), createGithubReleases: true, git: new Git({ cwd: process.cwd() }), cwd: process.cwd(), }); if (result.published) { console.log("Published:", result.publishedPackages); // Output: [{ name: "@scope/pkg", version: "1.0.0" }] } else { console.log("Nothing was published"); } ``` -------------------------------- ### Git Constructor Example Source: https://github.com/changesets/action/blob/main/_autodocs/api-reference/git.md Demonstrates how to instantiate the Git class using either the git CLI (default) or the GitHub API. ```typescript import { Git } from "@changesets/action"; import { setupOctokit } from "@changesets/action"; // Using git CLI (default) const git = new Git({ cwd: process.cwd() }); // Using GitHub API const token = process.env.GITHUB_TOKEN; const git = new Git({ octokit: setupOctokit(token), cwd: process.cwd(), }); ``` -------------------------------- ### fileExists Example Source: https://github.com/changesets/action/blob/main/_autodocs/api-reference/utils.md Demonstrates how to use the fileExists function to check for the existence of a file and conditionally create it. ```typescript import { fileExists } from "@changesets/action"; if (await fileExists("/home/.npmrc")) { console.log("NPM config exists"); } else { console.log("Creating new NPM config"); await fs.writeFile("/home/.npmrc", "//registry.npmjs.org/:_authToken=..."); } // Common usage in action const userNpmrcPath = `${process.env.HOME}/.npmrc`; if (await fileExists(userNpmrcPath)) { console.log("Found existing .npmrc"); const content = await fs.readFile(userNpmrcPath, "utf8"); // ... check and update content ... } else { // ... create new .npmrc with token ... } ``` -------------------------------- ### Octokit Type Source: https://github.com/changesets/action/blob/main/_autodocs/api-reference/octokit.md Type representing the configured Octokit client instance. ```typescript export type Octokit = ReturnType ``` -------------------------------- ### pushChanges Method Example Source: https://github.com/changesets/action/blob/main/_autodocs/api-reference/git.md Example of committing and pushing all changes in the working directory using the pushChanges method. ```typescript const git = new Git({ cwd: process.cwd() }); await git.pushChanges({ branch: "changeset-release/main", message: "Version Packages", }); // Commits and pushes all changes in cwd to changeset-release/main ``` -------------------------------- ### Conditional Next Step Example Source: https://github.com/changesets/action/blob/main/_autodocs/errors.md Example of how to conditionally run subsequent steps based on Changesets action outputs. ```yaml - uses: changesets/action@v1 id: changesets - name: Conditional publishing if: steps.changesets.outputs.published == 'true' run: echo "Published packages" - name: Conditional version PR if: steps.changesets.outputs.pullRequestNumber != '' run: echo "Created PR #${{ steps.changesets.outputs.pullRequestNumber }}" ``` -------------------------------- ### Automatic Retry on Rate Limit Source: https://github.com/changesets/action/blob/main/_autodocs/api-reference/octokit.md Demonstrates automatic retry behavior when rate-limited. ```typescript const octokit = setupOctokit(token); // This call will automatically retry if rate-limited try { const releases = await octokit.rest.repos.listReleases({ owner: "changesets", repo: "action", }); } catch (err) { // After 3 retry attempts with delays, still fails console.error("Failed to fetch releases:", err); } ``` -------------------------------- ### Custom .npmrc Creation Example Source: https://github.com/changesets/action/blob/main/README.md An example of how to create a custom .npmrc file before running the Changesets GitHub Action, allowing for custom configurations. ```yaml - name: Creating .npmrc run: | cat << EOF > "$HOME/.npmrc" //registry.npmjs.org/:_authToken=$NPM_TOKEN EOF env: NPM_TOKEN: ${{ secrets.NPM_TOKEN }} ``` -------------------------------- ### pushTag Example Source: https://github.com/changesets/action/blob/main/_autodocs/api-reference/git.md Demonstrates how to push a tag using both Git CLI mode and GitHub API mode. ```typescript const git = new Git({ cwd: process.cwd() }); // Using CLI await git.pushTag("v1.0.0"); // Using API const octokit = setupOctokit(token); const git = new Git({ octokit, cwd: process.cwd() }); await git.pushTag("@scope/pkg@1.0.0"); ``` -------------------------------- ### sortTheThings Example Source: https://github.com/changesets/action/blob/main/_autodocs/api-reference/utils.md Illustrates how to use the sortTheThings function to sort an array of packages based on their public/private status and semantic version bump level. ```typescript import { sortTheThings } from "@changesets/action"; const packages = [ { private: true, highestLevel: 3 }, { private: false, highestLevel: 1 }, { private: false, highestLevel: 3 }, { private: true, highestLevel: 1 }, ]; packages.sort(sortTheThings); // Result order: // { private: false, highestLevel: 3 }, // Public, Major // { private: false, highestLevel: 1 }, // Public, Patch // { private: true, highestLevel: 3 }, // Private, Major // { private: true, highestLevel: 1 }, // Private, Patch ``` -------------------------------- ### getChangedPackages Example Source: https://github.com/changesets/action/blob/main/_autodocs/api-reference/utils.md Example usage of getChangedPackages to find modified packages. ```typescript import { getVersionsByDirectory, getChangedPackages } from "@changesets/action"; // Get versions before running changeset version const versionsBefore = await getVersionsByDirectory(process.cwd()); // ... run changeset version which updates package.json files ... // Get changed packages const changed = await getChangedPackages(process.cwd(), versionsBefore); changed.forEach((pkg) => { console.log(`${pkg.packageJson.name}: changed`); }); // Output: // @myorg/core: changed // @myorg/utils: changed ``` -------------------------------- ### Example Usage of getVersionPrBody Source: https://github.com/changesets/action/blob/main/_autodocs/api-reference/run.md This example shows how to use the `getVersionPrBody` function to generate the markdown content for a version pull request. It includes sample data for `changedPackagesInfo` and other options like `hasPublishScript`, `branch`, and `prBodyMaxCharacters`. ```typescript import { getVersionPrBody } from "@changesets/action"; const prBody = await getVersionPrBody({ hasPublishScript: true, branch: "main", changedPackagesInfo: [ { highestLevel: 3, private: false, header: "## @myorg/sdk@2.0.0", content: "### Major Changes\n\n- Breaking API change", }, ], prBodyMaxCharacters: 60000, }); console.log(prBody); // Output: // This PR was opened by the Changesets release GitHub action... // # Releases // ## @myorg/sdk@2.0.0 // ### Major Changes // - Breaking API change ``` -------------------------------- ### Accessing Outputs in Next Step Source: https://github.com/changesets/action/blob/main/_autodocs/api-reference/index.md Example of how to access outputs from the Changesets Action in subsequent steps of a GitHub Actions workflow. ```yaml - uses: changesets/action@v1 id: changesets - name: Use outputs run: | echo "Published: ${{ steps.changesets.outputs.published }}" echo "PR Number: ${{ steps.changesets.outputs.pullRequestNumber }}" echo "Packages: ${{ steps.changesets.outputs.publishedPackages }}" ``` -------------------------------- ### Example: Pre-Release Filtering Source: https://github.com/changesets/action/blob/main/_autodocs/api-reference/readChangesetState.md An example illustrating how the readChangesetState function filters changesets when the repository is in pre-release mode. ```typescript // Scenario: Repository has 5 changeset files // - changeset-1.md, changeset-2.md, changeset-3.md (already in pre-release) // - changeset-4.md, changeset-5.md (new changesets) const state = await readChangesetState(cwd); if (state.preState) { console.log("Pre-release tag:", state.preState.tag); // e.g., "rc" console.log("Queued changesets:", state.preState.changesets); // Output: ["changeset-1", "changeset-2", "changeset-3"] } console.log("New changesets:", state.changesets.length); // Output: 2 (only changeset-4 and changeset-5) ``` -------------------------------- ### Example workflow - Without Publishing Source: https://github.com/changesets/action/blob/main/README.md This example demonstrates how to set up a GitHub Actions workflow to create a release pull request without publishing. ```yaml name: Release on: push: branches: - main concurrency: ${{ github.workflow }}-${{ github.ref }} jobs: release: name: Release runs-on: ubuntu-latest steps: - name: Checkout Repo uses: actions/checkout@v6 - name: Setup pnpm uses: pnpm/action-setup@v6 - name: Setup Node.js 26 uses: actions/setup-node@v6 with: node-version: 26 - name: Install Dependencies run: pnpm install --frozen-lockfile - name: Create Release Pull Request uses: changesets/action@v1 ``` -------------------------------- ### Use Custom Version Script Source: https://github.com/changesets/action/blob/main/_autodocs/errors.md Example of using a custom version script with the action. ```yaml - uses: changesets/action@v1 with: version: pnpm custom-version-script ``` -------------------------------- ### getChangelogEntry Example Source: https://github.com/changesets/action/blob/main/_autodocs/api-reference/utils.md Demonstrates how to use the getChangelogEntry function to parse changelog content and extract the highest bump level and content for a specific version. ```typescript import { getChangelogEntry } from "@changesets/action"; import fs from "fs/promises"; const changelogContent = await fs.readFile("CHANGELOG.md", "utf8"); const entry = getChangelogEntry(changelogContent, "2.0.0"); console.log("Highest bump level:", entry.highestLevel); // Output: 3 (major) console.log("Changelog content:"); console.log(entry.content); // Output: // ### Major Changes // // - Breaking: Removed deprecated API // - Added new streaming interface ``` -------------------------------- ### Provide GitHub Token Input Source: https://github.com/changesets/action/blob/main/_autodocs/errors.md Example of how to explicitly pass the github-token input in a workflow. ```yaml - uses: changesets/action@v1 with: github-token: ${{ secrets.GITHUB_TOKEN }} ``` -------------------------------- ### Valid Commit Modes Source: https://github.com/changesets/action/blob/main/_autodocs/errors.md Example of setting the commitMode input. ```yaml - uses: changesets/action@v1 with: commitMode: "git-cli" # or "github-api" ``` -------------------------------- ### Valid PR Draft Modes Source: https://github.com/changesets/action/blob/main/_autodocs/errors.md Example of setting the prDraft input. ```yaml - uses: changesets/action@v1 with: prDraft: "create" # or "always" or omit for no draft ``` -------------------------------- ### isErrorWithCode Example Source: https://github.com/changesets/action/blob/main/_autodocs/api-reference/utils.md Shows how to use the isErrorWithCode type guard to check for specific error codes, such as file not found (ENOENT) or module not found (MODULE_NOT_FOUND). ```typescript import { isErrorWithCode } from "@changesets/action"; import fs from "fs/promises"; try { await fs.readFile("CHANGELOG.md", "utf8"); } catch (err) { if (isErrorWithCode(err, "ENOENT")) { console.log("File not found, skipping changelog"); } else { throw err; } } // Or with require try { require.resolve("@changesets/cli", { paths: [cwd] }); } catch (err) { if (isErrorWithCode(err, "MODULE_NOT_FOUND")) { throw new Error(`@changesets/cli not found in ${cwd}`); } throw err; } ``` -------------------------------- ### Accessing Detailed Error Info Source: https://github.com/changesets/action/blob/main/_autodocs/errors.md TypeScript example demonstrating how to catch and log detailed error information within action code. ```typescript try { // action code } catch (err) { console.error("Full error:", err); console.error("Stack:", err.stack); console.error("Code:", err.code); } ``` -------------------------------- ### Pre-Release Workflow Source: https://github.com/changesets/action/blob/main/_autodocs/api-reference/readChangesetState.md Example of how to use readChangesetState to detect if the current workflow is in a pre-release mode and log relevant information. ```typescript const state = await readChangesetState(cwd); if (state.preState) { const prTitle = `Version Packages (${state.preState.tag})`; console.log("In pre-release mode with tag:", state.preState.tag); console.log("This PR will create pre-release versions"); // Example: "Version Packages (rc)" or "Version Packages (alpha)" } ``` -------------------------------- ### Integration with Workflow Source: https://github.com/changesets/action/blob/main/_autodocs/api-reference/readChangesetState.md A comprehensive example demonstrating how to integrate readChangesetState into a release workflow, including checking the state, creating/updating a version PR, and handling publish scripts. ```typescript import readChangesetState from "@changesets/action"; import { runVersion } from "@changesets/action"; import { Git } from "@changesets/action"; import { setupOctokit } from "@changesets/action"; async function releaseWorkflow() { const cwd = process.cwd(); const token = process.env.GITHUB_TOKEN; // Step 1: Check current state const { changesets, preState } = await readChangesetState(cwd); if (changesets.length === 0) { console.log("No changesets found"); return; } // Step 2: Create/update version PR const git = new Git({ cwd, octokit: setupOctokit(token) }); const octokit = setupOctokit(token); const result = await runVersion({ githubToken: token, git, octokit, cwd, prTitle: `Version Packages${preState ? ` (${preState.tag})` : ""}`, hasPublishScript: true, }); console.log(`Created/updated PR #${result.pullRequestNumber}`); } ``` -------------------------------- ### Determining Release Scope Source: https://github.com/changesets/action/blob/main/_autodocs/api-reference/readChangesetState.md Example of how to use readChangesetState to check if any changesets contain actual package releases and log the packages to be released. ```typescript const state = await readChangesetState(cwd); // Check if any changesets have actual package releases const hasReleases = state.changesets.some(cs => cs.releases.length > 0); if (hasReleases) { console.log("Will release the following packages:"); state.changesets.forEach(cs => { cs.releases.forEach(r => { console.log(`- ${r.name}@${r.type}`); }); }); } ``` -------------------------------- ### GitHub Action Workflow for Publishing Source: https://github.com/changesets/action/blob/main/README.md This YAML configuration sets up a GitHub Actions workflow to automatically release packages to npm using the changesets/action. It checks out the repository, sets up pnpm and Node.js, installs dependencies, and then uses the changesets/action to publish. It requires an NPM_TOKEN secret to be configured in the repository. ```yaml name: Release on: push: branches: - main concurrency: ${{ github.workflow }}-${{ github.ref }} jobs: release: name: Release runs-on: ubuntu-latest steps: - name: Checkout Repo uses: actions/checkout@v6 - name: Setup pnpm uses: pnpm/action-setup@v6 - name: Setup Node.js 26 uses: actions/setup-node@v6 with: node-version: 26 - name: Install Dependencies run: pnpm install --frozen-lockfile - name: Create Release Pull Request or Publish to npm id: changesets uses: changesets/action@v1 with: # This expects you to have a script called release which does a build for your packages and calls changeset publish publish: pnpm release env: NPM_TOKEN: ${{ secrets.NPM_TOKEN }} - name: Send a Slack notification if a publish happens if: steps.changesets.outputs.published == 'true' # You can do something when a publish happens. run: my-slack-bot send-notification --message "A new version of ${GITHUB_REPOSITORY} was published!" ``` -------------------------------- ### Use Case: Checking if Release PR Should Be Created Source: https://github.com/changesets/action/blob/main/_autodocs/api-reference/readChangesetState.md An example demonstrating how to use readChangesetState to determine if a version pull request should be created based on the presence of changesets. ```typescript import readChangesetState from "@changesets/action"; const state = await readChangesetState(cwd); if (state.changesets.length === 0) { console.log("No changesets found, skipping version PR"); } else if (state.changesets.some(cs => cs.releases.length > 0)) { console.log("Creating version PR..."); } ``` -------------------------------- ### Run Tests Source: https://github.com/changesets/action/blob/main/_autodocs/MODULE_MAP.md Commands to run tests using pnpm. ```bash pnpm test # Run once pnpm test:watch # Watch mode ``` -------------------------------- ### Publishing Flow Source: https://github.com/changesets/action/blob/main/_autodocs/MODULE_MAP.md Illustrates the data flow for publishing packages. ```text index.ts ↓ !hasChangesets && hasPublishScript ↓ runPublish() ├─ Setup NPM auth (.npmrc or OIDC) ├─ Run publish script ├─ Parse script output for new tags ├─ Get packages from workspace ├─ For each published package: │ ├─ Push tag (git.pushTag) │ └─ Create release (createRelease → octokit.rest.repos.createRelease) └─ Return published packages list ``` -------------------------------- ### Pre-Release Detection Flow Source: https://github.com/changesets/action/blob/main/_autodocs/MODULE_MAP.md Illustrates the data flow for detecting pre-release state. ```text readChangesetState() ├─ Read .changeset/pre.json ├─ Read .changeset/*.md files ├─ If preState.mode === "pre": │ └─ Filter out preState.changesets └─ Return { preState, changesets } ``` -------------------------------- ### Formatting Source: https://github.com/changesets/action/blob/main/_autodocs/MODULE_MAP.md Commands to format code using pnpm scripts. ```bash pnpm format:fix # Auto-format code pnpm format # Check format only ``` -------------------------------- ### Testing NPM Publish Locally Source: https://github.com/changesets/action/blob/main/_autodocs/errors.md Command to test the npm publish process locally. ```bash npm publish ``` -------------------------------- ### With Publishing Source: https://github.com/changesets/action/blob/main/_autodocs/configuration.md GitHub Actions workflow step for Changesets Action configured to publish packages, including environment variables for authentication and a Slack notification on successful publishing. ```yaml - uses: changesets/action@v1 id: changesets with: publish: pnpm release env: NPM_TOKEN: ${{ secrets.NPM_TOKEN }} - name: Send Slack notification if: steps.changesets.outputs.published == 'true' run: | echo "Published: ${{ steps.changesets.outputs.publishedPackages }}" ``` -------------------------------- ### Typical workflow for creating and pushing a release branch Source: https://github.com/changesets/action/blob/main/_autodocs/api-reference/git.md Illustrates a common workflow for preparing, committing, and pushing a release branch, including pushing tags. ```typescript import { Git } from "@changesets/action"; import { setupOctokit } from "@changesets/action"; const token = process.env.GITHUB_TOKEN; const cwd = process.cwd(); // Initialize Git instance (using API for faster operations) const git = new Git({ octokit: setupOctokit(token), cwd, }); // Prepare the release branch await git.prepareBranch("changeset-release/main"); // Make changes to files... // (version updates, changelog entries, etc.) // Commit and push changes await git.pushChanges({ branch: "changeset-release/main", message: "Version Packages", }); // Push tags for released packages await git.pushTag("@myorg/pkg@1.0.0"); await git.pushTag("v1.0.0"); ``` -------------------------------- ### Testing PNPM Publish Locally Source: https://github.com/changesets/action/blob/main/_autodocs/errors.md Command to test the pnpm publish process locally. ```bash pnpm publish ``` -------------------------------- ### Entering Pre-Release Mode Source: https://github.com/changesets/action/blob/main/_autodocs/errors.md Command to enter pre-release mode for Changesets, used for fixing corrupted pre.json files. ```bash changeset pre enter rc ``` -------------------------------- ### VersionOptions Type Source: https://github.com/changesets/action/blob/main/_autodocs/types.md Options for configuring the version PR creation workflow. ```typescript type VersionOptions = { script?: string; githubToken: string; git: Git; octokit: Octokit; cwd?: string; prTitle?: string; commitMessage?: string; hasPublishScript?: boolean; prBodyMaxCharacters?: number; prDraft?: "always" | "create"; branch?: string; } ``` -------------------------------- ### Testing Custom Version Script Locally Source: https://github.com/changesets/action/blob/main/_autodocs/errors.md Command to run a custom version script locally for debugging. ```bash pnpm {custom-version-script} ``` -------------------------------- ### getVersionsByDirectory Function Signature Source: https://github.com/changesets/action/blob/main/_autodocs/api-reference/utils.md Read all packages and return a map of their current versions indexed by directory. ```typescript export async function getVersionsByDirectory( cwd: string ): Promise> ``` -------------------------------- ### Checking File Permissions for .netrc Source: https://github.com/changesets/action/blob/main/_autodocs/errors.md Command to list file details, including permissions, for the .netrc file. ```bash ls -la ~/.netrc ``` -------------------------------- ### Version PR Creation Flow Source: https://github.com/changesets/action/blob/main/_autodocs/MODULE_MAP.md Illustrates the data flow for creating a Version Pull Request. ```text index.ts ↓ hasChangesets && hasNonEmptyChangesets ↓ runVersion() ├─ Prepare release branch (git.prepareBranch) ├─ Run version script (changeset version or custom) ├─ Get versions before/after ├─ Parse CHANGELOG entries ├─ Generate PR body (getVersionPrBody) ├─ Find/fetch existing PR ├─ Create or update PR (octokit.rest.pulls) └─ Return PR number ``` -------------------------------- ### Git CLI Execution Mode (Default) Source: https://github.com/changesets/action/blob/main/_autodocs/MODULE_MAP.md Details the operations performed in the default Git CLI execution mode. ```text Git { octokit: null, cwd } ├─ setupUser() → git config user.name/email ├─ prepareBranch() → git checkout/checkout -b + git reset ├─ pushChanges() → git add . + git commit + git push --force └─ pushTag() → git push origin {tag} ``` -------------------------------- ### With Custom Version Script Source: https://github.com/changesets/action/blob/main/_autodocs/configuration.md GitHub Actions workflow step for Changesets Action specifying a custom script for versioning and a script for publishing. ```yaml - uses: changesets/action@v1 with: version: pnpm version:script publish: pnpm release ``` -------------------------------- ### Directory Layout Source: https://github.com/changesets/action/blob/main/_autodocs/MODULE_MAP.md The directory layout of the @changesets/action project. ```bash action/ ├── src/ │ ├── index.ts # Main action entry point (167 lines) │ ├── run.ts # Version & publish operations (436 lines) │ ├── git.ts # Git operations class (129 lines) │ ├── octokit.ts # GitHub API client setup (41 lines) │ ├── readChangesetState.ts # Changeset state reading (29 lines) │ ├── utils.ts # Utility functions (115 lines) │ ├── run.test.ts # Tests for run.ts │ └── utils.test.ts # Tests for utils.ts ├── action.yml # GitHub Action metadata ├── package.json # Node.js package manifest ├── rolldown.config.js # Build configuration └── README.md # User-facing documentation ``` -------------------------------- ### Minimal: Create Version PRs Only Source: https://github.com/changesets/action/blob/main/_autodocs/configuration.md A basic GitHub Actions workflow configuration to create version Pull Requests using Changesets Action. ```yaml name: Release on: push: branches: - main concurrency: ${{ github.workflow }}-${{ github.ref }} jobs: release: runs-on: ubuntu-latest steps: - uses: actions/checkout@v6 - uses: pnpm/action-setup@v6 - uses: actions/setup-node@v6 with: node-version: 24 - run: pnpm install --frozen-lockfile - uses: changesets/action@v1 ``` -------------------------------- ### With Yarn 2 / Plug'n'Play Source: https://github.com/changesets/action/blob/main/README.md Configuration for the Changesets action when using Yarn Plug'n'Play, specifying a custom version command. ```yaml - uses: changesets/action@v1 with: version: yarn changeset version # ... ``` -------------------------------- ### Testing Changeset Version Script Locally Source: https://github.com/changesets/action/blob/main/_autodocs/errors.md Command to run the Changeset version script locally for debugging. ```bash pnpm changeset version ``` -------------------------------- ### Error Handling Source: https://github.com/changesets/action/blob/main/_autodocs/api-reference/index.md Top-level error catching in the Changesets Action to log errors and mark the action step as failed. ```typescript .catch((err) => { core.error(err); core.setFailed(err.message); }); ``` -------------------------------- ### Setting .netrc Permissions Source: https://github.com/changesets/action/blob/main/_autodocs/errors.md Command to set appropriate file permissions (read/write for owner only) for the .netrc file. ```bash chmod 600 ~/.netrc ``` -------------------------------- ### With Draft PRs Source: https://github.com/changesets/action/blob/main/_autodocs/configuration.md GitHub Actions workflow step for Changesets Action configured to create draft Pull Requests. ```yaml - uses: changesets/action@v1 with: prDraft: "create" ``` -------------------------------- ### GitOptions Type Source: https://github.com/changesets/action/blob/main/_autodocs/types.md Options object for git operations. ```typescript type GitOptions = { cwd: string; } ``` -------------------------------- ### Dependency Graph Source: https://github.com/changesets/action/blob/main/_autodocs/MODULE_MAP.md The dependency graph of the @changesets/action modules. ```text index.ts (entry point) ├── setupOctokit() [octokit.ts] ├── Git [git.ts] │ └── exec, getExecOutput [@actions/exec] ├── readChangesetState() [readChangesetState.ts] │ ├── readPreState [@changesets/pre] │ └── readChangesets [@changesets/read] ├── runVersion() [run.ts] │ ├── readChangesetState() [readChangesetState.ts] │ ├── Git [git.ts] │ ├── setupOctokit() [octokit.ts] │ ├── getVersionsByDirectory() [utils.ts] │ ├── getChangedPackages() [utils.ts] │ ├── getChangelogEntry() [utils.ts] │ ├── sortTheThings() [utils.ts] │ └── getVersionPrBody() [run.ts] └── runPublish() [run.ts] ├── getExecOutput [@actions/exec] ├── getPackages [@manypkg/get-packages] ├── isErrorWithCode() [utils.ts] ├── getChangelogEntry() [utils.ts] └── Git [git.ts] ``` -------------------------------- ### Enable Verbose Logging Source: https://github.com/changesets/action/blob/main/_autodocs/errors.md How to enable debug logging for the Changesets action by setting the ACTIONS_STEP_DEBUG environment variable. ```yaml - uses: changesets/action@v1 env: ACTIONS_STEP_DEBUG: true ``` -------------------------------- ### Type Checking Source: https://github.com/changesets/action/blob/main/_autodocs/MODULE_MAP.md Command to run the TypeScript compiler for type checking. ```bash pnpm typecheck # Run TypeScript compiler ``` -------------------------------- ### GitHub API Execution Mode Source: https://github.com/changesets/action/blob/main/_autodocs/MODULE_MAP.md Details the operations performed when using the GitHub API for execution. ```text Git { octokit: Octokit, cwd } ├─ setupUser() → no-op ├─ prepareBranch() → no-op ├─ pushChanges() → commitChangesFromRepo() via @changesets/ghcommit └─ pushTag() → octokit.rest.git.createRef() ``` -------------------------------- ### GitHub Action Workflow for Custom Publishing Source: https://github.com/changesets/action/blob/main/README.md This workflow demonstrates how to use the 'hasChangesets' output from the changesets/action to trigger custom publishing logic. It skips the default publishing step and allows users to implement their own publishing commands. ```yaml name: Release on: push: branches: - main jobs: release: name: Release runs-on: ubuntu-latest steps: - name: Checkout Repo uses: actions/checkout@v6 - name: Setup pnpm uses: pnpm/action-setup@v6 - name: Setup Node.js 26 uses: actions/setup-node@v6 with: node-version: 26 - name: Install Dependencies run: pnpm install --frozen-lockfile - name: Create Release Pull Request or Publish to npm id: changesets uses: changesets/action@v1 - name: Publish if: steps.changesets.outputs.hasChangesets == 'false' # You can do something when a publish should happen. run: pnpm publish ``` -------------------------------- ### GitHub Action Workflow with Version Script Source: https://github.com/changesets/action/blob/main/README.md This workflow demonstrates how to use a custom version script with the changesets/action. If a 'version' script is defined in the package.json, the action will execute that script instead of the default 'changeset version' command, allowing for additional logic during the versioning process. ```yaml name: Release on: push: branches: - main concurrency: ${{ github.workflow }}-${{ github.ref }} jobs: release: name: Release runs-on: ubuntu-latest steps: - name: Checkout Repo uses: actions/checkout@v6 - name: Setup pnpm uses: pnpm/action-setup@v6 - name: Setup Node.js 26 uses: actions/setup-node@v6 with: node-version: 26 - name: Install Dependencies run: pnpm install --frozen-lockfile - name: Create Release Pull Request uses: changesets/action@v1 with: # this expects you to have a npm script called version that runs some logic and then calls `changeset version`. version: pnpm version ``` -------------------------------- ### PublishOptions Type Source: https://github.com/changesets/action/blob/main/_autodocs/types.md Options for configuring the publish operation. ```typescript type PublishOptions = { script: string; githubToken: string; octokit: Octokit; createGithubReleases: boolean; git: Git; cwd: string; } ``` -------------------------------- ### getChangelogEntry Function Signature Source: https://github.com/changesets/action/blob/main/_autodocs/api-reference/utils.md Extract changelog content for a specific version from a CHANGELOG.md file. ```typescript export function getChangelogEntry( changelog: string, version: string ): { content: string; highestLevel: number; } ```