Compare commits

...
Author SHA1 Message Date
changeset-internal-publish-bot[bot] c47fa68bd4 v2.0.0-next.3 2026-07-01 14:06:32 +00:00
Mateusz Burzyński e3e2663c0e Add uncommitted .github/actions/setup-bot-auth (#687)
* Add uncommitted `.github/actions/setup-bot-auth`

* tweak codeowners
2026-07-01 13:52:58 +00:00
Mateusz Burzyński e43c867727 Setup git user in the release script (#686)
* Setup git user in the release script

* refactor stuff
2026-07-01 13:29:33 +00:00
changesets-org-version-bot[bot]andgithub-actions[bot] 4b6e1f1099 Version Packages (next) (#677)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-07-01 12:28:07 +00:00
Mateusz Burzyński cf45e93c21 Use split publishing workflow (#679)
* fix release line timing

* Use split publishing workflow

* remove release check, handle through publish plan

* remove unused script

* remove unused publish plan output

* fmt

* update a thing

* fmt

* simplify

* update pre

* update changesets cli
2026-07-01 12:24:41 +00:00
Bjorn Lu 73591071e6 Rename root action inputs and outputs (#681) 2026-07-01 12:08:50 +00:00
Mateusz Burzyński f71ae043ed Expect publish output to be shared through a file (#678)
* Expect publish output to be shared through a file

* throw at all times

* match latest changes

* fmt

* rename things

* update changesets

* add changeset
2026-07-01 09:08:14 +00:00
Bjorn Lu ca57073900 Split git tag and github release options (#680)
* Split git tag and github release options

* Rename to push-git-tags

* Validate inputs
2026-07-01 07:30:13 +00:00
Bjorn Lu 0eae789230 Rename to kebab-case for root action inputs and outputs (#668)
* Rename to kebab-case for root action inputs and outputs

* Throw on renamed inputs
2026-06-30 08:24:21 +00:00
Bjorn Lu 164652bdd6 Remove GITHUB_TOKEN env var support (#674) 2026-06-30 00:20:57 +00:00
Bjorn LuandMateusz Burzyński a35a66bd1e Update @changesets/ghcommit to v3 beta (#675)
Co-authored-by: Mateusz Burzyński <mateuszburzynski@gmail.com>
2026-06-25 11:01:17 +00:00
Bjorn LuandMateusz Burzyński 823cf741ca Update to changesets v3 packages (#673)
* Update to changesets v3 packages

* Dedupe

* Fix test

* Fix test 2

* update more

---------

Co-authored-by: Mateusz Burzyński <mateuszburzynski@gmail.com>
2026-06-25 10:58:02 +00:00
changesets-org-version-bot[bot]andgithub-actions[bot] b12c36a7bf Version Packages (next) (#671)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-06-24 10:28:35 +00:00
Mateusz Burzyński 5a8b9b721b Avoid putting the github token in the global .netrc file (#670)
* Avoid putting the github token in the global `.netrc` file

* fix wording
2026-06-24 10:07:11 +00:00
changesets-org-version-bot[bot]andgithub-actions[bot] 0490518932 Version Packages (next) (#664)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-06-23 11:29:25 +00:00
Mateusz Burzyński dc29b738b5 Fix the /version subaction to not crash on missing pr-base-branch input (#666)
* use `getOptionalInput` consistently

* introduce `getRequiredInput`

* add changeset
2026-06-23 11:26:43 +00:00
Mateusz Burzyński ccb38113ea Fix the computed publish plan path passed internally to changeset pack by the /pack subaction (#663)
* Fix the computed publish plan path passed internally to `changeset pack` by the `/pack` subaction

* fix it
2026-06-23 10:00:39 +00:00
Mateusz Burzyński cf37561cd9 Fix description of the /version's script input (#665) 2026-06-23 09:55:13 +00:00
Mateusz Burzyński 5c88881fff Fixed usage of --from-publish-plan flag used by the /pack subaction (#662) 2026-06-23 09:25:48 +00:00
52 changed files with 1360 additions and 1397 deletions
+5
View File
@@ -0,0 +1,5 @@
---
"@changesets/action": patch
---
Fix the computed publish plan path passed internally to `changeset pack` by the `/pack` subaction.
+7
View File
@@ -0,0 +1,7 @@
---
"@changesets/action": major
---
Add a new `push-git-tags` option that complements `create-github-releases` to control specifically if git tags should be created but not GitHub releases.
If `create-github-releases` was previously set to `false`, which also indirectly disabled git tag creation, git tags will now be created instead by default. If this is not desired, set `push-git-tags` to `false` explicitly.
+7 -6
View File
@@ -1,13 +1,14 @@
{
"$schema": "https://unpkg.com/@changesets/config@1.6.2/schema.json",
"changelog": [
"@changesets/changelog-github",
{ "repo": "changesets/action" }
],
"$schema": "https://unpkg.com/@changesets/config@4.0.0-next.6/schema.json",
"changelog": "@changesets/changelog-github",
"commit": false,
"linked": [],
"access": "restricted",
"baseBranch": "main",
"updateInternalDependencies": "patch",
"ignore": []
"ignore": [],
"privatePackages": {
"version": true,
"tag": true
}
}
+17
View File
@@ -0,0 +1,17 @@
---
"@changesets/action": major
---
Rename the root action inputs and outputs to better match the sub-actions' conventions.
Inputs:
- `version` -> `version-script`
- `publish` -> `publish-script`
- `commit` -> `commit-message`
- `title` -> `pr-title`
- `branch` -> `pr-base-branch`
Outputs:
- `pull-request-number` -> `pr-number`
+5
View File
@@ -0,0 +1,5 @@
---
"@changesets/action": major
---
Remove support for passing custom GitHub token through the GITHUB_TOKEN environment variable. It should be passed to the `github-token` input instead.
+5
View File
@@ -0,0 +1,5 @@
---
"@changesets/action": patch
---
Authenticate git CLI pushes with the configured GitHub token using Git extra headers instead of writing to a global `.netrc` file.
+5
View File
@@ -0,0 +1,5 @@
---
"@changesets/action": patch
---
Derive the Git server URL from the GitHub Actions context when configuring git CLI authentication to support GitHub Enterprise Server setups.
+16 -4
View File
@@ -1,8 +1,20 @@
{
"mode": "pre",
"tag": "next",
"initialVersions": {
"@changesets/action": "1.9.0"
},
"changesets": ["eight-clocks-pull", "eighty-doors-swim", "lemon-turtles-itch"]
"changesets": [
"all-cars-grin",
"chubby-geese-sink",
"eight-clocks-pull",
"eighty-doors-swim",
"eighty-parks-tickle",
"fiery-toes-vanish",
"git-cli-auth-header",
"git-cli-server-url",
"lemon-turtles-itch",
"ready-mangos-boil",
"shaky-rings-type",
"shy-months-crash",
"silent-tips-dance",
"yellow-roses-fix"
]
}
+5
View File
@@ -0,0 +1,5 @@
---
"@changesets/action": patch
---
Fixed usage of `--from-publish-plan` flag used by the `/pack` subaction
+5
View File
@@ -0,0 +1,5 @@
---
"@changesets/action": major
---
Update to Changesets v3 packages
+5
View File
@@ -0,0 +1,5 @@
---
"@changesets/action": minor
---
Published packages detection done through stdout parsing was replaced with one based on the shared output file using `CHANGESETS_OUTPUT` environment variable. When using custom scripts this environment variable should always be passed down to the Changesets CLI invocations.
+5
View File
@@ -0,0 +1,5 @@
---
"@changesets/action": patch
---
Fix the `/version` subaction to not crash on missing `pr-base-branch` input. This input is meant to be optional.
+5
View File
@@ -0,0 +1,5 @@
---
"@changesets/action": major
---
Rename the input and output names to kebab-case instead of camelCase to match the official GitHub actions pattern
+1 -1
View File
@@ -1,4 +1,4 @@
/.github/workflows/** @Andarist @bluwy @emmatown
/.github/** @Andarist @bluwy @emmatown
/action.yml @Andarist @bluwy @emmatown
/scripts/bump.ts @Andarist @bluwy @emmatown
/scripts/release.ts @Andarist @bluwy @emmatown
+44
View File
@@ -0,0 +1,44 @@
name: Setup bot auth
description: Create a GitHub App token and configure matching git identity
inputs:
client-id:
description: GitHub App client ID
required: true
private-key:
description: GitHub App private key
required: true
permission-contents:
description: Contents permission for the GitHub App token
required: false
default: write
permission-pull-requests:
description: Pull requests permission for the GitHub App token
required: false
outputs:
token:
description: GitHub App installation access token
value: ${{ steps.app-token.outputs.token }}
runs:
using: composite
steps:
- uses: actions/create-github-app-token@bcd2ba49218906704ab6c1aa796996da409d3eb1 # v3.2.0
id: app-token
with:
client-id: ${{ inputs.client-id }}
private-key: ${{ inputs.private-key }}
permission-contents: ${{ inputs.permission-contents }}
permission-pull-requests: ${{ inputs.permission-pull-requests }}
- name: Setup Git user
shell: bash
run: |
app_user="$APP_SLUG[bot]"
app_id="$(gh api "/users/$app_user" --jq .id)"
git config user.name "$app_user"
git config user.email "$app_id+$app_user@users.noreply.github.com"
env:
APP_SLUG: ${{ steps.app-token.outputs.app-slug }}
GH_TOKEN: ${{ steps.app-token.outputs.token }}
+61 -35
View File
@@ -15,13 +15,12 @@ concurrency:
permissions: {} # each job should define its own permission explicitly
jobs:
version:
name: Version
select-mode:
name: Select mode
runs-on: ubuntu-latest
environment: version
timeout-minutes: 20
outputs:
hasChangesets: ${{ steps.changesets.outputs.hasChangesets }}
mode: ${{ steps.select-mode.outputs.mode }}
permissions:
contents: read # to check out repo (actions/checkout)
steps:
@@ -37,38 +36,20 @@ jobs:
- name: Build
run: pnpm build
- uses: actions/create-github-app-token@bcd2ba49218906704ab6c1aa796996da409d3eb1 # v3.2.0
id: app-token
with:
client-id: ${{ vars.APP_CLIENT_ID }}
private-key: ${{ secrets.APP_PRIVATE_KEY }}
permission-contents: write # to create version commits (changesets/action)
permission-pull-requests: write # to create pull request (changesets/action)
- name: Select mode
id: select-mode
uses: ./select-mode
- name: Create or update release pull request
id: changesets
uses: ./
with:
github-token: ${{ steps.app-token.outputs.token }}
version: pnpm bump
publish:
name: Publish
if: needs.version.outputs.hasChangesets == 'false'
needs: version
version:
name: Version
if: needs.select-mode.outputs.mode == 'version'
needs: select-mode
runs-on: ubuntu-latest
environment: marketplace
environment: version
timeout-minutes: 20
permissions:
contents: write # to create release and have it authored by github-actions (changesets/action)
contents: read # to check out repo (actions/checkout)
steps:
- uses: actions/create-github-app-token@bcd2ba49218906704ab6c1aa796996da409d3eb1 # v3.2.0
id: app-token
with:
client-id: ${{ vars.APP_CLIENT_ID }}
private-key: ${{ secrets.APP_PRIVATE_KEY }}
permission-contents: write # to bypass branch and tag protection rules (release.ts)
- name: Check out repo
uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3
with:
@@ -81,8 +62,53 @@ jobs:
- name: Build
run: pnpm build
- name: Publish to marketplace
uses: ./
- uses: ./.github/actions/setup-bot-auth
id: bot-auth
with:
github-token: ${{ steps.app-token.outputs.token }}
publish: pnpm release
client-id: ${{ vars.APP_CLIENT_ID }}
private-key: ${{ secrets.APP_PRIVATE_KEY }}
permission-contents: write # to create version commits (changesets/action)
permission-pull-requests: write # to create pull request (changesets/action)
- name: Create or update release pull request
id: changesets
uses: ./version
with:
github-token: ${{ steps.bot-auth.outputs.token }}
setup-git-user: false
script: pnpm bump
publish:
name: Publish
if: needs.select-mode.outputs.mode == 'publish'
needs: select-mode
runs-on: ubuntu-latest
environment: marketplace
timeout-minutes: 20
permissions:
contents: write # to create release and have it authored by github-actions (changesets/action)
steps:
- name: Check out repo
uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3
with:
persist-credentials: false
- uses: ./.github/actions/ci-setup
with:
skip-cache: true # avoid cache poisoning attacks
- name: Build
run: pnpm build
- uses: ./.github/actions/setup-bot-auth
id: bot-auth
with:
client-id: ${{ vars.APP_CLIENT_ID }}
private-key: ${{ secrets.APP_PRIVATE_KEY }}
permission-contents: write # to bypass branch and tag protection rules (release.ts)
- name: Publish to marketplace
uses: ./publish
with:
github-token: ${{ steps.bot-auth.outputs.token }}
script: pnpm release
+7 -12
View File
@@ -122,13 +122,6 @@ jobs:
pull-requests: write # to comment on the pull request with the release result (changesets/action)
steps:
- uses: actions/create-github-app-token@bcd2ba49218906704ab6c1aa796996da409d3eb1 # v3.2.0
id: app-token
with:
client-id: ${{ vars.APP_CLIENT_ID }}
private-key: ${{ secrets.APP_PRIVATE_KEY }}
permission-contents: write # to push the release snapshot branch (release-pr.ts)
- name: Check out repo
uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3
with:
@@ -173,15 +166,17 @@ jobs:
- name: Build
run: pnpm build
- name: Setup Git user
run: |
git config --global user.name "github-actions[bot]"
git config --global user.email "41898282+github-actions[bot]@users.noreply.github.com"
- uses: ./.github/actions/setup-bot-auth
id: bot-auth
with:
client-id: ${{ vars.APP_CLIENT_ID }}
private-key: ${{ secrets.APP_PRIVATE_KEY }}
permission-contents: write # to push the release snapshot branch (release-pr.ts)
- name: Release snapshot version
run: pnpm release:pr
env:
GITHUB_TOKEN: ${{ steps.app-token.outputs.token }}
GITHUB_TOKEN: ${{ steps.bot-auth.outputs.token }}
- name: Add success reaction
run: gh api "/repos/$GH_REPO/issues/comments/$COMMENT_ID/reactions" -f content='rocket'
+48
View File
@@ -1,5 +1,53 @@
# @changesets/action
## 2.0.0-next.3
### Major Changes
- [#680](https://github.com/changesets/action/pull/680) [`ca57073`](https://github.com/changesets/action/commit/ca57073900dc678254406a052a03c0c8824e319d) Thanks [@bluwy](https://github.com/bluwy)! - Add a new `push-git-tags` option that complements `create-github-releases` to control specifically if git tags should be created but not GitHub releases.
If `create-github-releases` was previously set to `false`, which also indirectly disabled git tag creation, git tags will now be created instead by default. If this is not desired, set `push-git-tags` to `false` explicitly.
- [#681](https://github.com/changesets/action/pull/681) [`7359107`](https://github.com/changesets/action/commit/73591071e61c7f61cf322dd7a6341dc29a8e1d4e) Thanks [@bluwy](https://github.com/bluwy)! - Rename the root action inputs and outputs to better match the sub-actions' conventions.
Inputs:
- `version` -> `version-script`
- `publish` -> `publish-script`
- `commit` -> `commit-message`
- `title` -> `pr-title`
- `branch` -> `pr-base-branch`
Outputs:
- `pull-request-number` -> `pr-number`
- [#674](https://github.com/changesets/action/pull/674) [`164652b`](https://github.com/changesets/action/commit/164652bdd60525670d95291addb8c6f92833ac60) Thanks [@bluwy](https://github.com/bluwy)! - Remove support for passing custom GitHub token through the GITHUB_TOKEN environment variable. It should be passed to the `github-token` input instead.
- [#673](https://github.com/changesets/action/pull/673) [`823cf74`](https://github.com/changesets/action/commit/823cf741ca57c5e22652123d3a847dfafcd77ca0) Thanks [@bluwy](https://github.com/bluwy)! - Update to Changesets v3 packages
- [#668](https://github.com/changesets/action/pull/668) [`0eae789`](https://github.com/changesets/action/commit/0eae789230defbc4ad287e9b476aba7e842e34e0) Thanks [@bluwy](https://github.com/bluwy)! - Rename the input and output names to kebab-case instead of camelCase to match the official GitHub actions pattern
### Minor Changes
- [#678](https://github.com/changesets/action/pull/678) [`f71ae04`](https://github.com/changesets/action/commit/f71ae043ed5deb17952900091e009a60edef9507) Thanks [@Andarist](https://github.com/Andarist)! - Published packages detection done through stdout parsing was replaced with one based on the shared output file using `CHANGESETS_OUTPUT` environment variable. When using custom scripts this environment variable should always be passed down to the Changesets CLI invocations.
## 2.0.0-next.2
### Patch Changes
- [#670](https://github.com/changesets/action/pull/670) [`5a8b9b7`](https://github.com/changesets/action/commit/5a8b9b721bf683e3bf9bd72ea92a685dc024147b) Thanks [@Andarist](https://github.com/Andarist)! - Authenticate git CLI pushes with the configured GitHub token using Git extra headers instead of writing to a global `.netrc` file.
- [#670](https://github.com/changesets/action/pull/670) [`5a8b9b7`](https://github.com/changesets/action/commit/5a8b9b721bf683e3bf9bd72ea92a685dc024147b) Thanks [@Andarist](https://github.com/Andarist)! - Derive the Git server URL from the GitHub Actions context when configuring git CLI authentication to support GitHub Enterprise Server setups.
## 2.0.0-next.1
### Patch Changes
- [#663](https://github.com/changesets/action/pull/663) [`ccb3811`](https://github.com/changesets/action/commit/ccb38113eaaa4a13eb6aabe09520e49cc8519b84) Thanks [@Andarist](https://github.com/Andarist)! - Fix the computed publish plan path passed internally to `changeset pack` by the `/pack` subaction.
- [#662](https://github.com/changesets/action/pull/662) [`5c88881`](https://github.com/changesets/action/commit/5c88881fff1f0d8b055d4a2d3a74a8ce843db6f3) Thanks [@Andarist](https://github.com/Andarist)! - Fixed usage of `--from-publish-plan` flag used by the `/pack` subaction
- [#666](https://github.com/changesets/action/pull/666) [`dc29b73`](https://github.com/changesets/action/commit/dc29b738b532d9e95f46b9bf493e2e3fdf48a7ed) Thanks [@Andarist](https://github.com/Andarist)! - Fix the `/version` subaction to not crash on missing `pr-base-branch` input. This input is meant to be optional.
## 2.0.0-next.0
### Major Changes
+8 -8
View File
@@ -65,7 +65,7 @@ jobs:
run: pnpm install --frozen-lockfile
- name: Create Release Pull Request
uses: changesets/action@v1
uses: changesets/action@v2
```
#### With Publishing
@@ -103,10 +103,10 @@ jobs:
- name: Create Release Pull Request or Publish to npm
id: changesets
uses: changesets/action@v1
uses: changesets/action@v2
with:
# This expects you to have a script called release which does a build for your packages and calls changeset publish
publish: pnpm release
publish-script: pnpm release
env:
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
@@ -170,7 +170,7 @@ jobs:
- name: Create Release Pull Request or Publish to npm
id: changesets
uses: changesets/action@v1
uses: changesets/action@v2
- name: Publish
if: steps.changesets.outputs.hasChangesets == 'false'
@@ -214,10 +214,10 @@ jobs:
run: pnpm install --frozen-lockfile
- name: Create Release Pull Request
uses: changesets/action@v1
uses: changesets/action@v2
with:
# this expects you to have a npm script called version that runs some logic and then calls `changeset version`.
version: pnpm version
version-script: pnpm version
```
#### With Yarn 2 / Plug'n'Play
@@ -225,8 +225,8 @@ jobs:
If you are using [Yarn Plug'n'Play](https://yarnpkg.com/features/pnp), you should use a custom `version` command so that the action can resolve the `changeset` CLI:
```yaml
- uses: changesets/action@v1
- uses: changesets/action@v2
with:
version: yarn changeset version
version-script: yarn changeset version
# ...
```
+27 -20
View File
@@ -8,28 +8,37 @@ inputs:
description: "The GitHub token to use for authentication. Defaults to the GitHub-provided token."
required: false
default: ${{ github.token }}
publish:
publish-script:
description: "The command to use to build and publish packages"
required: false
version:
version-script:
description: "The command to update version, edit CHANGELOG, read and delete changesets. Default to `changeset version` if not provided"
required: false
commit:
description: |
The commit message. Default to `Version Packages`
commit-message:
description: "The commit message. Default to `Version Packages`"
required: false
title:
description: The pull request title. Default to `Version Packages`
default: "Version Packages"
pr-title:
description: "The pull request title. Default to `Version Packages`"
required: false
setupGitUser:
description: Sets up the git user for commits as `"github-actions[bot]"`. Default to `true`
default: "Version Packages"
pr-draft:
description: "Controls draft PR behavior. Use 'create' to create new version PRs as draft, or 'always' to also convert existing version PRs back to draft when updating them."
required: false
pr-base-branch:
description: "Sets the base branch of the PR. Defaults to `github.ref_name`."
required: false
create-github-releases:
description: "Whether to create Github releases after publish"
required: false
default: true
createGithubReleases:
description: "A boolean value to indicate whether to create Github releases after `publish` or not"
push-git-tags:
description: >
Whether to create git tags after publish. If `create-github-releases` is set to `true`,
this option will also always be `true`.
required: false
default: true
commitMode:
commit-mode:
description: >
An enum to specify the commit mode. Use "git-cli" to push changes using the Git CLI,
or "github-api" to push changes via the GitHub API. When using "github-api",
@@ -37,21 +46,19 @@ inputs:
or app who owns the GITHUB_TOKEN.
required: false
default: "git-cli"
branch:
description: Sets the branch in which the action will run. Default to `github.ref_name` if not provided
required: false
prDraft:
description: 'Controls draft PR behavior. Use "create" to create new version PRs as draft, or "always" to also convert existing version PRs back to draft when updating them.'
setup-git-user:
description: Sets up the git user for commits as `"github-actions[bot]"`. Default to `true`
required: false
default: true
outputs:
published:
description: A boolean value to indicate whether a publishing is happened or not
publishedPackages:
published-packages:
description: >
A JSON array to present the published packages. The format is `[{"name": "@xx/xx", "version": "1.2.0"}, {"name": "@xx/xy", "version": "0.8.9"}]`
hasChangesets:
has-changesets:
description: A boolean about whether there were changesets. Useful if you want to create your own publishing functionality.
pullRequestNumber:
pr-number:
description: The pull request number that was created or updated
branding:
icon: "package"
+12
View File
File diff suppressed because one or more lines are too long
+2
View File
@@ -0,0 +1,2 @@
import{d as e,f as t,l as n,m as r,p as i,u as a}from"./manypkg-get-packages-BoFCbqAx.js";import{n as o,r as s,t as c}from"./run-Bw2IS-rI.js";import{c as l,f as u,r as d,s as f}from"./utils-DxGVktYo.js";import{t as p}from"./readChangesetState-wtnwjhXS.js";import m from"node:fs/promises";(async()=>{u({publish:`publish-script`,version:`version-script`,commit:`commit-mesage`,title:`pr-title`,branch:`pr-base-branch`,prDraft:`pr-draft`,createGithubReleases:`create-github-releases`,commitMode:`commit-mode`,setupGitUser:`setup-git-user`});let h=l(`github-token`);if(process.env.GITHUB_TOKEN&&process.env.GITHUB_TOKEN!==h)throw Error(`The GITHUB_TOKEN environment variable is set and does not match the "github-token" input. Please pass the custom GitHub token to the "github-token" input and remove the GITHUB_TOKEN environment variable to avoid conflicts.`);let g=process.cwd(),_=f(`commit-mode`)??`git-cli`,v=f(`pr-draft`);if(_!==`git-cli`&&_!==`github-api`){i(`Invalid commit mode: ${_}`);return}if(v!==void 0&&v!==`always`&&v!==`create`){i(`Invalid pr-draft: ${v}`);return}let y=new s({cwd:g,githubToken:h,commitMode:_});a(`setup-git-user`)&&(t(`setting git user`),await y.setupUser());let{changesets:b}=await p(g),x=e(`publish-script`),S=b.length!==0,C=b.some(e=>e.releases.length>0),w=!!x;switch(r(`published`,`false`),r(`published-packages`,`[]`),r(`has-changesets`,String(S)),!0){case!S&&!w:t(`No changesets present or were removed by merging release PR. Not publishing because no publish script found.`);return;case!S&&w:{if(t(`No changesets found. Attempting to publish any unpublished packages to npm`),process.env.NPM_TOKEN){let e=`${process.env.HOME}/.npmrc`;await d(e)?(t(`Found existing user .npmrc file`),(await m.readFile(e,`utf8`)).split(`
`).find(e=>/^\s*\/\/registry\.npmjs\.org\/:[_-]authToken=/i.test(e))?t(`Found existing auth token for the npm registry in the user .npmrc file`):(t(`Didn't find existing auth token for the npm registry in the user .npmrc file, creating one`),await m.appendFile(e,`\n//registry.npmjs.org/:_authToken=${process.env.NPM_TOKEN}\n`))):(t(`No user .npmrc file found, creating one with NPM_TOKEN used as auth token`),await m.writeFile(e,`//registry.npmjs.org/:_authToken=${process.env.NPM_TOKEN}\n`))}else process.env.ACTIONS_ID_TOKEN_REQUEST_TOKEN&&process.env.ACTIONS_ID_TOKEN_REQUEST_URL?t(`No NPM_TOKEN found, but OIDC is available - using npm trusted publishing`):t(`No NPM_TOKEN or OIDC available - assuming npm is already authenticated`);let e=a(`create-github-releases`),i=a(`push-git-tags`);if(e&&!i)throw Error(`The input 'create-github-releases' is set to true, but 'push-git-tags' is set to false. Creating GitHub releases requires pushing git tags. Please set 'push-git-tags' to true or set 'create-github-releases' to false.`);let o=await c({script:x,github:y,createGithubReleases:e,pushGitTags:i,cwd:g});o.published&&(r(`published`,`true`),r(`published-packages`,JSON.stringify(o.publishedPackages))),o.exitCode!==0&&(n(`Publish command exited with code ${o.exitCode}${o.published?`, but some packages were published: ${o.publishedPackages.map(e=>`${e.name}@${e.version}`).join(`, `)}`:``}`),process.exit(o.exitCode));return}case S&&!C:t(`All changesets are empty; not creating PR`);return;case S:{let{pullRequestNumber:e}=await o({script:f(`version-script`),github:y,cwd:g,prTitle:f(`pr-title`),commitMessage:f(`commit-message`),hasPublishScript:w,prDraft:v,branch:f(`pr-base-branch`)});r(`pr-number`,String(e));return}}})().catch(e=>{n(e),i(e.message)});export{};
File diff suppressed because one or more lines are too long
+1
View File
@@ -0,0 +1 @@
import{m as e,p as t}from"./manypkg-get-packages-BoFCbqAx.js";import{n,p as r,s as i,t as a}from"./utils-DxGVktYo.js";import o from"node:fs/promises";import s from"node:path";import c from"node:os";try{await l()}catch(e){t(e.message)}async function l(){let t=i(`publish-plan-artifact-id`),n=process.cwd(),a=process.env.RUNNER_TEMP??await o.realpath(c.tmpdir()),l=s.join(a,`changeset-pack-${Date.now()}`);await u(n,{outDir:l,publishPlanPath:t?await d(a,Number(t)):void 0});let p=await r.uploadArtifact(`changeset-pack-${Date.now()}`,await f(l),l,{retentionDays:30});if(p.id===void 0)throw Error(`Packed artifact upload did not return an artifact id`);e(`pack-dir-artifact-id`,String(p.id))}async function u(e,t){let r=[`pack`,`--out-dir`,t.outDir];t.publishPlanPath&&r.push(`--from-publish-plan`,t.publishPlanPath),await n(r,{cwd:e,env:process.env})}async function d(e,t){let n=await a(e,t,`changeset-publish-plan`);return s.join(n,`publish-plan.json`)}async function f(e){let t=await o.readdir(e,{withFileTypes:!0});return(await Promise.all(t.map(async t=>{let n=s.join(e,t.name);return t.isDirectory()?f(n):[n]}))).flat()}export{};
+1
View File
@@ -0,0 +1 @@
import{a as e,f as t,i as n,m as r,p as i}from"./manypkg-get-packages-BoFCbqAx.js";import{c as a,s as o}from"./utils-DxGVktYo.js";try{await s()}catch(e){i(e.message)}async function s(){let i=n.payload.pull_request;if(!i)throw Error("This action should only be run on `pull_request_target` or `pull_request` events");let s=a(`github-token`),l=a(`body`),u=o(`update-id`),d=u?c(u):null,f=d?`${d}\n\n${l}`:l,p={repo:i.base.repo.name,owner:i.base.repo.owner.login,issue_number:i.number,body:f},m=e(s),h;d&&(t(`Checking for existing comment...`),h=await m.rest.issues.listComments({repo:i.base.repo.name,owner:i.base.repo.owner.login,issue_number:i.number}).then(e=>e.data.find(e=>e.body?.includes(d))?.id)),h?(t(`Updating existing comment (id: ${h})...`),await m.rest.issues.updateComment({...p,comment_id:h}),r(`comment-id`,h)):(t(`Creating new comment...`),r(`comment-id`,(await m.rest.issues.createComment(p)).data.id)),t(`Done!`)}function c(e){let t=`changesets-action-pr-comment`;return t===e?`<!-- ${t} -->`:`<!-- ${t}:${e} -->`}export{};
+38
View File
File diff suppressed because one or more lines are too long
+1
View File
@@ -0,0 +1 @@
import{m as e,p as t,u as n}from"./manypkg-get-packages-BoFCbqAx.js";import{r,t as i}from"./run-Bw2IS-rI.js";import{c as a,s as o,t as s}from"./utils-DxGVktYo.js";import c from"node:fs/promises";import l from"node:os";try{await u()}catch(e){t(e.message)}async function u(){let t=a(`github-token`),u=o(`script`),d=o(`pack-dir-artifact-id`),f=n(`create-github-releases`),p=n(`push-git-tags`);if(f&&!p)throw Error(`The input 'create-github-releases' is set to true, but 'push-git-tags' is set to false. Creating GitHub releases requires pushing git tags. Please set 'push-git-tags' to true or set 'create-github-releases' to false.`);let m=process.cwd(),h=await i({script:u,github:new r({cwd:m,githubToken:t,commitMode:`github-api`}),createGithubReleases:f,pushGitTags:p,cwd:m,fromPackDir:d?await s(process.env.RUNNER_TEMP??await c.realpath(l.tmpdir()),Number(d),`changeset-pack`):void 0});if(h.published?(e(`published`,`true`),e(`published-packages`,JSON.stringify(h.publishedPackages))):e(`published`,`false`),h.exitCode!==0)throw Error(`Publish command exited with code ${h.exitCode}${h.published?`, but some packages were published: ${h.publishedPackages.map(e=>`${e.name}@${e.version}`).join(`, `)}`:``}`)}export{};
+1
View File
@@ -0,0 +1 @@
import{i as e,t}from"./dist-IQHIouET.js";async function n(n=process.cwd()){let r=await e(n),i=await t(n);if(r!==void 0&&r.mode===`pre`){let e=new Set(r.changesets);return{preState:r,changesets:i.filter(t=>!e.has(t.id))}}return{preState:void 0,changesets:i}}export{n as t};
+98
View File
@@ -0,0 +1,98 @@
import{T as e,_ as t,a as n,f as r,g as i,i as a,t as o,v as s}from"./manypkg-get-packages-BoFCbqAx.js";import{o as c}from"./dist-IQHIouET.js";import{a as l,d as u,i as d,l as f,m as p,n as m,o as h,u as g}from"./utils-DxGVktYo.js";import{t as ee}from"./readChangesetState-wtnwjhXS.js";import _ from"node:fs/promises";import v from"path";import{Buffer as y}from"node:buffer";import{randomUUID as b}from"node:crypto";import x from"node:path";import S from"node:os";const C=async(e,t)=>(await e.graphql(`
query getRepositoryMetadata(
$owner: String!
$repo: String!
$baseRef: String!
$targetRef: String!
) {
repository(owner: $owner, name: $repo) {
id
baseRef: ref(qualifiedName: $baseRef) {
id
target {
oid
... on Tag {
target {
oid
}
}
}
}
targetBranch: ref(qualifiedName: $targetRef) {
id
target {
oid
}
}
}
}
`,t)).repository,w=async(e,t)=>e.graphql(`
mutation createCommitOnBranch($input: CreateCommitOnBranchInput!) {
createCommitOnBranch(input: $input) {
commit {
oid
}
ref {
id
}
}
}
`,t);function T(e){if(typeof e==`object`)return{headline:e.headline.trim(),body:e.body?.trim()};if(!e.includes(`
`))return{headline:e.trim()};let[t,...n]=e.split(`
`);return{headline:t.trim(),body:n.join(`
`).trim()}}function E(e){return`branch`in e?`refs/heads/${e.branch}`:`tag`in e?`refs/tags/${e.tag}`:e.commit}async function D({octokit:e,owner:t,repo:n,branch:r,base:i,force:a=!1,message:o,fileChanges:s}){let c=E(i),l=await C(e,{owner:t,repo:n,baseRef:c,targetRef:`refs/heads/${r}`});if(!l)throw Error(`Repository "${t}/${n}" not found`);let u=`commit`in i?i.commit:O(l.baseRef);if(!u)throw Error(`Could not determine sha for base ref "${c}"`);let d=l.targetBranch?.target?.oid??null,f=async(t,n)=>{let r=await w(e,{input:{branch:{id:t},expectedHeadOid:u,message:T(o),fileChanges:s}});if(r.createCommitOnBranch?.ref?.id==null)throw Error(`Failed to create commit on branch "${n}"`);if(r.createCommitOnBranch?.commit?.oid==null)throw Error(`Failed to determine commit sha for commit on branch "${n}"`);return{commitSha:r.createCommitOnBranch.commit.oid}};if(d==null){let i=(await e.rest.git.createRef({owner:t,repo:n,ref:`refs/heads/${r}`,sha:u})).data.node_id;if(!i)throw Error(`Failed to create branch "${r}"`);return await f(i,r),{refId:i}}else if(d===u){let e=l.targetBranch.id;return await f(e,r),{refId:e}}else if(a){let i=`changesets-ghcommit-temp/${r}`;try{let{tempRefId:a}=await k({octokit:e,owner:t,repo:n,tempBranch:i,baseSha:u}),{commitSha:o}=await f(a,i),s=(await e.rest.git.updateRef({owner:t,repo:n,ref:`heads/${r}`,sha:o,force:!0})).data.node_id;if(!s)throw Error(`Failed to force update branch "${r}"`);return{refId:s}}finally{await e.rest.git.deleteRef({owner:t,repo:n,ref:`heads/${i}`})}}else throw Error(`Branch "${r}" exists but its HEAD does not match the base ${u} and \`force\` is set to false`)}function O(e){return e?.target?`target`in e.target?e.target.target.oid:e.target.oid:null}async function k({octokit:e,owner:t,repo:n,tempBranch:r,baseSha:i}){try{let a=(await e.rest.git.createRef({owner:t,repo:n,ref:`refs/heads/${r}`,sha:i})).data.node_id;if(!a)throw Error(`Failed to create temporary branch "${r}"`);return{tempRefId:a}}catch(a){if(!A(a))throw a;let o=(await e.rest.git.updateRef({owner:t,repo:n,ref:`heads/${r}`,sha:i,force:!0})).data.node_id;if(!o)throw Error(`Failed to force update temporary branch "${r}"`);return{tempRefId:o}}}function A(e){return typeof e==`object`&&!!e&&`status`in e&&`message`in e&&typeof e.status==`number`&&typeof e.message==`string`&&e.status===422&&e.message.includes(`Reference already exists`)}async function j({cwd:e,filterFiles:t,...n}){e=v.resolve(e??process.cwd());let r=E(n.base??{commit:`HEAD`}),i=await N(e,r);if(!i)throw Error(`Could not determine sha for ref ${r}`);return await D({...n,fileChanges:await M(e,i,t),base:{commit:i}})}async function M(e,t,n){let r=await P(e),i=[],a=[],o=async e=>{if(n&&!n(e))return;let t=v.join(r,e),a=await _.lstat(t);if(a.isSymbolicLink())throw Error(`Unexpected symlink at ${e}, GitHub API only supports files and directories. You may need to add this file to .gitignore`);if(a.mode&73)throw Error(`Unexpected executable file at ${e}, GitHub API only supports non-executable files and directories. You may need to add this file to .gitignore`);i.push({path:e,contents:await _.readFile(t,`base64`)})},s=e=>{n&&!n(e)||a.push({path:e})},[l,u]=await Promise.all([c(`git`,[`diff`,`--name-status`,`--diff-filter=ACDMRT`,t],{throwOnError:!0,nodeOptions:{cwd:r}}),c(`git`,[`ls-files`,`--others`,`--exclude-standard`],{throwOnError:!0,nodeOptions:{cwd:r}})]);for(let e of l.stdout.trim().split(`
`)){if(!e)continue;let[t,...n]=e.split(` `);if(t.startsWith(`R`)||t.startsWith(`C`)){let[e,t]=n;s(e),await o(t);continue}let r=n[0];t===`D`?s(r):await o(r)}for(let e of u.stdout.trim().split(`
`))e&&await o(e);return i.sort((e,t)=>e.path>t.path?1:-1),a.sort((e,t)=>e.path>t.path?1:-1),{additions:i,deletions:a}}async function N(e,t){try{let{stdout:n}=await c(`git`,[`rev-parse`,t],{throwOnError:!0,nodeOptions:{cwd:e}});return n.trim()}catch{return null}}async function P(e){try{let{stdout:t}=await c(`git`,[`rev-parse`,`--git-dir`],{throwOnError:!0,nodeOptions:{cwd:e}});return v.dirname(v.resolve(e,t.trim()))}catch{return e}}var F=e(p(),1),I=`0.0.0-development`,L=()=>Promise.resolve();function R(e,t,n){return e.retryLimiter.schedule(z,e,t,n)}async function z(e,t,n){let{pathname:r}=new URL(n.url,`http://github.test`),i=B(n.method,r),a=!i&&n.method!==`GET`&&n.method!==`HEAD`,o=n.method===`GET`&&r.startsWith(`/search/`),s=r.startsWith(`/graphql`),c=~~t.retryCount>0?{priority:0,weight:0}:{};e.clustering&&(c.expiration=1e3*60),(a||s)&&await e.write.key(e.id).schedule(c,L),a&&e.triggersNotification(r)&&await e.notifications.key(e.id).schedule(c,L),o&&await e.search.key(e.id).schedule(c,L);let l=(i?e.auth:e.global).key(e.id).schedule(c,t,n);if(s){let e=await l;if(e.data.errors!=null&&e.data.errors.some(e=>e.type===`RATE_LIMITED`))throw Object.assign(Error(`GraphQL Rate Limit Exceeded`),{response:e,data:e.data})}return l}function B(e,t){return e===`PATCH`&&/^\/applications\/[^/]+\/token\/scoped$/.test(t)||e===`POST`&&(/^\/applications\/[^/]+\/token$/.test(t)||/^\/app\/installations\/[^/]+\/access_tokens$/.test(t)||t===`/login/oauth/access_token`)}var V=[`/orgs/{org}/invitations`,`/orgs/{org}/invitations/{invitation_id}`,`/orgs/{org}/teams/{team_slug}/discussions`,`/orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments`,`/repos/{owner}/{repo}/collaborators/{username}`,`/repos/{owner}/{repo}/commits/{commit_sha}/comments`,`/repos/{owner}/{repo}/issues`,`/repos/{owner}/{repo}/issues/{issue_number}/comments`,`/repos/{owner}/{repo}/issues/{issue_number}/sub_issue`,`/repos/{owner}/{repo}/issues/{issue_number}/sub_issues/priority`,`/repos/{owner}/{repo}/pulls`,`/repos/{owner}/{repo}/pulls/{pull_number}/comments`,`/repos/{owner}/{repo}/pulls/{pull_number}/comments/{comment_id}/replies`,`/repos/{owner}/{repo}/pulls/{pull_number}/merge`,`/repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers`,`/repos/{owner}/{repo}/pulls/{pull_number}/reviews`,`/repos/{owner}/{repo}/releases`,`/teams/{team_id}/discussions`,`/teams/{team_id}/discussions/{discussion_number}/comments`];function H(e){let t=`^(?:${e.map(e=>e.split(`/`).map(e=>e.startsWith(`{`)?`(?:.+?)`:e).join(`/`)).map(e=>`(?:${e})`).join(`|`)})[^/]*$`;return new RegExp(t,`i`)}var U=H(V),W=U.test.bind(U),G={},K=function(e,t){G.global=new e.Group({id:`octokit-global`,maxConcurrent:10,...t}),G.auth=new e.Group({id:`octokit-auth`,maxConcurrent:1,...t}),G.search=new e.Group({id:`octokit-search`,maxConcurrent:1,minTime:2e3,...t}),G.write=new e.Group({id:`octokit-write`,maxConcurrent:1,minTime:1e3,...t}),G.notifications=new e.Group({id:`octokit-notifications`,maxConcurrent:1,minTime:3e3,...t})};function q(e,t){let{enabled:n=!0,Bottleneck:r=F.default,id:i=`no-id`,timeout:a=1e3*60*2,connection:o}=t.throttle||{};if(!n)return{};let s={timeout:a};o!==void 0&&(s.connection=o),G.global??K(r,s);let c=Object.assign({clustering:o!=null,triggersNotification:W,fallbackSecondaryRateRetryAfter:60,retryAfterBaseValue:1e3,retryLimiter:new r,id:i,...G},t.throttle);if(typeof c.onSecondaryRateLimit!=`function`||typeof c.onRateLimit!=`function`)throw Error(`octokit/plugin-throttling error:
You must pass the onSecondaryRateLimit and onRateLimit error handlers.
See https://octokit.github.io/rest.js/#throttling
const octokit = new Octokit({
throttle: {
onSecondaryRateLimit: (retryAfter, options) => {/* ... */},
onRateLimit: (retryAfter, options) => {/* ... */}
}
})
`);let l={},u=new r.Events(l);return l.on(`secondary-limit`,c.onSecondaryRateLimit),l.on(`rate-limit`,c.onRateLimit),l.on(`error`,t=>e.log.warn(`Error in throttling-plugin limit handler`,t)),c.retryLimiter.on(`failed`,async function(t,n){let[r,i,a]=n.args,{pathname:o}=new URL(a.url,`http://github.test`);if(!(o.startsWith(`/graphql`)&&t.status!==401||t.status===403||t.status===429))return;let s=~~i.retryCount;i.retryCount=s,a.request.retryCount=s;let{wantRetry:c,retryAfter:l=0}=await(async function(){if(/\bsecondary rate\b/i.test(t.message)){let n=Number(t.response.headers[`retry-after`])||r.fallbackSecondaryRateRetryAfter;return{wantRetry:await u.trigger(`secondary-limit`,n,a,e,s),retryAfter:n}}if(t.response.headers!=null&&t.response.headers[`x-ratelimit-remaining`]===`0`||(t.response.data?.errors??[]).some(e=>e.type===`RATE_LIMITED`)){let n=new Date(~~t.response.headers[`x-ratelimit-reset`]*1e3).getTime(),r=Math.max(Math.ceil((n-Date.now())/1e3)+1,0);return{wantRetry:await u.trigger(`rate-limit`,r,a,e,s),retryAfter:r}}return{}})();if(c)return i.retryCount++,l*r.retryAfterBaseValue}),e.hook.wrap(`request`,R.bind(null,c)),{}}q.VERSION=I,q.triggersNotification=W;const J=e=>n(e,{throttle:{onRateLimit:(e,t,n,a)=>{if(i(`Request quota exhausted for request ${t.method} ${t.url}`),a<=2)return r(`Retrying after ${e} seconds!`),!0},onSecondaryRateLimit:(e,t,n,a)=>{if(i(`SecondaryRateLimit detected for request ${t.method} ${t.url}`),a<=2)return r(`Retrying after ${e} seconds!`),!0}}},q),Y=async(e,n)=>{await t(`git`,[`push`,`origin`,`HEAD:${e}`,`--force`],n)},X=async(e,n)=>{let{stderr:r}=await s(`git`,[`checkout`,e],{ignoreReturnCode:!0,...n});r.toString().includes(`Switched to a new branch '${e}'`)||await t(`git`,[`checkout`,`-b`,e],n)},Z=async(e,n)=>{await t(`git`,[`reset`,`--hard`,e],n)},Q=async(e,n)=>{await t(`git`,[`add`,`.`],n),await t(`git`,[`commit`,`-m`,e],n)},te=async e=>{let{stdout:t}=await s(`git`,[`status`,`--porcelain`],e);return!t.length};var ne=class{#e;octokit;cwd;commitMode;constructor(e){this.#e=e.githubToken,this.cwd=e.cwd,this.commitMode=e.commitMode??`git-cli`,this.octokit=J(e.githubToken)}getToken(){return this.#e}#t(){let e=y.from(`x-access-token:${this.#e}`).toString(`base64`),t=(a.serverUrl??process.env.GITHUB_SERVER_URL??`https://github.com`).replace(/\/+$/,``),n=Number(process.env.GIT_CONFIG_COUNT??0);if(!Number.isInteger(n)||n<0)throw Error(`Invalid GIT_CONFIG_COUNT value: ${process.env.GIT_CONFIG_COUNT}`);return{GIT_CONFIG_COUNT:String(n+1),[`GIT_CONFIG_KEY_${n}`]:`http.${t}/.extraheader`,[`GIT_CONFIG_VALUE_${n}`]:`AUTHORIZATION: basic ${e}`}}async setupUser(){this.commitMode!==`github-api`&&(await t(`git`,[`config`,`user.name`,`"github-actions[bot]"`],{cwd:this.cwd}),await t(`git`,[`config`,`user.email`,`"41898282+github-actions[bot]@users.noreply.github.com"`],{cwd:this.cwd}))}async pushTag(e){if(this.commitMode===`github-api`)return this.octokit.rest.git.createRef({...a.repo,ref:`refs/tags/${e}`,sha:a.sha}).catch(t=>{i(`Failed to create tag ${e}: ${t.message}`)});await t(`git`,[`push`,`origin`,e],{cwd:this.cwd,env:{...process.env,...this.#t()}})}async prepareBranch(e){this.commitMode!==`github-api`&&(await X(e,{cwd:this.cwd}),await Z(a.sha,{cwd:this.cwd}))}async pushChanges({branch:e,message:t}){if(this.commitMode===`github-api`){await j({octokit:this.octokit,...a.repo,branch:e,message:t,base:{commit:a.sha},cwd:this.cwd});return}await te({cwd:this.cwd})||await Q(t,{cwd:this.cwd}),await Y(e,{cwd:this.cwd,env:{...process.env,...this.#t()}})}};const re=async(e,{pkg:t,tagName:n})=>{let r;try{r=await _.readFile(x.join(t.dir,`CHANGELOG.md`),`utf8`)}catch(e){if(g(e,`ENOENT`))return;throw e}let i=l(r,t.packageJson.version);if(!i)throw Error(`Could not find changelog entry for ${t.packageJson.name}@${t.packageJson.version}`);await e.rest.repos.createRelease({name:n,tag_name:n,body:i.content,prerelease:t.packageJson.version.includes(`-`),...a.repo})};function $(e){return typeof e==`object`&&!!e}function ie(e){return $(e)&&`type`in e&&e.type===`git-tag`&&`tag`in e&&typeof e.tag==`string`&&`packageName`in e&&typeof e.packageName==`string`}async function ae(e){let t;try{t=await _.readFile(e,`utf8`)}catch(t){throw Error(`Failed to read changesets output at ${e}`,{cause:t})}let n=[],r=0;for(;r<=t.length;){let e=t.indexOf(`
`,r);e===-1&&(e=t.length);let i=t.slice(r,e);if(r=e+1,/^\s*$/.test(i))continue;let a;try{a=JSON.parse(i)}catch(e){throw Error(`Failed to parse changesets output event: ${i}`,{cause:e})}ie(a)&&n.push(a)}return n}async function oe({script:e,fromPackDir:t,github:n,createGithubReleases:r,pushGitTags:i,cwd:a}){let{octokit:c}=n,l,u=x.join(process.env.RUNNER_TEMP??await _.realpath(S.tmpdir()),`changesets-output-${b()}.ndjson`),d={cwd:a,ignoreReturnCode:!0,env:{...process.env,GITHUB_TOKEN:n.getToken(),CHANGESETS_OUTPUT:u}};if(e)l=await s(e,void 0,d);else{let e=[`publish`];t&&e.push(`--from-pack-dir`,t),l=await h(e,d)}let{packages:f,tool:p}=await o(a),m=new Map(f.map(e=>[e.packageJson.name,e])),g=(await ae(u)).map(e=>{let t=m.get(e.packageName);if(t===void 0)throw Error(`Package "${e.packageName}" not found.This is probably a bug in the action, please open an issue`);return{pkg:t,tag:e.tag}});if(p.type===`root`&&f.length===0)throw Error(`No package found.This is probably a bug in the action, please open an issue`);return(r||i)&&await Promise.all(g.map(async({pkg:e,tag:t})=>{i&&await n.pushTag(t),r&&await re(c,{pkg:e,tagName:t})})),g.length?{published:!0,publishedPackages:g.map(({pkg:e})=>({name:e.packageJson.name,version:e.packageJson.version})),exitCode:l.exitCode}:{published:!1,exitCode:l.exitCode}}async function se({hasPublishScript:e,preState:t,changedPackagesInfo:n,prBodyMaxCharacters:r,branch:i}){let a=`This PR was opened by the [Changesets release](https://github.com/changesets/action) GitHub action. When you're ready to do a release, you can merge this and ${e?`the packages will be published to npm automatically`:`publish to npm yourself or [setup this action to publish automatically](https://github.com/changesets/action#with-publishing)`}. If you're not ready to do a release yet, that's fine, whenever you add more changesets to ${i}, this PR will be updated.
`,o=t?`⚠️⚠️⚠️⚠️⚠️⚠️
\`${i}\` is currently in **pre mode** so this branch has prereleases rather than normal releases. If you want to exit prereleases, run \`changeset pre exit\` on \`${i}\`.
⚠️⚠️⚠️⚠️⚠️⚠️
`:``,s=`# Releases`,c=[a,o,s,...n.map(e=>`${e.header}\n\n${e.content}`)].join(`
`);return c.length>r&&(c=[a,o,s,`
> The changelog information of each package has been omitted from this message, as the content exceeds the size limit.
`,...n.map(e=>`${e.header}\n\n`)].join(`
`)),c.length>r&&(c=[a,o,s,`
> All release information have been omitted from this message, as the content exceeds the size limit.`].join(`
`)),c}async function ce({script:e,github:n,cwd:i=process.cwd(),prTitle:o=`Version Packages`,commitMessage:s=`Version Packages`,hasPublishScript:c=!1,prBodyMaxCharacters:p=6e4,branch:h=a.ref.replace(`refs/heads/`,``),prDraft:g}){let{octokit:v}=n,y=`changeset-release/${h}`,{preState:b}=await ee(i);await n.prepareBranch(y);let S=await f(i),C={...process.env,GITHUB_TOKEN:n.getToken()};e?await t(e,void 0,{cwd:i,env:C}):await m([`version`],{cwd:i,env:C});let w=await d(i,S),T=Promise.all(w.map(async e=>{let t=l(await _.readFile(x.join(e.dir,`CHANGELOG.md`),`utf8`),e.packageJson.version);return{highestLevel:t.highestLevel,private:!!e.packageJson.private,content:t.content,header:`## ${e.packageJson.name}@${e.packageJson.version}`}})),E=`${o}${b?` (${b.tag})`:``}`,D=`${s}${b?` (${b.tag})`:``}`,O=await v.rest.pulls.list({...a.repo,state:`open`,head:`${a.repo.owner}:${y}`,base:h});r(`Existing pull requests: ${JSON.stringify(O.data,null,2)}`),await n.pushChanges({branch:y,message:D});let k=await se({hasPublishScript:c,preState:b,branch:h,changedPackagesInfo:(await T).filter(e=>e).sort(u),prBodyMaxCharacters:p});if(O.data.length===0){r(`creating pull request`);let{data:e}=await v.rest.pulls.create({base:h,head:y,title:E,body:k,draft:g!==void 0,...a.repo});return{pullRequestNumber:e.number}}else{let[e]=O.data;r(`updating found pull request #${e.number}`);let t=`
mutation UpdatePullRequest(
$pullRequestId: ID!
$title: String!
$body: String!
) {
${g===`always`?`
convertPullRequestToDraft(
input: {
pullRequestId: $pullRequestId
}
) {
pullRequest {
id
}
}`:``}
updatePullRequest(
input: {
pullRequestId: $pullRequestId
title: $title
body: $body
state: OPEN
}
) {
pullRequest {
id
}
}
}
`;return await v.graphql(t,{pullRequestId:e.node_id,title:E,body:k}),{pullRequestNumber:e.number}}}export{ce as n,ne as r,oe as t};
+1
View File
@@ -0,0 +1 @@
import{m as e,p as t}from"./manypkg-get-packages-BoFCbqAx.js";import{n,p as r}from"./utils-DxGVktYo.js";import{t as i}from"./readChangesetState-wtnwjhXS.js";import a from"node:fs/promises";import o from"node:path";import s from"node:os";try{await c()}catch(e){t(e.message)}async function c(){let t=await l();if(e(`mode`,t.mode),t.mode===`publish`){let n=await r.uploadArtifact(o.basename(t.publishPlanPath,`.json`),[t.publishPlanPath],o.dirname(t.publishPlanPath),{skipArchive:!0,retentionDays:30});if(n.id===void 0)throw Error(`Publish plan artifact upload did not return an artifact id`);e(`publish-plan-artifact-id`,String(n.id))}}async function l(){let{changesets:e}=await i();if(e.length>0)return e.some(e=>e.releases.length>0)?{mode:`version`}:{mode:`none`};let t=process.cwd(),r=o.join(process.env.RUNNER_TEMP??await a.realpath(s.tmpdir()),`changeset-publish-plan-${Date.now()}`,`publish-plan.json`);return await n([`publish-plan`,`--output`,r],{cwd:t,env:process.env}),(await u(r)).length===0?{mode:`none`}:{mode:`publish`,publishPlanPath:r}}async function u(e){let t;try{t=await a.readFile(e,`utf8`)}catch(t){throw Error(`Failed to read publish plan at ${e}`,{cause:t})}let n;try{n=JSON.parse(t)}catch(t){throw Error(`Failed to parse publish plan at ${e}`,{cause:t})}if(typeof n!=`object`||!n||!(`version`in n)||typeof n.version!=`number`||!(`plan`in n)||!Array.isArray(n.plan))throw Error(`Invalid publish plan at ${e}: expected { version: number; plan: unknown[] }`);return n.plan}export{};
+82
View File
File diff suppressed because one or more lines are too long
+1
View File
@@ -0,0 +1 @@
import{f as e,m as t,p as n,u as r}from"./manypkg-get-packages-BoFCbqAx.js";import{n as i,r as a}from"./run-Bw2IS-rI.js";import{c as o,s}from"./utils-DxGVktYo.js";try{await c()}catch(e){n(e.message)}async function c(){let n=o(`github-token`),c=s(`script`),l=o(`commit-message`),u=o(`pr-title`),d=s(`pr-draft`),f=s(`pr-base-branch`),p=s(`commit-mode`)??`git-cli`,m=r(`setup-git-user`);if(d!==void 0&&d!==`always`&&d!==`create`)throw Error(`Invalid pr-draft input: ${d}`);if(p!==`git-cli`&&p!==`github-api`)throw Error(`Invalid commit-mode input: ${p}`);let h=process.cwd(),g=new a({cwd:h,githubToken:n,commitMode:p});m&&(e(`setting git user`),await g.setupUser());let{pullRequestNumber:_}=await i({script:c,github:g,cwd:h,prTitle:u,commitMessage:l,hasPublishScript:!0,prDraft:d,branch:f});t(`pr-number`,String(_))}export{};
+12 -11
View File
@@ -1,6 +1,7 @@
{
"name": "@changesets/action",
"version": "2.0.0-next.0",
"version": "2.0.0-next.3",
"private": true,
"license": "MIT",
"type": "module",
"main": "dist/index.js",
@@ -21,12 +22,12 @@
"@actions/core": "^3.0.1",
"@actions/exec": "^3.0.0",
"@actions/github": "^9.1.1",
"@changesets/get-release-plan": "^4.0.16",
"@changesets/ghcommit": "^2.1.1",
"@changesets/git": "^3.0.4",
"@changesets/pre": "^2.0.2",
"@changesets/read": "^0.6.7",
"@manypkg/get-packages": "^1.1.3",
"@changesets/get-release-plan": "^5.0.0-next.7",
"@changesets/ghcommit": "^3.0.0-next.1",
"@changesets/git": "^4.0.0-next.6",
"@changesets/pre": "^3.0.0-next.6",
"@changesets/read": "^1.0.0-next.7",
"@manypkg/get-packages": "^3.1.0",
"@octokit/core": "^7.0.6",
"@octokit/plugin-throttling": "^11.0.3",
"human-id": "^4.1.3",
@@ -35,10 +36,10 @@
"tinyexec": "^1.2.4"
},
"devDependencies": {
"@changesets/changelog-github": "^0.7.0",
"@changesets/cli": "^2.31.0",
"@changesets/types": "^6.1.0",
"@changesets/write": "^0.4.0",
"@changesets/changelog-github": "^1.0.0-next.6",
"@changesets/cli": "^3.0.0-next.8",
"@changesets/types": "^7.0.0-next.6",
"@changesets/write": "^1.0.0-next.6",
"@tsconfig/node24": "^24.0.4",
"@types/node": "^24.12.4",
"@types/semver": "^7.7.1",
+275 -1046
View File
File diff suppressed because it is too large Load Diff
+17 -1
View File
@@ -3,7 +3,23 @@ dedupePeers: true
dedupePeerDependents: true
minimumReleaseAge: 10080
minimumReleaseAgeExclude:
- "@changesets/ghcommit@2.1.1"
- "@changesets/apply-release-plan@8.0.0-next.7"
- "@changesets/assemble-release-plan@7.0.0-next.7"
- "@changesets/changelog-git@1.0.0-next.6"
- "@changesets/changelog-github@1.0.0-next.6"
- "@changesets/cli@3.0.0-next.8"
- "@changesets/config@4.0.0-next.6"
- "@changesets/get-dependents-graph@3.0.0-next.6"
- "@changesets/get-github-info@1.0.0-next.3"
- "@changesets/get-release-plan@5.0.0-next.7"
- "@changesets/ghcommit@3.0.0-next.1"
- "@changesets/git@4.0.0-next.6"
- "@changesets/parse@1.0.0-next.7"
- "@changesets/pre@3.0.0-next.6"
- "@changesets/read@1.0.0-next.7"
- "@changesets/should-skip-package@1.0.0-next.6"
- "@changesets/types@7.0.0-next.6"
- "@changesets/write@1.0.0-next.6"
overrides:
lightningcss: "-" # we do not bundle any css
+6
View File
@@ -18,6 +18,12 @@ inputs:
description: "Whether to create Github releases after publish"
required: false
default: true
push-git-tags:
description: >
Whether to create git tags after publish. If `create-github-releases` is set to `true`,
this option will also always be `true`.
required: false
default: true
outputs:
published:
description: "A boolean value to indicate whether a publishing has happened or not"
+3 -1
View File
@@ -1,12 +1,14 @@
import fs from "node:fs";
import path from "node:path";
import { exec } from "@actions/exec";
import pkgJson from "../package.json" with { type: "json" };
process.chdir(path.join(import.meta.dirname, ".."));
await exec("changeset", ["version"]);
// read after versioning to get the new version
const pkgJson = (await import("../package.json", { with: { type: "json" } }))
.default;
const releaseLine = `v${pkgJson.version.split(".")[0]}`;
const readmePath = path.join(import.meta.dirname, "..", "README.md");
+4 -24
View File
@@ -1,6 +1,6 @@
import { Buffer } from "node:buffer";
import path from "node:path";
import { exec, getExecOutput } from "@actions/exec";
import { exec } from "@actions/exec";
import pkgJson from "../package.json" with { type: "json" };
const tag = `v${pkgJson.version}`;
@@ -20,37 +20,17 @@ const gitEnv = {
process.chdir(path.join(import.meta.dirname, ".."));
(async () => {
const { exitCode, stderr } = await getExecOutput(
`git`,
["ls-remote", "--exit-code", "origin", "--tags", `refs/tags/${tag}`],
{
ignoreReturnCode: true,
},
);
if (exitCode === 0) {
console.log(
`Action is not being published because version ${tag} is already published`,
);
return;
}
if (exitCode !== 2) {
throw new Error(`git ls-remote exited with ${exitCode}:\n${stderr}`);
}
await exec("git", ["checkout", "--detach"]);
await exec("git", ["add", "--force", "dist"]);
await exec("git", ["commit", "-m", tag]);
await exec("changeset", ["tag"]);
await exec("changeset", ["git-tag"]);
if (isPrerelease) {
await exec("git", ["push", "origin", `refs/tags/${tag}`], {
env: gitEnv,
});
return;
}
} else {
await exec(
"git",
[
@@ -64,4 +44,4 @@ process.chdir(path.join(import.meta.dirname, ".."));
env: gitEnv,
},
);
})();
}
+71 -28
View File
@@ -1,11 +1,15 @@
import { Buffer } from "node:buffer";
import * as core from "@actions/core";
import { exec, getExecOutput } from "@actions/exec";
import * as github from "@actions/github";
import { commitChangesFromRepo } from "@changesets/ghcommit/git";
import type { Octokit } from "./octokit.ts";
import { context } from "@actions/github";
import { commitChangesSinceBase } from "@changesets/ghcommit";
import { setupOctokit, type Octokit } from "./octokit.ts";
export type CommitMode = "git-cli" | "github-api";
type GitOptions = {
cwd: string;
env?: Record<string, string>;
};
const push = async (branch: string, options: GitOptions) => {
@@ -46,17 +50,51 @@ const checkIfClean = async (options: GitOptions): Promise<boolean> => {
return !stdout.length;
};
export class Git {
readonly octokit: Octokit | null;
export class GitHub {
readonly #githubToken: string;
readonly octokit: Octokit;
readonly cwd: string;
readonly commitMode: CommitMode;
constructor(args: { octokit?: Octokit; cwd: string }) {
this.octokit = args.octokit ?? null;
this.cwd = args.cwd;
constructor(options: {
githubToken: string;
cwd: string;
commitMode?: CommitMode;
}) {
this.#githubToken = options.githubToken;
this.cwd = options.cwd;
this.commitMode = options.commitMode ?? "git-cli";
this.octokit = setupOctokit(options.githubToken);
}
getToken() {
return this.#githubToken;
}
#getCliAuthEnv(): Record<string, string> {
const basic = Buffer.from(`x-access-token:${this.#githubToken}`).toString(
"base64",
);
const serverUrl = (
context.serverUrl ??
process.env.GITHUB_SERVER_URL ??
"https://github.com"
).replace(/\/+$/, "");
const gitConfigCount = Number(process.env.GIT_CONFIG_COUNT ?? 0);
if (!Number.isInteger(gitConfigCount) || gitConfigCount < 0) {
throw new Error(
`Invalid GIT_CONFIG_COUNT value: ${process.env.GIT_CONFIG_COUNT}`,
);
}
return {
GIT_CONFIG_COUNT: String(gitConfigCount + 1),
[`GIT_CONFIG_KEY_${gitConfigCount}`]: `http.${serverUrl}/.extraheader`,
[`GIT_CONFIG_VALUE_${gitConfigCount}`]: `AUTHORIZATION: basic ${basic}`,
};
}
async setupUser() {
if (this.octokit) {
if (this.commitMode === "github-api") {
return;
}
await exec("git", ["config", "user.name", `"github-actions[bot]"`], {
@@ -76,54 +114,59 @@ export class Git {
}
async pushTag(tag: string) {
if (this.octokit) {
if (this.commitMode === "github-api") {
return this.octokit.rest.git
.createRef({
...github.context.repo,
...context.repo,
ref: `refs/tags/${tag}`,
sha: github.context.sha,
sha: context.sha,
})
.catch((err) => {
// Assuming tag was manually pushed in custom publish script
core.warning(`Failed to create tag ${tag}: ${err.message}`);
});
}
await exec("git", ["push", "origin", tag], { cwd: this.cwd });
await exec("git", ["push", "origin", tag], {
cwd: this.cwd,
env: {
...process.env,
...this.#getCliAuthEnv(),
} as Record<string, string>,
});
}
async prepareBranch(branch: string) {
if (this.octokit) {
if (this.commitMode === "github-api") {
// Preparing a new local branch is not necessary when using the API
return;
}
await switchToMaybeExistingBranch(branch, { cwd: this.cwd });
await reset(github.context.sha, { cwd: this.cwd });
await reset(context.sha, { cwd: this.cwd });
}
async pushChanges({ branch, message }: { branch: string; message: string }) {
if (this.octokit) {
/**
* Only add files form the current working directory
*
* This will emulate the behavior of `git add .`,
* used in {@link commitAll}.
*/
const addFromDirectory = this.cwd;
return commitChangesFromRepo({
if (this.commitMode === "github-api") {
await commitChangesSinceBase({
octokit: this.octokit,
...github.context.repo,
...context.repo,
branch,
message,
base: {
commit: github.context.sha,
commit: context.sha,
},
cwd: this.cwd,
force: true,
});
return;
}
if (!(await checkIfClean({ cwd: this.cwd }))) {
await commitAll(message, { cwd: this.cwd });
}
await push(branch, { cwd: this.cwd });
await push(branch, {
cwd: this.cwd,
env: {
...process.env,
...this.#getCliAuthEnv(),
} as Record<string, string>,
});
}
}
+57 -43
View File
@@ -1,59 +1,66 @@
import fs from "node:fs/promises";
import path from "node:path";
import * as core from "@actions/core";
import { Git } from "./git.ts";
import { setupOctokit } from "./octokit.ts";
import { GitHub } from "./github.ts";
import readChangesetState from "./readChangesetState.ts";
import { runPublish, runVersion } from "./run.ts";
import { fileExists } from "./utils.ts";
const getOptionalInput = (name: string) => core.getInput(name) || undefined;
import {
fileExists,
getOptionalInput,
getRequiredInput,
throwOnRenamedInputs,
} from "./utils.ts";
(async () => {
// to maintain compatibility with workflows created before github-token input was introduced
// it's important to prefer the explicitly set GITHUB_TOKEN over the default token coming from github.token
let githubToken = process.env.GITHUB_TOKEN || core.getInput("github-token");
throwOnRenamedInputs({
publish: "publish-script",
version: "version-script",
commit: "commit-mesage",
title: "pr-title",
branch: "pr-base-branch",
prDraft: "pr-draft",
createGithubReleases: "create-github-releases",
commitMode: "commit-mode",
setupGitUser: "setup-git-user",
});
if (!githubToken) {
core.setFailed("Please add the GITHUB_TOKEN to the changesets action");
return;
const githubToken = getRequiredInput("github-token");
if (process.env.GITHUB_TOKEN && process.env.GITHUB_TOKEN !== githubToken) {
throw new Error(
'The GITHUB_TOKEN environment variable is set and does not match the "github-token" input. ' +
'Please pass the custom GitHub token to the "github-token" input and ' +
"remove the GITHUB_TOKEN environment variable to avoid conflicts.",
);
}
// If the user needs to change the cwd, set `working-directory` in the step instead
const cwd = process.cwd();
const octokit = setupOctokit(githubToken);
const commitMode = getOptionalInput("commitMode") ?? "git-cli";
const prDraft = getOptionalInput("prDraft");
const commitMode = getOptionalInput("commit-mode") ?? "git-cli";
const prDraft = getOptionalInput("pr-draft");
if (commitMode !== "git-cli" && commitMode !== "github-api") {
core.setFailed(`Invalid commit mode: ${commitMode}`);
return;
}
if (prDraft !== undefined && prDraft !== "always" && prDraft !== "create") {
core.setFailed(`Invalid prDraft: ${prDraft}`);
core.setFailed(`Invalid pr-draft: ${prDraft}`);
return;
}
const git = new Git({
octokit: commitMode === "github-api" ? octokit : undefined,
const github = new GitHub({
cwd,
githubToken,
commitMode,
});
let setupGitUser = core.getBooleanInput("setupGitUser");
let setupGitUser = core.getBooleanInput("setup-git-user");
if (setupGitUser) {
core.info("setting git user");
await git.setupUser();
await github.setupUser();
}
core.info("setting GitHub credentials");
await fs.writeFile(
`${process.env.HOME}/.netrc`,
`machine github.com\nlogin github-actions[bot]\npassword ${githubToken}`,
);
let { changesets } = await readChangesetState(cwd);
let publishScript = core.getInput("publish");
let publishScript = core.getInput("publish-script");
let hasChangesets = changesets.length !== 0;
const hasNonEmptyChangesets = changesets.some(
(changeset) => changeset.releases.length > 0,
@@ -61,8 +68,8 @@ const getOptionalInput = (name: string) => core.getInput(name) || undefined;
let hasPublishScript = !!publishScript;
core.setOutput("published", "false");
core.setOutput("publishedPackages", "[]");
core.setOutput("hasChangesets", String(hasChangesets));
core.setOutput("published-packages", "[]");
core.setOutput("has-changesets", String(hasChangesets));
switch (true) {
case !hasChangesets && !hasPublishScript:
@@ -120,19 +127,29 @@ const getOptionalInput = (name: string) => core.getInput(name) || undefined;
);
}
const createGithubReleases = core.getBooleanInput(
"create-github-releases",
);
const pushGitTags = core.getBooleanInput("push-git-tags");
if (createGithubReleases && !pushGitTags) {
throw new Error(
"The input 'create-github-releases' is set to true, but 'push-git-tags' is set to false. " +
"Creating GitHub releases requires pushing git tags. Please set 'push-git-tags' to true " +
"or set 'create-github-releases' to false.",
);
}
const result = await runPublish({
script: publishScript,
githubToken,
git,
octokit,
createGithubReleases: core.getBooleanInput("createGithubReleases"),
github,
createGithubReleases,
pushGitTags,
cwd,
});
if (result.published) {
core.setOutput("published", "true");
core.setOutput(
"publishedPackages",
"published-packages",
JSON.stringify(result.publishedPackages),
);
}
@@ -155,21 +172,18 @@ const getOptionalInput = (name: string) => core.getInput(name) || undefined;
core.info("All changesets are empty; not creating PR");
return;
case hasChangesets: {
const octokit = setupOctokit(githubToken);
const { pullRequestNumber } = await runVersion({
script: getOptionalInput("version"),
githubToken,
git,
octokit,
script: getOptionalInput("version-script"),
github,
cwd,
prTitle: getOptionalInput("title"),
commitMessage: getOptionalInput("commit"),
prTitle: getOptionalInput("pr-title"),
commitMessage: getOptionalInput("commit-message"),
hasPublishScript,
prDraft,
branch: getOptionalInput("branch"),
branch: getOptionalInput("pr-base-branch"),
});
core.setOutput("pullRequestNumber", String(pullRequestNumber));
core.setOutput("pr-number", String(pullRequestNumber));
return;
}
+7 -3
View File
@@ -3,7 +3,11 @@ import os from "node:os";
import path from "node:path";
import artifact from "@actions/artifact";
import * as core from "@actions/core";
import { downloadArtifact, execChangesetsCli } from "../utils.ts";
import {
downloadArtifact,
execChangesetsCli,
getOptionalInput,
} from "../utils.ts";
try {
await main();
@@ -12,7 +16,7 @@ try {
}
async function main() {
const publishPlanArtifactId = core.getInput("publish-plan-artifact-id");
const publishPlanArtifactId = getOptionalInput("publish-plan-artifact-id");
// If the user needs to change the cwd, set `working-directory` in the step instead
const cwd = process.cwd();
@@ -49,7 +53,7 @@ async function pack(
) {
const cliArgs = ["pack", "--out-dir", args.outDir];
if (args.publishPlanPath) {
cliArgs.push("--from-plan", args.publishPlanPath);
cliArgs.push("--from-publish-plan", args.publishPlanPath);
}
await execChangesetsCli(cliArgs, {
+4 -3
View File
@@ -1,5 +1,6 @@
import * as core from "@actions/core";
import * as github from "@actions/github";
import { getOptionalInput, getRequiredInput } from "../utils.ts";
type Octokit = ReturnType<typeof github.getOctokit>;
type CreateCommentParams = NonNullable<
@@ -23,9 +24,9 @@ async function main() {
);
}
const githubToken = core.getInput("github-token", { required: true });
const body = core.getInput("body", { required: true });
const updateId = core.getInput("update-id");
const githubToken = getRequiredInput("github-token");
const body = getRequiredInput("body");
const updateId = getOptionalInput("update-id");
const commentMarker = updateId ? getCommentMarker(updateId) : null;
const commentBody = commentMarker ? `${commentMarker}\n\n${body}` : body;
+1 -1
View File
@@ -1,5 +1,5 @@
import * as github from "@actions/github";
import getReleasePlan from "@changesets/get-release-plan";
import { getReleasePlan } from "@changesets/get-release-plan";
import type {
ComprehensiveRelease,
ReleasePlan,
+2 -1
View File
@@ -1,6 +1,6 @@
import { pathToFileURL } from "node:url";
import type * as github from "@actions/github";
import getReleasePlan from "@changesets/get-release-plan";
import { getReleasePlan } from "@changesets/get-release-plan";
import { createFixture } from "fs-fixture";
import { exec } from "tinyexec";
import { describe, expect, it } from "vitest";
@@ -28,6 +28,7 @@ describe("getPullRequestWorktree", () => {
private: true,
workspaces: ["packages/*"],
}),
"package-lock.json": "",
"packages/pkg-a/package.json": JSON.stringify({
name: "pkg-a",
version: "1.0.0",
+22 -12
View File
@@ -1,10 +1,13 @@
import fs from "node:fs/promises";
import os from "node:os";
import * as core from "@actions/core";
import { Git } from "../git.ts";
import { setupOctokit } from "../octokit.ts";
import { GitHub } from "../github.ts";
import { runPublish } from "../run.ts";
import { downloadArtifact } from "../utils.ts";
import {
downloadArtifact,
getOptionalInput,
getRequiredInput,
} from "../utils.ts";
try {
await main();
@@ -13,17 +16,25 @@ try {
}
async function main() {
const githubToken = core.getInput("github-token", { required: true });
const script = core.getInput("script");
const packDirArtifactId = core.getInput("pack-dir-artifact-id");
const githubToken = getRequiredInput("github-token");
const script = getOptionalInput("script");
const packDirArtifactId = getOptionalInput("pack-dir-artifact-id");
const createGithubReleases = core.getBooleanInput("create-github-releases");
const pushGitTags = core.getBooleanInput("push-git-tags");
if (createGithubReleases && !pushGitTags) {
throw new Error(
"The input 'create-github-releases' is set to true, but 'push-git-tags' is set to false. " +
"Creating GitHub releases requires pushing git tags. Please set 'push-git-tags' to true " +
"or set 'create-github-releases' to false.",
);
}
// If the user needs to change the cwd, set `working-directory` in the step instead
const cwd = process.cwd();
const octokit = setupOctokit(githubToken);
// NOTE: Always pass octokit here as publish does not need a commit-mode
const git = new Git({ octokit, cwd });
// NOTE: Always use API mode here as publish does not need a commit-mode.
const github = new GitHub({ cwd, githubToken, commitMode: "github-api" });
const fromPackDir = packDirArtifactId
? await downloadArtifact(
@@ -35,10 +46,9 @@ async function main() {
const result = await runPublish({
script,
githubToken,
git,
octokit,
github,
createGithubReleases,
pushGitTags,
cwd,
fromPackDir,
});
+1 -1
View File
@@ -1,5 +1,5 @@
import { readPreState } from "@changesets/pre";
import readChangesets from "@changesets/read";
import { readChangesets } from "@changesets/read";
import type { PreState, NewChangeset } from "@changesets/types";
export type ChangesetState = {
+20 -29
View File
@@ -1,10 +1,9 @@
import path from "node:path";
import type { Changeset } from "@changesets/types";
import writeChangeset from "@changesets/write";
import { writeChangeset } from "@changesets/write";
import { createFixture } from "fs-fixture";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { Git } from "./git.ts";
import { setupOctokit } from "./octokit.ts";
import { GitHub } from "./github.ts";
import { runVersion } from "./run.ts";
vi.mock("@actions/github", () => ({
@@ -21,8 +20,7 @@ vi.mock("@actions/github", () => ({
graphql: mockedGraphql,
}),
}));
vi.mock("./git.ts");
vi.mock("@changesets/ghcommit/git");
vi.mock("@changesets/ghcommit");
let mockedGithubMethods = {
pulls: {
@@ -58,6 +56,7 @@ function createSimpleProjectFixture() {
private: true,
workspaces: ["packages/*"],
}),
"package-lock.json": "",
});
}
@@ -84,6 +83,7 @@ function createIgnoredPackageFixture() {
private: true,
workspaces: ["packages/*"],
}),
"package-lock.json": "",
});
}
@@ -91,6 +91,13 @@ const writeChangesets = (changesets: Changeset[], cwd: string) => {
return Promise.all(changesets.map((commit) => writeChangeset(commit, cwd)));
};
const createGithub = (cwd: string) =>
new GitHub({
cwd,
githubToken: "@@GITHUB_TOKEN",
commitMode: "github-api",
});
beforeEach(() => {
vi.clearAllMocks();
});
@@ -126,9 +133,7 @@ describe("version", () => {
);
await runVersion({
octokit: setupOctokit("@@GITHUB_TOKEN"),
githubToken: "@@GITHUB_TOKEN",
git: new Git({ cwd }),
github: createGithub(cwd),
cwd,
});
@@ -161,9 +166,7 @@ describe("version", () => {
);
await runVersion({
octokit: setupOctokit("@@GITHUB_TOKEN"),
githubToken: "@@GITHUB_TOKEN",
git: new Git({ cwd }),
github: createGithub(cwd),
cwd,
prDraft: "create",
});
@@ -197,9 +200,7 @@ describe("version", () => {
);
await runVersion({
octokit: setupOctokit("@@GITHUB_TOKEN"),
githubToken: "@@GITHUB_TOKEN",
git: new Git({ cwd }),
github: createGithub(cwd),
cwd,
});
@@ -232,9 +233,7 @@ describe("version", () => {
);
await runVersion({
octokit: setupOctokit("@@GITHUB_TOKEN"),
githubToken: "@@GITHUB_TOKEN",
git: new Git({ cwd }),
github: createGithub(cwd),
cwd,
});
@@ -287,9 +286,7 @@ fluminis divesque vulnere aquis parce lapsis rabie si visa fulmineis.
);
await runVersion({
octokit: setupOctokit("@@GITHUB_TOKEN"),
githubToken: "@@GITHUB_TOKEN",
git: new Git({ cwd }),
github: createGithub(cwd),
cwd,
prBodyMaxCharacters: 1000,
});
@@ -346,9 +343,7 @@ fluminis divesque vulnere aquis parce lapsis rabie si visa fulmineis.
);
await runVersion({
octokit: setupOctokit("@@GITHUB_TOKEN"),
githubToken: "@@GITHUB_TOKEN",
git: new Git({ cwd }),
github: createGithub(cwd),
cwd,
prBodyMaxCharacters: 500,
});
@@ -383,9 +378,7 @@ fluminis divesque vulnere aquis parce lapsis rabie si visa fulmineis.
);
await runVersion({
octokit: setupOctokit("@@GITHUB_TOKEN"),
githubToken: "@@GITHUB_TOKEN",
git: new Git({ cwd }),
github: createGithub(cwd),
cwd,
prDraft: "create",
});
@@ -417,9 +410,7 @@ fluminis divesque vulnere aquis parce lapsis rabie si visa fulmineis.
);
await runVersion({
octokit: setupOctokit("@@GITHUB_TOKEN"),
githubToken: "@@GITHUB_TOKEN",
git: new Git({ cwd }),
github: createGithub(cwd),
cwd,
prDraft: "always",
});
+117 -71
View File
@@ -1,4 +1,6 @@
import { randomUUID } from "node:crypto";
import fs from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import * as core from "@actions/core";
import {
@@ -7,10 +9,10 @@ import {
type ExecOptions,
type ExecOutput,
} from "@actions/exec";
import * as github from "@actions/github";
import { context } from "@actions/github";
import type { PreState } from "@changesets/types";
import { type Package, getPackages } from "@manypkg/get-packages";
import { Git } from "./git.ts";
import type { GitHub } from "./github.ts";
import type { Octokit } from "./octokit.ts";
import readChangesetState from "./readChangesetState.ts";
import {
@@ -57,21 +59,25 @@ const createRelease = async (
tag_name: tagName,
body: changelogEntry.content,
prerelease: pkg.packageJson.version.includes("-"),
...github.context.repo,
...context.repo,
});
};
type PublishOptions = {
script?: string;
fromPackDir?: string;
githubToken: string;
octokit: Octokit;
createGithubReleases: boolean;
git: Git;
pushGitTags: boolean;
github: GitHub;
cwd: string;
};
type PublishedPackage = { name: string; version: string };
type ChangesetsOutputEvent = {
type: "git-tag";
tag: string;
packageName: string;
};
type PublishResult =
| {
@@ -84,20 +90,90 @@ type PublishResult =
exitCode: number;
};
function isObject(value: unknown) {
return typeof value === "object" && value !== null;
}
function isChangesetsOutputEvent(
value: unknown,
): value is ChangesetsOutputEvent {
return (
isObject(value) &&
"type" in value &&
value.type === "git-tag" &&
"tag" in value &&
typeof value.tag === "string" &&
"packageName" in value &&
typeof value.packageName === "string"
);
}
async function readChangesetsOutput(outputPath: string) {
let rawOutput: string;
try {
rawOutput = await fs.readFile(outputPath, "utf8");
} catch (err) {
throw new Error(`Failed to read changesets output at ${outputPath}`, {
cause: err,
});
}
const events: ChangesetsOutputEvent[] = [];
let lineStart = 0;
while (lineStart <= rawOutput.length) {
let lineEnd = rawOutput.indexOf("\n", lineStart);
if (lineEnd === -1) {
lineEnd = rawOutput.length;
}
const line = rawOutput.slice(lineStart, lineEnd);
lineStart = lineEnd + 1;
if (/^\s*$/.test(line)) {
continue;
}
let event: unknown;
try {
event = JSON.parse(line);
} catch (err) {
throw new Error(`Failed to parse changesets output event: ${line}`, {
cause: err,
});
}
if (!isChangesetsOutputEvent(event)) {
continue;
}
events.push(event);
}
return events;
}
export async function runPublish({
script,
fromPackDir,
githubToken,
git,
octokit,
github,
createGithubReleases,
pushGitTags,
cwd,
}: PublishOptions): Promise<PublishResult> {
const { octokit } = github;
let changesetPublishOutput: ExecOutput;
const outputFile = path.join(
process.env.RUNNER_TEMP ?? (await fs.realpath(os.tmpdir())),
`changesets-output-${randomUUID()}.ndjson`,
);
const execOptions: ExecOptions = {
cwd,
ignoreReturnCode: true,
env: { ...process.env, GITHUB_TOKEN: githubToken },
env: {
...process.env,
GITHUB_TOKEN: github.getToken(),
CHANGESETS_OUTPUT: outputFile,
},
};
if (script) {
@@ -118,66 +194,43 @@ export async function runPublish({
}
let { packages, tool } = await getPackages(cwd);
let releasedPackages: Package[] = [];
if (tool !== "root") {
let newTagRegex = /New tag:\s+(@[^/]+\/[^@]+|[^/]+)@([^\s]+)/;
let packagesByName = new Map(packages.map((x) => [x.packageJson.name, x]));
for (let line of changesetPublishOutput.stdout.split("\n")) {
let match = line.match(newTagRegex);
if (match === null) {
continue;
}
let pkgName = match[1];
let pkg = packagesByName.get(pkgName);
let output = await readChangesetsOutput(outputFile);
let releases = output.map((event) => {
let pkg = packagesByName.get(event.packageName);
if (pkg === undefined) {
throw new Error(
`Package "${pkgName}" not found.` +
`Package "${event.packageName}" not found.` +
"This is probably a bug in the action, please open an issue",
);
}
releasedPackages.push(pkg);
}
return { pkg, tag: event.tag };
});
if (createGithubReleases) {
await Promise.all(
releasedPackages.map(async (pkg) => {
const tagName = `${pkg.packageJson.name}@${pkg.packageJson.version}`;
await git.pushTag(tagName);
await createRelease(octokit, { pkg, tagName });
}),
);
}
} else {
if (packages.length === 0) {
if (tool.type === "root" && packages.length === 0) {
throw new Error(
`No package found.` +
"This is probably a bug in the action, please open an issue",
);
}
let pkg = packages[0];
let newTagRegex = /New tag:/;
for (let line of changesetPublishOutput.stdout.split("\n")) {
let match = line.match(newTagRegex);
if (match) {
releasedPackages.push(pkg);
if (createGithubReleases || pushGitTags) {
await Promise.all(
releases.map(async ({ pkg, tag }) => {
if (pushGitTags) {
await github.pushTag(tag);
}
if (createGithubReleases) {
const tagName = `v${pkg.packageJson.version}`;
await git.pushTag(tagName);
await createRelease(octokit, { pkg, tagName });
}
break;
}
await createRelease(octokit, { pkg, tagName: tag });
}
}),
);
}
if (releasedPackages.length) {
if (releases.length) {
return {
published: true,
publishedPackages: releasedPackages.map((pkg) => ({
publishedPackages: releases.map(({ pkg }) => ({
name: pkg.packageJson.name,
version: pkg.packageJson.version,
})),
@@ -259,9 +312,7 @@ export async function getVersionPrBody({
type VersionOptions = {
script?: string;
githubToken: string;
git: Git;
octokit: Octokit;
github: GitHub;
cwd?: string;
prTitle?: string;
commitMessage?: string;
@@ -277,26 +328,25 @@ type RunVersionResult = {
export async function runVersion({
script,
githubToken,
git,
octokit,
github,
cwd = process.cwd(),
prTitle = "Version Packages",
commitMessage = "Version Packages",
hasPublishScript = false,
prBodyMaxCharacters = MAX_CHARACTERS_PER_MESSAGE,
branch = github.context.ref.replace("refs/heads/", ""),
branch = context.ref.replace("refs/heads/", ""),
prDraft,
}: VersionOptions): Promise<RunVersionResult> {
const { octokit } = github;
let versionBranch = `changeset-release/${branch}`;
let { preState } = await readChangesetState(cwd);
await git.prepareBranch(versionBranch);
await github.prepareBranch(versionBranch);
let versionsByDirectory = await getVersionsByDirectory(cwd);
const env = { ...process.env, GITHUB_TOKEN: githubToken };
const env = { ...process.env, GITHUB_TOKEN: github.getToken() };
if (script) {
await exec(script, undefined, { cwd, env });
@@ -327,17 +377,10 @@ export async function runVersion({
!!preState ? ` (${preState.tag})` : ""
}`;
/**
* Fetch any existing pull requests that are open against the branch,
* before we push any changes that may inadvertently close the existing PRs.
*
* (`@changesets/ghcommit` has to reset the branch to the same commit as the base,
* which GitHub will then react to by closing the PRs)
*/
const existingPullRequests = await octokit.rest.pulls.list({
...github.context.repo,
...context.repo,
state: "open",
head: `${github.context.repo.owner}:${versionBranch}`,
head: `${context.repo.owner}:${versionBranch}`,
base: branch,
});
core.info(
@@ -348,7 +391,10 @@ export async function runVersion({
)}`,
);
await git.pushChanges({ branch: versionBranch, message: finalCommitMessage });
await github.pushChanges({
branch: versionBranch,
message: finalCommitMessage,
});
const changedPackagesInfo = (await changedPackagesInfoPromises)
.filter((x) => x)
@@ -370,7 +416,7 @@ export async function runVersion({
title: finalPrTitle,
body: prBody,
draft: prDraft !== undefined,
...github.context.repo,
...context.repo,
});
return {
+3 -1
View File
@@ -64,7 +64,9 @@ async function getMode(): Promise<ModeResult> {
const cwd = process.cwd();
const publishPlanPath = path.join(
process.env.RUNNER_TEMP ?? (await fs.realpath(os.tmpdir())),
`changeset-publish-plan-${Date.now()}.json`,
`changeset-publish-plan-${Date.now()}`,
// we need a stable filename here (in a unique dirname) so the artifact download can find this cleanly
"publish-plan.json",
);
await execChangesetsCli(["publish-plan", "--output", publishPlanPath], {
cwd,
+31
View File
@@ -2,6 +2,7 @@ import fs from "node:fs/promises";
import { createRequire } from "node:module";
import path from "node:path";
import artifact from "@actions/artifact";
import * as core from "@actions/core";
import {
exec,
getExecOutput,
@@ -123,6 +124,36 @@ export function fileExists(filePath: string) {
);
}
export function getOptionalInput(name: string) {
// normalize empty string default return value of `core.getInput` to undefined
return core.getInput(name) || undefined;
}
export function getRequiredInput(name: string) {
// it's just a small utility wrapper, mainly introduced for usage parity with our custom `getOptionalInput`
// note: `core.getBooleanInput` gets used directly as it already normalizes the return value nicely
return core.getInput(name, { required: true });
}
export function throwOnRenamedInputs(renames: Record<string, string>) {
const references: Record<string, string> = {};
for (const [oldInput, newInput] of Object.entries(renames)) {
if (core.getInput(oldInput)) {
references[oldInput] = newInput;
}
}
if (Object.keys(references).length > 0) {
const list = Object.entries(references)
.map(([oldInput, newInput]) => `- "${oldInput}" -> "${newInput}"`)
.join("\n");
throw new Error(
`The following inputs have been renamed:\n${list}\nPlease update your workflow file.`,
);
}
}
function resolveChangesetsCli(cwd: string) {
return require.resolve("@changesets/cli/bin.js", {
paths: [cwd],
+17 -16
View File
@@ -1,7 +1,7 @@
import * as core from "@actions/core";
import { Git } from "../git.ts";
import { setupOctokit } from "../octokit.ts";
import { GitHub } from "../github.ts";
import { runVersion } from "../run.ts";
import { getOptionalInput, getRequiredInput } from "../utils.ts";
try {
await main();
@@ -10,39 +10,40 @@ try {
}
async function main() {
const githubToken = core.getInput("github-token", { required: true });
const script = core.getInput("script");
const commitMessage = core.getInput("commit-message", { required: true });
const prTitle = core.getInput("pr-title", { required: true });
const prDraft = core.getInput("pr-draft") || undefined;
const prBaseBranch = core.getInput("pr-base-branch");
const commitMode = core.getInput("commit-mode") || "git-cli";
const githubToken = getRequiredInput("github-token");
const script = getOptionalInput("script");
const commitMessage = getRequiredInput("commit-message");
const prTitle = getRequiredInput("pr-title");
const prDraft = getOptionalInput("pr-draft");
const prBaseBranch = getOptionalInput("pr-base-branch");
const commitMode = getOptionalInput("commit-mode") ?? "git-cli";
const setupGitUser = core.getBooleanInput("setup-git-user");
// Validations
if (prDraft !== undefined && prDraft !== "always" && prDraft !== "create") {
throw new Error(`Invalid pr-draft input: ${prDraft}`);
}
if (commitMode !== "git-cli" && commitMode !== "github-api") {
throw new Error(`Invalid commit-mode input: ${commitMode}`);
}
// If the user needs to change the cwd, set `working-directory` in the step instead
const cwd = process.cwd();
const octokit = setupOctokit(githubToken);
const git = new Git({
octokit: commitMode === "github-api" ? octokit : undefined,
const github = new GitHub({
cwd,
githubToken,
commitMode,
});
if (setupGitUser) {
core.info("setting git user");
await git.setupUser();
await github.setupUser();
}
const { pullRequestNumber } = await runVersion({
script,
githubToken,
git,
octokit,
github,
cwd,
prTitle,
commitMessage,
+4 -2
View File
@@ -9,7 +9,7 @@ inputs:
required: false
default: ${{ github.token }}
script:
description: "The command to use to publish packages"
description: "The command to use to version packages"
required: false
commit-message:
description: "The commit message. Default to `Version Packages`"
@@ -37,7 +37,9 @@ inputs:
description: Sets up the git user for commits as `"github-actions[bot]"`. Default to `true`
required: false
default: true
outputs: {}
outputs:
pr-number:
description: The pull request number that was created or updated
branding:
icon: package
color: blue