mirror of
https://github.com/changesets/action
synced 2026-10-26 16:39:56 +08:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c47fa68bd4 |
@@ -1,5 +0,0 @@
|
||||
---
|
||||
"@changesets/action": patch
|
||||
---
|
||||
|
||||
Validate that projects use Changesets CLI v3 and direct Changesets CLI v2 users to `changesets/action@v1`.
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
"@changesets/action": patch
|
||||
---
|
||||
|
||||
Allow custom publish scripts to complete without a Changesets output file, warning that GitHub releases and git tags cannot be created when that file is missing.
|
||||
@@ -1,7 +0,0 @@
|
||||
---
|
||||
"@changesets/action": minor
|
||||
---
|
||||
|
||||
Add staged publishing support to the publish action and a GitHub release action
|
||||
that validates the staged handoff, verifies approved packages, and creates tags
|
||||
and releases idempotently.
|
||||
@@ -14,23 +14,20 @@ There are also sub-actions hosted in this repository. Check out their respective
|
||||
|
||||
### Inputs
|
||||
|
||||
- publish-script - The command to use to build and publish packages
|
||||
- version-script - The command to update version, edit CHANGELOG, read and delete changesets. Default to `changeset version` if not provided
|
||||
- commit-message - The commit message to use. Default to `Version Packages`
|
||||
- pr-title - The pull request title. Default to `Version Packages`
|
||||
- setup-git-user - Sets up the git user for commits as `"github-actions[bot]"`. Default to `true`
|
||||
- create-github-releases - A boolean value to indicate whether to create Github releases after `publish` or not. Default to `true`
|
||||
- push-git-tags - A boolean value to indicate whether to create git tags after `publish` or not. Default to `true`
|
||||
- commit-mode - Specifies 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"`, all commits and tags are GPG-signed and attributed to the user or app who owns the `GITHUB_TOKEN`. Default to `git-cli`
|
||||
- publish - The command to use to build and publish packages
|
||||
- version - The command to update version, edit CHANGELOG, read and delete changesets. Default to `changeset version` if not provided
|
||||
- commit - The commit message to use. Default to `Version Packages`
|
||||
- title - The pull request title. Default to `Version Packages`
|
||||
- setupGitUser - Sets up the git user for commits as `"github-actions[bot]"`. Default to `true`
|
||||
- createGithubReleases - A boolean value to indicate whether to create Github releases after `publish` or not. Default to `true`
|
||||
- commitMode - Specifies 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"`, all commits and tags are GPG-signed and attributed to the user or app who owns the `GITHUB_TOKEN`. Default to `git-cli`.
|
||||
- cwd - Changes node's `process.cwd()` if the project is not located on the root. Default to `process.cwd()`
|
||||
- pr-draft - 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. By default, version PRs are not forced into draft mode
|
||||
- github-token - Passes a custom GitHub token
|
||||
- prDraft - 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. By default, version PRs are not forced into draft mode.
|
||||
|
||||
### Outputs
|
||||
|
||||
- published - A boolean value to indicate whether a publishing has happened or not
|
||||
- published-packages - 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"}]`
|
||||
- staged-release-artifact-id - The exact artifact id for staged packages emitted by a configured or custom publish command
|
||||
- publishedPackages - 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"}]`
|
||||
|
||||
### Example workflow
|
||||
|
||||
|
||||
@@ -56,8 +56,6 @@ outputs:
|
||||
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"}]`
|
||||
staged-release-artifact-id:
|
||||
description: Artifact id for a staged release handoff emitted by the publish script
|
||||
has-changesets:
|
||||
description: A boolean about whether there were changesets. Useful if you want to create your own publishing functionality.
|
||||
pr-number:
|
||||
|
||||
Vendored
+12
File diff suppressed because one or more lines are too long
Vendored
+2
@@ -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{};
|
||||
+143
File diff suppressed because one or more lines are too long
Vendored
+1
@@ -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{};
|
||||
Vendored
+1
@@ -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{};
|
||||
Vendored
+38
File diff suppressed because one or more lines are too long
Vendored
+1
@@ -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{};
|
||||
Vendored
+1
@@ -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};
|
||||
Vendored
+98
@@ -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};
|
||||
Vendored
+1
@@ -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{};
|
||||
Vendored
+82
File diff suppressed because one or more lines are too long
Vendored
+1
@@ -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{};
|
||||
@@ -1,13 +0,0 @@
|
||||
# changesets/action/github-release
|
||||
|
||||
Finalizes packages produced by staged publishing. Pass the exact
|
||||
`staged-release-artifact-id` output from `changesets/action/publish`.
|
||||
|
||||
By default the action waits up to two minutes for every approved package
|
||||
version to become visible before creating any Git tag or GitHub Release.
|
||||
Private registries therefore need read authentication configured before this
|
||||
step. Set `verify-published: false` to skip that check.
|
||||
|
||||
The handoff is bound to the repository, workflow run, and commit. Tags and
|
||||
releases are created idempotently; a tag that already points at another commit
|
||||
is rejected.
|
||||
@@ -1,23 +0,0 @@
|
||||
name: Changesets - GitHub Release
|
||||
description: Create Git tags and GitHub Releases after approving a staged publish
|
||||
runs:
|
||||
using: node24
|
||||
main: ../dist/github-release.js
|
||||
inputs:
|
||||
github-token:
|
||||
description: "The GitHub token to use for authentication. Defaults to the GitHub-provided token."
|
||||
required: false
|
||||
default: ${{ github.token }}
|
||||
staged-release-artifact-id:
|
||||
description: "The exact artifact id emitted by the publish action"
|
||||
required: true
|
||||
verify-published:
|
||||
description: "Verify that every approved package is visible in its configured registry before creating tags and releases"
|
||||
required: false
|
||||
default: true
|
||||
outputs:
|
||||
released-packages:
|
||||
description: "A JSON array of packages finalized by this action"
|
||||
branding:
|
||||
icon: package
|
||||
color: blue
|
||||
+1
-22
@@ -1,24 +1,3 @@
|
||||
# changesets/action/publish
|
||||
|
||||
Publishes packages with Changesets.
|
||||
|
||||
Set the optional `stage` input to `true` or `false` to override
|
||||
`stagedPublishing` from the Changesets config. The input is tri-state: omitting
|
||||
it leaves the config in control. An explicit `stage` cannot be combined with a
|
||||
custom `script`; configure the script itself instead.
|
||||
|
||||
When packages are staged, the action uploads a 30-day handoff and returns its
|
||||
exact id as `staged-release-artifact-id`. It also prints a topologically
|
||||
ordered approval command:
|
||||
|
||||
```sh
|
||||
changeset stage approve <id...>
|
||||
```
|
||||
|
||||
That command is only a convenience and uses the default registry. For custom
|
||||
or multiple registries, split the IDs into correctly scoped commands and pass
|
||||
`--registry` to each.
|
||||
|
||||
After approval, pass the artifact id to
|
||||
`changesets/action/github-release` to verify publication and create Git tags
|
||||
and GitHub Releases.
|
||||
TODO
|
||||
|
||||
@@ -11,12 +11,6 @@ inputs:
|
||||
script:
|
||||
description: "The command to use to publish packages"
|
||||
required: false
|
||||
stage:
|
||||
description: >
|
||||
Whether to use staged publishing. Omit to use the Changesets config,
|
||||
set to true for --stage, or false for --no-stage. Cannot be combined
|
||||
with a custom script.
|
||||
required: false
|
||||
pack-dir-artifact-id:
|
||||
description: "Artifact id for packed publish output generated by the pack subaction"
|
||||
required: false
|
||||
@@ -36,8 +30,6 @@ outputs:
|
||||
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"}]`
|
||||
staged-release-artifact-id:
|
||||
description: "Artifact id for the staged release handoff"
|
||||
branding:
|
||||
icon: package
|
||||
color: blue
|
||||
|
||||
@@ -9,7 +9,6 @@ export default defineConfig({
|
||||
"select-mode": "src/select-mode/index.ts",
|
||||
version: "src/version/index.ts",
|
||||
publish: "src/publish/index.ts",
|
||||
"github-release": "src/github-release/index.ts",
|
||||
},
|
||||
output: {
|
||||
dir: "dist",
|
||||
|
||||
@@ -1,46 +0,0 @@
|
||||
import * as core from "@actions/core";
|
||||
import { GitHub } from "../github.ts";
|
||||
import {
|
||||
downloadAndValidateStagedRelease,
|
||||
finalizeStagedRelease,
|
||||
} from "../staged-release.ts";
|
||||
import { getOptionalBooleanInput, getRequiredInput } from "../utils.ts";
|
||||
|
||||
try {
|
||||
await main();
|
||||
} catch (error) {
|
||||
core.setFailed((error as Error).message);
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const cwd = process.cwd();
|
||||
const github = new GitHub({
|
||||
cwd,
|
||||
githubToken: getRequiredInput("github-token"),
|
||||
commitMode: "github-api",
|
||||
});
|
||||
const artifactId = Number(getRequiredInput("staged-release-artifact-id"));
|
||||
const verify = getOptionalBooleanInput("verify-published") ?? true;
|
||||
const { handoff, packagesByName } = await downloadAndValidateStagedRelease(
|
||||
artifactId,
|
||||
cwd,
|
||||
);
|
||||
|
||||
await finalizeStagedRelease({
|
||||
github,
|
||||
handoff,
|
||||
packagesByName,
|
||||
cwd,
|
||||
verify,
|
||||
});
|
||||
|
||||
core.setOutput(
|
||||
"released-packages",
|
||||
JSON.stringify(
|
||||
handoff.releases.map((release) => ({
|
||||
name: release.packageName,
|
||||
version: release.version,
|
||||
})),
|
||||
),
|
||||
);
|
||||
}
|
||||
+3
-14
@@ -3,20 +3,14 @@ import * as core from "@actions/core";
|
||||
import { GitHub } from "./github.ts";
|
||||
import readChangesetState from "./readChangesetState.ts";
|
||||
import { runPublish, runVersion } from "./run.ts";
|
||||
import { uploadStagedRelease } from "./staged-release.ts";
|
||||
import {
|
||||
fileExists,
|
||||
getOptionalInput,
|
||||
getRequiredInput,
|
||||
throwOnRenamedInputs,
|
||||
validateChangesetsCliVersion,
|
||||
} from "./utils.ts";
|
||||
|
||||
(async () => {
|
||||
// If the user needs to change the cwd, set `working-directory` in the step instead
|
||||
const cwd = process.cwd();
|
||||
await validateChangesetsCliVersion(cwd);
|
||||
|
||||
throwOnRenamedInputs({
|
||||
publish: "publish-script",
|
||||
version: "version-script",
|
||||
@@ -38,6 +32,9 @@ import {
|
||||
);
|
||||
}
|
||||
|
||||
// If the user needs to change the cwd, set `working-directory` in the step instead
|
||||
const cwd = process.cwd();
|
||||
|
||||
const commitMode = getOptionalInput("commit-mode") ?? "git-cli";
|
||||
const prDraft = getOptionalInput("pr-draft");
|
||||
if (commitMode !== "git-cli" && commitMode !== "github-api") {
|
||||
@@ -149,14 +146,6 @@ import {
|
||||
cwd,
|
||||
});
|
||||
|
||||
if (result.stagedPackages?.length) {
|
||||
const artifactId = await uploadStagedRelease(
|
||||
result.stagedPackages,
|
||||
result.exitCode === 0 ? "approve" : "reject",
|
||||
);
|
||||
core.setOutput("staged-release-artifact-id", String(artifactId));
|
||||
}
|
||||
|
||||
if (result.published) {
|
||||
core.setOutput("published", "true");
|
||||
core.setOutput(
|
||||
|
||||
+2
-5
@@ -7,7 +7,6 @@ import {
|
||||
downloadArtifact,
|
||||
execChangesetsCli,
|
||||
getOptionalInput,
|
||||
validateChangesetsCliVersion,
|
||||
} from "../utils.ts";
|
||||
|
||||
try {
|
||||
@@ -17,12 +16,10 @@ try {
|
||||
}
|
||||
|
||||
async function main() {
|
||||
// If the user needs to change the cwd, set `working-directory` in the step instead
|
||||
const cwd = process.cwd();
|
||||
await validateChangesetsCliVersion(cwd);
|
||||
|
||||
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();
|
||||
const tmpDir = process.env.RUNNER_TEMP ?? (await fs.realpath(os.tmpdir()));
|
||||
const outDir = path.join(tmpDir, `changeset-pack-${Date.now()}`);
|
||||
|
||||
|
||||
+3
-20
@@ -3,15 +3,11 @@ import os from "node:os";
|
||||
import * as core from "@actions/core";
|
||||
import { GitHub } from "../github.ts";
|
||||
import { runPublish } from "../run.ts";
|
||||
import { uploadStagedRelease } from "../staged-release.ts";
|
||||
import {
|
||||
downloadArtifact,
|
||||
getOptionalBooleanInput,
|
||||
getOptionalInput,
|
||||
getRequiredInput,
|
||||
validateChangesetsCliVersion,
|
||||
} from "../utils.ts";
|
||||
import { assertValidStageInput } from "./options.ts";
|
||||
|
||||
try {
|
||||
await main();
|
||||
@@ -20,19 +16,12 @@ try {
|
||||
}
|
||||
|
||||
async function main() {
|
||||
// If the user needs to change the cwd, set `working-directory` in the step instead
|
||||
const cwd = process.cwd();
|
||||
await validateChangesetsCliVersion(cwd);
|
||||
|
||||
const githubToken = getRequiredInput("github-token");
|
||||
const script = getOptionalInput("script");
|
||||
const stage = getOptionalBooleanInput("stage");
|
||||
const packDirArtifactId = getOptionalInput("pack-dir-artifact-id");
|
||||
const createGithubReleases = core.getBooleanInput("create-github-releases");
|
||||
const pushGitTags = core.getBooleanInput("push-git-tags");
|
||||
|
||||
assertValidStageInput(stage, script);
|
||||
|
||||
if (createGithubReleases && !pushGitTags) {
|
||||
throw new Error(
|
||||
"The input 'create-github-releases' is set to true, but 'push-git-tags' is set to false. " +
|
||||
@@ -41,6 +30,9 @@ async function main() {
|
||||
);
|
||||
}
|
||||
|
||||
// If the user needs to change the cwd, set `working-directory` in the step instead
|
||||
const cwd = process.cwd();
|
||||
|
||||
// NOTE: Always use API mode here as publish does not need a commit-mode.
|
||||
const github = new GitHub({ cwd, githubToken, commitMode: "github-api" });
|
||||
|
||||
@@ -54,7 +46,6 @@ async function main() {
|
||||
|
||||
const result = await runPublish({
|
||||
script,
|
||||
stage,
|
||||
github,
|
||||
createGithubReleases,
|
||||
pushGitTags,
|
||||
@@ -62,14 +53,6 @@ async function main() {
|
||||
fromPackDir,
|
||||
});
|
||||
|
||||
if (result.stagedPackages?.length) {
|
||||
const artifactId = await uploadStagedRelease(
|
||||
result.stagedPackages,
|
||||
result.exitCode === 0 ? "approve" : "reject",
|
||||
);
|
||||
core.setOutput("staged-release-artifact-id", String(artifactId));
|
||||
}
|
||||
|
||||
if (result.published) {
|
||||
core.setOutput("published", "true");
|
||||
core.setOutput(
|
||||
|
||||
@@ -1,16 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { assertValidStageInput } from "./options.ts";
|
||||
|
||||
describe("publish stage input", () => {
|
||||
it("rejects an explicit stage override with a custom script", () => {
|
||||
expect(() => assertValidStageInput(false, "pnpm release")).toThrow(
|
||||
"cannot be combined with a custom 'script'",
|
||||
);
|
||||
});
|
||||
|
||||
it("allows an omitted stage input with a custom script", () => {
|
||||
expect(() =>
|
||||
assertValidStageInput(undefined, "pnpm release"),
|
||||
).not.toThrow();
|
||||
});
|
||||
});
|
||||
@@ -1,10 +0,0 @@
|
||||
export function assertValidStageInput(
|
||||
stage: boolean | undefined,
|
||||
script: string | undefined,
|
||||
) {
|
||||
if (stage !== undefined && script) {
|
||||
throw new Error(
|
||||
"The 'stage' input cannot be combined with a custom 'script'. Configure staged publishing inside the script instead.",
|
||||
);
|
||||
}
|
||||
}
|
||||
+2
-154
@@ -1,11 +1,10 @@
|
||||
import path from "node:path";
|
||||
import * as core from "@actions/core";
|
||||
import type { Changeset } from "@changesets/types";
|
||||
import { writeChangeset } from "@changesets/write";
|
||||
import { createFixture } from "fs-fixture";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { GitHub } from "./github.ts";
|
||||
import { readChangesetsOutput, runPublish, runVersion } from "./run.ts";
|
||||
import { runVersion } from "./run.ts";
|
||||
|
||||
vi.mock("@actions/github", () => ({
|
||||
context: {
|
||||
@@ -21,8 +20,6 @@ vi.mock("@actions/github", () => ({
|
||||
graphql: mockedGraphql,
|
||||
}),
|
||||
}));
|
||||
vi.mock("@actions/core", { spy: true });
|
||||
const mockedWarning = vi.mocked(core.warning);
|
||||
vi.mock("@changesets/ghcommit");
|
||||
|
||||
let mockedGithubMethods = {
|
||||
@@ -105,155 +102,6 @@ beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllEnvs();
|
||||
});
|
||||
|
||||
describe("publish", () => {
|
||||
it("parses staged publish events in emitted order", async () => {
|
||||
await using fixture = await createFixture({
|
||||
"changesets-output.ndjson": [
|
||||
JSON.stringify({
|
||||
type: "npm-stage",
|
||||
packageName: "pkg-b",
|
||||
version: "1.0.0",
|
||||
tag: "latest",
|
||||
gitTag: "pkg-b@1.0.0",
|
||||
stageId: "stage-b",
|
||||
}),
|
||||
JSON.stringify({ type: "unknown" }),
|
||||
JSON.stringify({
|
||||
type: "npm-stage",
|
||||
packageName: "pkg-a",
|
||||
version: "1.0.0",
|
||||
tag: "latest",
|
||||
gitTag: "pkg-a@1.0.0",
|
||||
stageId: "stage-a",
|
||||
}),
|
||||
].join("\n"),
|
||||
});
|
||||
|
||||
await expect(
|
||||
readChangesetsOutput(path.join(fixture.path, "changesets-output.ndjson")),
|
||||
).resolves.toMatchObject([
|
||||
{ type: "npm-stage", stageId: "stage-b" },
|
||||
{ type: "npm-stage", stageId: "stage-a" },
|
||||
]);
|
||||
});
|
||||
|
||||
it("returns staged packages from a custom publish script", async () => {
|
||||
await using fixture = await createSimpleProjectFixture();
|
||||
const cwd = fixture.path;
|
||||
vi.stubEnv("RUNNER_TEMP", cwd);
|
||||
await fixture.writeFile(
|
||||
"write-output.cjs",
|
||||
`require("node:fs").writeFileSync(process.env.CHANGESETS_OUTPUT, JSON.stringify({
|
||||
type: "npm-stage",
|
||||
packageName: "changesets-dev-simple-project-pkg-b",
|
||||
version: "1.0.0",
|
||||
tag: "latest",
|
||||
gitTag: "changesets-dev-simple-project-pkg-b@1.0.0",
|
||||
stageId: "stage-b"
|
||||
}) + "\\n")`,
|
||||
);
|
||||
|
||||
const result = await runPublish({
|
||||
script: "node write-output.cjs",
|
||||
github: createGithub(cwd),
|
||||
createGithubReleases: false,
|
||||
pushGitTags: false,
|
||||
cwd,
|
||||
});
|
||||
|
||||
expect(result).toMatchObject({
|
||||
published: false,
|
||||
exitCode: 0,
|
||||
stagedPackages: [{ type: "npm-stage", stageId: "stage-b" }],
|
||||
});
|
||||
expect(mockedGithubMethods.repos.createRelease).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("passes an explicit stage override to the built-in CLI", async () => {
|
||||
await using fixture = await createFixture({
|
||||
"node_modules/@changesets/cli/package.json": JSON.stringify({
|
||||
name: "@changesets/cli",
|
||||
type: "module",
|
||||
}),
|
||||
"node_modules/@changesets/cli/bin.js": `
|
||||
import fs from "node:fs";
|
||||
fs.writeFileSync("args.json", JSON.stringify(process.argv.slice(2)));
|
||||
fs.writeFileSync(process.env.CHANGESETS_OUTPUT, "");
|
||||
`,
|
||||
"package.json": JSON.stringify({
|
||||
name: "simple-project",
|
||||
version: "1.0.0",
|
||||
}),
|
||||
"package-lock.json": "",
|
||||
});
|
||||
const cwd = fixture.path;
|
||||
vi.stubEnv("RUNNER_TEMP", cwd);
|
||||
|
||||
await runPublish({
|
||||
stage: false,
|
||||
github: createGithub(cwd),
|
||||
createGithubReleases: false,
|
||||
pushGitTags: false,
|
||||
cwd,
|
||||
});
|
||||
|
||||
await expect(
|
||||
fixture.readFile("args.json", "utf8").then(JSON.parse),
|
||||
).resolves.toEqual(["publish", "--no-stage"]);
|
||||
});
|
||||
|
||||
it("warns when a custom publish script does not create the output file", async () => {
|
||||
await using fixture = await createSimpleProjectFixture();
|
||||
const cwd = fixture.path;
|
||||
vi.stubEnv("RUNNER_TEMP", cwd);
|
||||
|
||||
const result = await runPublish({
|
||||
script: 'node -e "void 0"',
|
||||
github: createGithub(cwd),
|
||||
createGithubReleases: true,
|
||||
pushGitTags: true,
|
||||
cwd,
|
||||
});
|
||||
|
||||
expect(result).toEqual({ published: false, exitCode: 0 });
|
||||
expect(mockedWarning).toHaveBeenCalledWith(
|
||||
expect.stringContaining(
|
||||
"GitHub releases and git tags cannot be created without this output",
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it("throws when the built-in publish command does not create the output file", async () => {
|
||||
await using fixture = await createFixture({
|
||||
"node_modules/@changesets/cli/package.json": JSON.stringify({
|
||||
name: "@changesets/cli",
|
||||
type: "module",
|
||||
}),
|
||||
"node_modules/@changesets/cli/bin.js": "",
|
||||
"package.json": JSON.stringify({
|
||||
name: "simple-project",
|
||||
version: "1.0.0",
|
||||
}),
|
||||
"package-lock.json": "",
|
||||
});
|
||||
const cwd = fixture.path;
|
||||
vi.stubEnv("RUNNER_TEMP", cwd);
|
||||
|
||||
await expect(
|
||||
runPublish({
|
||||
github: createGithub(cwd),
|
||||
createGithubReleases: true,
|
||||
pushGitTags: true,
|
||||
cwd,
|
||||
}),
|
||||
).rejects.toThrow("Failed to read changesets output at");
|
||||
});
|
||||
});
|
||||
|
||||
describe("version", () => {
|
||||
it("creates simple PR", async () => {
|
||||
await using fixture = await createSimpleProjectFixture();
|
||||
|
||||
+26
-93
@@ -31,7 +31,7 @@ import {
|
||||
// To avoid that, we ensure to cap the message to 60k chars.
|
||||
const MAX_CHARACTERS_PER_MESSAGE = 60000;
|
||||
|
||||
export const createRelease = async (
|
||||
const createRelease = async (
|
||||
octokit: Octokit,
|
||||
{ pkg, tagName }: { pkg: Package; tagName: string },
|
||||
) => {
|
||||
@@ -66,7 +66,6 @@ export const createRelease = async (
|
||||
type PublishOptions = {
|
||||
script?: string;
|
||||
fromPackDir?: string;
|
||||
stage?: boolean;
|
||||
createGithubReleases: boolean;
|
||||
pushGitTags: boolean;
|
||||
github: GitHub;
|
||||
@@ -74,38 +73,20 @@ type PublishOptions = {
|
||||
};
|
||||
|
||||
type PublishedPackage = { name: string; version: string };
|
||||
export type ChangesetsOutputEvent =
|
||||
| {
|
||||
type: "git-tag";
|
||||
tag: string;
|
||||
packageName: string;
|
||||
}
|
||||
| {
|
||||
type: "npm-stage";
|
||||
packageName: string;
|
||||
version: string;
|
||||
tag: string;
|
||||
gitTag: string;
|
||||
stageId: string;
|
||||
};
|
||||
|
||||
export type NpmStageEvent = Extract<
|
||||
ChangesetsOutputEvent,
|
||||
{ type: "npm-stage" }
|
||||
>;
|
||||
|
||||
class ChangesetsOutputReadError extends Error {}
|
||||
type ChangesetsOutputEvent = {
|
||||
type: "git-tag";
|
||||
tag: string;
|
||||
packageName: string;
|
||||
};
|
||||
|
||||
type PublishResult =
|
||||
| {
|
||||
published: true;
|
||||
publishedPackages: PublishedPackage[];
|
||||
stagedPackages?: NpmStageEvent[];
|
||||
exitCode: number;
|
||||
}
|
||||
| {
|
||||
published: false;
|
||||
stagedPackages?: NpmStageEvent[];
|
||||
exitCode: number;
|
||||
};
|
||||
|
||||
@@ -116,40 +97,25 @@ function isObject(value: unknown) {
|
||||
function isChangesetsOutputEvent(
|
||||
value: unknown,
|
||||
): value is ChangesetsOutputEvent {
|
||||
if (!isObject(value) || !("type" in value)) return false;
|
||||
if (
|
||||
return (
|
||||
isObject(value) &&
|
||||
"type" in value &&
|
||||
value.type === "git-tag" &&
|
||||
"tag" in value &&
|
||||
typeof value.tag === "string" &&
|
||||
"packageName" in value &&
|
||||
typeof value.packageName === "string"
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
return (
|
||||
value.type === "npm-stage" &&
|
||||
"packageName" in value &&
|
||||
typeof value.packageName === "string" &&
|
||||
"version" in value &&
|
||||
typeof value.version === "string" &&
|
||||
"tag" in value &&
|
||||
typeof value.tag === "string" &&
|
||||
"gitTag" in value &&
|
||||
typeof value.gitTag === "string" &&
|
||||
"stageId" in value &&
|
||||
typeof value.stageId === "string"
|
||||
);
|
||||
}
|
||||
|
||||
export async function readChangesetsOutput(outputPath: string) {
|
||||
async function readChangesetsOutput(outputPath: string) {
|
||||
let rawOutput: string;
|
||||
try {
|
||||
rawOutput = await fs.readFile(outputPath, "utf8");
|
||||
} catch (err) {
|
||||
throw new ChangesetsOutputReadError(
|
||||
`Failed to read changesets output at ${outputPath}`,
|
||||
{ cause: err },
|
||||
);
|
||||
throw new Error(`Failed to read changesets output at ${outputPath}`, {
|
||||
cause: err,
|
||||
});
|
||||
}
|
||||
|
||||
const events: ChangesetsOutputEvent[] = [];
|
||||
@@ -189,7 +155,6 @@ export async function readChangesetsOutput(outputPath: string) {
|
||||
export async function runPublish({
|
||||
script,
|
||||
fromPackDir,
|
||||
stage,
|
||||
github,
|
||||
createGithubReleases,
|
||||
pushGitTags,
|
||||
@@ -219,9 +184,6 @@ export async function runPublish({
|
||||
);
|
||||
} else {
|
||||
const args = ["publish"];
|
||||
if (stage !== undefined) {
|
||||
args.push(stage ? "--stage" : "--no-stage");
|
||||
}
|
||||
if (fromPackDir) {
|
||||
args.push("--from-pack-dir", fromPackDir);
|
||||
}
|
||||
@@ -231,43 +193,19 @@ export async function runPublish({
|
||||
);
|
||||
}
|
||||
|
||||
let { packages, rootPackage, tool } = await getPackages(cwd);
|
||||
let packagesByName = new Map(
|
||||
[...packages, ...(rootPackage ? [rootPackage] : [])].map((x) => [
|
||||
x.packageJson.name,
|
||||
x,
|
||||
]),
|
||||
);
|
||||
let output: ChangesetsOutputEvent[];
|
||||
try {
|
||||
output = await readChangesetsOutput(outputFile);
|
||||
} catch (err) {
|
||||
if (!script || !(err instanceof ChangesetsOutputReadError)) {
|
||||
throw err;
|
||||
let { packages, tool } = await getPackages(cwd);
|
||||
let packagesByName = new Map(packages.map((x) => [x.packageJson.name, x]));
|
||||
let output = await readChangesetsOutput(outputFile);
|
||||
let releases = output.map((event) => {
|
||||
let pkg = packagesByName.get(event.packageName);
|
||||
if (pkg === undefined) {
|
||||
throw new Error(
|
||||
`Package "${event.packageName}" not found.` +
|
||||
"This is probably a bug in the action, please open an issue",
|
||||
);
|
||||
}
|
||||
core.warning(
|
||||
`${err.message}. GitHub releases and git tags cannot be created without this output. Ensure the custom publish script passes CHANGESETS_OUTPUT to the Changesets CLI.`,
|
||||
);
|
||||
output = [];
|
||||
}
|
||||
const stagedPackages = output.filter(
|
||||
(event): event is NpmStageEvent => event.type === "npm-stage",
|
||||
);
|
||||
let releases = output
|
||||
.filter(
|
||||
(event): event is Extract<ChangesetsOutputEvent, { type: "git-tag" }> =>
|
||||
event.type === "git-tag",
|
||||
)
|
||||
.map((event) => {
|
||||
let pkg = packagesByName.get(event.packageName);
|
||||
if (pkg === undefined) {
|
||||
throw new Error(
|
||||
`Package "${event.packageName}" not found.` +
|
||||
"This is probably a bug in the action, please open an issue",
|
||||
);
|
||||
}
|
||||
return { pkg, tag: event.tag };
|
||||
});
|
||||
return { pkg, tag: event.tag };
|
||||
});
|
||||
|
||||
if (tool.type === "root" && packages.length === 0) {
|
||||
throw new Error(
|
||||
@@ -296,16 +234,11 @@ export async function runPublish({
|
||||
name: pkg.packageJson.name,
|
||||
version: pkg.packageJson.version,
|
||||
})),
|
||||
...(stagedPackages.length > 0 ? { stagedPackages } : {}),
|
||||
exitCode: changesetPublishOutput.exitCode,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
published: false,
|
||||
...(stagedPackages.length > 0 ? { stagedPackages } : {}),
|
||||
exitCode: changesetPublishOutput.exitCode,
|
||||
};
|
||||
return { published: false, exitCode: changesetPublishOutput.exitCode };
|
||||
}
|
||||
|
||||
type GetMessageOptions = {
|
||||
|
||||
@@ -4,7 +4,7 @@ import path from "node:path";
|
||||
import artifact from "@actions/artifact";
|
||||
import * as core from "@actions/core";
|
||||
import readChangesetState from "../readChangesetState.ts";
|
||||
import { execChangesetsCli, validateChangesetsCliVersion } from "../utils.ts";
|
||||
import { execChangesetsCli } from "../utils.ts";
|
||||
|
||||
type ModeResult =
|
||||
| {
|
||||
@@ -27,10 +27,7 @@ try {
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const cwd = process.cwd();
|
||||
await validateChangesetsCliVersion(cwd);
|
||||
|
||||
const result = await getMode(cwd);
|
||||
const result = await getMode();
|
||||
core.setOutput("mode", result.mode);
|
||||
if (result.mode === "publish") {
|
||||
const publishPlanArtifact = await artifact.uploadArtifact(
|
||||
@@ -51,8 +48,8 @@ async function main() {
|
||||
}
|
||||
}
|
||||
|
||||
async function getMode(cwd: string): Promise<ModeResult> {
|
||||
const { changesets } = await readChangesetState(cwd);
|
||||
async function getMode(): Promise<ModeResult> {
|
||||
const { changesets } = await readChangesetState();
|
||||
|
||||
if (changesets.length > 0) {
|
||||
const hasNonEmptyChangesets = changesets.some(
|
||||
@@ -64,6 +61,7 @@ async function getMode(cwd: string): Promise<ModeResult> {
|
||||
return { mode: "none" };
|
||||
}
|
||||
|
||||
const cwd = process.cwd();
|
||||
const publishPlanPath = path.join(
|
||||
process.env.RUNNER_TEMP ?? (await fs.realpath(os.tmpdir())),
|
||||
`changeset-publish-plan-${Date.now()}`,
|
||||
|
||||
@@ -1,218 +0,0 @@
|
||||
import * as path from "node:path";
|
||||
import { getExecOutput } from "@actions/exec";
|
||||
import type { Package } from "@manypkg/get-packages";
|
||||
import { createFixture } from "fs-fixture";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import type { GitHub } from "./github.ts";
|
||||
import {
|
||||
createStagedReleaseHandoff,
|
||||
finalizeStagedRelease,
|
||||
formatStageCommand,
|
||||
validateStagedReleaseHandoff,
|
||||
verifyPublished,
|
||||
type StagedReleaseEntry,
|
||||
} from "./staged-release.ts";
|
||||
|
||||
vi.mock("@actions/github", () => ({
|
||||
context: {
|
||||
repo: { owner: "changesets", repo: "action" },
|
||||
runId: 123,
|
||||
sha: "abc123",
|
||||
},
|
||||
}));
|
||||
vi.mock("@actions/exec", async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import("@actions/exec")>()),
|
||||
getExecOutput: vi.fn(),
|
||||
}));
|
||||
|
||||
const entry: StagedReleaseEntry = {
|
||||
packageName: "pkg-a",
|
||||
version: "1.0.0",
|
||||
tag: "latest",
|
||||
gitTag: "pkg-a@1.0.0",
|
||||
stageId: "1de6f3db-2ed9-4d72-b3dd-8f0e2b474a2f",
|
||||
};
|
||||
|
||||
async function createProject() {
|
||||
return createFixture({
|
||||
"package.json": JSON.stringify({
|
||||
name: "repo",
|
||||
private: true,
|
||||
workspaces: ["packages/*"],
|
||||
}),
|
||||
"package-lock.json": "",
|
||||
"packages/pkg-a/package.json": JSON.stringify({
|
||||
name: "pkg-a",
|
||||
version: "1.0.0",
|
||||
}),
|
||||
"packages/pkg-b/package.json": JSON.stringify({
|
||||
name: "pkg-b",
|
||||
version: "1.0.0",
|
||||
}),
|
||||
});
|
||||
}
|
||||
|
||||
describe("staged release handoff", () => {
|
||||
it("prints stage ids in their topological event order", () => {
|
||||
expect(
|
||||
formatStageCommand(
|
||||
[
|
||||
{ type: "npm-stage", ...entry, stageId: "stage-b" },
|
||||
{ type: "npm-stage", ...entry, stageId: "stage-a" },
|
||||
],
|
||||
"approve",
|
||||
),
|
||||
).toBe("changeset stage approve stage-b stage-a");
|
||||
});
|
||||
|
||||
it("prints rejection recovery for a partial publish failure", () => {
|
||||
expect(
|
||||
formatStageCommand(
|
||||
[{ type: "npm-stage", ...entry, stageId: "stage-a" }],
|
||||
"reject",
|
||||
),
|
||||
).toBe("changeset stage reject stage-a");
|
||||
});
|
||||
|
||||
it("validates origin, manifests, tags, and preserves order", async () => {
|
||||
await using fixture = await createProject();
|
||||
const handoff = createStagedReleaseHandoff(
|
||||
[
|
||||
{ type: "npm-stage", ...entry },
|
||||
{
|
||||
type: "npm-stage",
|
||||
...entry,
|
||||
packageName: "pkg-b",
|
||||
gitTag: "pkg-b@1.0.0",
|
||||
stageId: "2de6f3db-2ed9-4d72-b3dd-8f0e2b474a2f",
|
||||
},
|
||||
],
|
||||
{ repository: "changesets/action", runId: 123, sha: "abc123" },
|
||||
);
|
||||
const result = await validateStagedReleaseHandoff(handoff, fixture.path, {
|
||||
repository: "changesets/action",
|
||||
runId: 123,
|
||||
sha: "abc123",
|
||||
});
|
||||
expect(result.handoff.releases.map((release) => release.stageId)).toEqual([
|
||||
"1de6f3db-2ed9-4d72-b3dd-8f0e2b474a2f",
|
||||
"2de6f3db-2ed9-4d72-b3dd-8f0e2b474a2f",
|
||||
]);
|
||||
});
|
||||
|
||||
it("rejects a handoff from another workflow run", async () => {
|
||||
await using fixture = await createProject();
|
||||
const handoff = createStagedReleaseHandoff(
|
||||
[{ type: "npm-stage", ...entry }],
|
||||
{ repository: "changesets/action", runId: 122, sha: "abc123" },
|
||||
);
|
||||
|
||||
await expect(
|
||||
validateStagedReleaseHandoff(handoff, fixture.path, {
|
||||
repository: "changesets/action",
|
||||
runId: 123,
|
||||
sha: "abc123",
|
||||
}),
|
||||
).rejects.toThrow("do not match this workflow run");
|
||||
});
|
||||
|
||||
it("verifies an exact version through the configured package manager", async () => {
|
||||
await using fixture = await createProject();
|
||||
vi.mocked(getExecOutput).mockResolvedValue({
|
||||
exitCode: 0,
|
||||
stdout: JSON.stringify("1.0.0"),
|
||||
stderr: "",
|
||||
} as never);
|
||||
|
||||
await verifyPublished([entry], fixture.path, { timeoutMs: 0 });
|
||||
|
||||
expect(getExecOutput).toHaveBeenCalledWith(
|
||||
"npm",
|
||||
["view", "pkg-a@1.0.0", "version", "--json"],
|
||||
expect.objectContaining({ cwd: fixture.path }),
|
||||
);
|
||||
});
|
||||
|
||||
it("accepts existing correct tags and releases without writes", async () => {
|
||||
const getRef = vi.fn().mockResolvedValue({
|
||||
data: { object: { sha: "abc123" } },
|
||||
});
|
||||
const createRef = vi.fn();
|
||||
const getReleaseByTag = vi.fn().mockResolvedValue({ data: { id: 1 } });
|
||||
const createRelease = vi.fn();
|
||||
const github = {
|
||||
octokit: {
|
||||
rest: {
|
||||
git: { getRef, createRef },
|
||||
repos: { getReleaseByTag, createRelease },
|
||||
},
|
||||
},
|
||||
} as unknown as GitHub;
|
||||
const pkg = {
|
||||
dir: path.join("/repo", "packages/pkg-a"),
|
||||
relativeDir: "packages/pkg-a",
|
||||
packageJson: { name: "pkg-a", version: "1.0.0" },
|
||||
} satisfies Package;
|
||||
|
||||
await finalizeStagedRelease({
|
||||
github,
|
||||
handoff: {
|
||||
version: 1,
|
||||
repository: "changesets/action",
|
||||
runId: 123,
|
||||
sha: "abc123",
|
||||
releases: [entry],
|
||||
},
|
||||
packagesByName: new Map([["pkg-a", pkg]]),
|
||||
cwd: "/repo",
|
||||
verify: false,
|
||||
});
|
||||
|
||||
expect(createRef).not.toHaveBeenCalled();
|
||||
expect(createRelease).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rejects an existing tag at another commit", async () => {
|
||||
const github = {
|
||||
octokit: {
|
||||
rest: {
|
||||
git: {
|
||||
getRef: vi.fn().mockResolvedValue({
|
||||
data: { object: { sha: "wrong" } },
|
||||
}),
|
||||
createRef: vi.fn(),
|
||||
},
|
||||
repos: {
|
||||
getReleaseByTag: vi.fn(),
|
||||
createRelease: vi.fn(),
|
||||
},
|
||||
},
|
||||
},
|
||||
} as unknown as GitHub;
|
||||
|
||||
await expect(
|
||||
finalizeStagedRelease({
|
||||
github,
|
||||
handoff: {
|
||||
version: 1,
|
||||
repository: "changesets/action",
|
||||
runId: 123,
|
||||
sha: "abc123",
|
||||
releases: [entry],
|
||||
},
|
||||
packagesByName: new Map([
|
||||
[
|
||||
"pkg-a",
|
||||
{
|
||||
dir: "/repo/pkg-a",
|
||||
relativeDir: "pkg-a",
|
||||
packageJson: { name: "pkg-a", version: "1.0.0" },
|
||||
} satisfies Package,
|
||||
],
|
||||
]),
|
||||
cwd: "/repo",
|
||||
verify: false,
|
||||
}),
|
||||
).rejects.toThrow("expected abc123");
|
||||
});
|
||||
});
|
||||
@@ -1,342 +0,0 @@
|
||||
import fs from "node:fs/promises";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import artifact from "@actions/artifact";
|
||||
import * as core from "@actions/core";
|
||||
import { getExecOutput } from "@actions/exec";
|
||||
import { context } from "@actions/github";
|
||||
import { getPackages, type Package } from "@manypkg/get-packages";
|
||||
import type { GitHub } from "./github.ts";
|
||||
import { createRelease, type NpmStageEvent } from "./run.ts";
|
||||
import { downloadArtifact } from "./utils.ts";
|
||||
|
||||
export const STAGED_RELEASE_VERSION = 1;
|
||||
export const STAGED_RELEASE_FILENAME = "staged-release.json";
|
||||
const STAGE_ID_PATTERN =
|
||||
/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
||||
|
||||
export type StagedReleaseEntry = Omit<NpmStageEvent, "type">;
|
||||
|
||||
export type StagedReleaseHandoff = {
|
||||
version: typeof STAGED_RELEASE_VERSION;
|
||||
repository: string;
|
||||
runId: number;
|
||||
sha: string;
|
||||
releases: StagedReleaseEntry[];
|
||||
};
|
||||
|
||||
type HandoffIdentity = {
|
||||
repository: string;
|
||||
runId: number;
|
||||
sha: string;
|
||||
};
|
||||
|
||||
function currentIdentity(): HandoffIdentity {
|
||||
return {
|
||||
repository: `${context.repo.owner}/${context.repo.repo}`,
|
||||
runId: context.runId,
|
||||
sha: context.sha,
|
||||
};
|
||||
}
|
||||
|
||||
function isObject(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === "object" && value !== null;
|
||||
}
|
||||
|
||||
function isHttpNotFound(error: unknown) {
|
||||
return (
|
||||
isObject(error) &&
|
||||
(error.status === 404 || error.code === 404 || error.code === "404")
|
||||
);
|
||||
}
|
||||
|
||||
function isStagedReleaseEntry(value: unknown): value is StagedReleaseEntry {
|
||||
return (
|
||||
isObject(value) &&
|
||||
typeof value.packageName === "string" &&
|
||||
value.packageName.length > 0 &&
|
||||
typeof value.version === "string" &&
|
||||
value.version.length > 0 &&
|
||||
typeof value.tag === "string" &&
|
||||
value.tag.length > 0 &&
|
||||
typeof value.gitTag === "string" &&
|
||||
value.gitTag.length > 0 &&
|
||||
typeof value.stageId === "string" &&
|
||||
STAGE_ID_PATTERN.test(value.stageId)
|
||||
);
|
||||
}
|
||||
|
||||
export function createStagedReleaseHandoff(
|
||||
events: readonly NpmStageEvent[],
|
||||
identity: HandoffIdentity = currentIdentity(),
|
||||
): StagedReleaseHandoff {
|
||||
return {
|
||||
version: STAGED_RELEASE_VERSION,
|
||||
...identity,
|
||||
releases: events.map(({ type: _, ...event }) => event),
|
||||
};
|
||||
}
|
||||
|
||||
export function formatStageCommand(
|
||||
events: readonly NpmStageEvent[],
|
||||
operation: "approve" | "reject",
|
||||
) {
|
||||
return `changeset stage ${operation} ${events
|
||||
.map((event) => event.stageId)
|
||||
.join(" ")}`;
|
||||
}
|
||||
|
||||
export async function uploadStagedRelease(
|
||||
events: readonly NpmStageEvent[],
|
||||
operation: "approve" | "reject",
|
||||
): Promise<number> {
|
||||
const verb = operation === "approve" ? "Approve" : "Reject";
|
||||
core.info(`${verb} the staged packages in this order:
|
||||
${formatStageCommand(events, operation)}`);
|
||||
core.info(
|
||||
"This command uses the default registry. For custom or multiple registries, split the IDs and pass --registry to each command.",
|
||||
);
|
||||
|
||||
const tmpDir = process.env.RUNNER_TEMP ?? (await fs.realpath(os.tmpdir()));
|
||||
const outDir = path.join(tmpDir, `changeset-staged-release-${Date.now()}`);
|
||||
const handoffPath = path.join(outDir, STAGED_RELEASE_FILENAME);
|
||||
await fs.mkdir(outDir, { recursive: true });
|
||||
await fs.writeFile(
|
||||
handoffPath,
|
||||
`${JSON.stringify(createStagedReleaseHandoff(events), null, 2)}\n`,
|
||||
);
|
||||
|
||||
const result = await artifact.uploadArtifact(
|
||||
`changeset-staged-release-${context.runId}-${Date.now()}`,
|
||||
[handoffPath],
|
||||
outDir,
|
||||
{ skipArchive: true, retentionDays: 30 },
|
||||
);
|
||||
if (result.id === undefined) {
|
||||
throw new Error("Staged release artifact upload did not return an id");
|
||||
}
|
||||
|
||||
return result.id;
|
||||
}
|
||||
|
||||
function expectedGitTag(
|
||||
tool: Awaited<ReturnType<typeof getPackages>>["tool"],
|
||||
entry: StagedReleaseEntry,
|
||||
) {
|
||||
return tool.type === "root"
|
||||
? `v${entry.version}`
|
||||
: `${entry.packageName}@${entry.version}`;
|
||||
}
|
||||
|
||||
export async function validateStagedReleaseHandoff(
|
||||
value: unknown,
|
||||
cwd: string,
|
||||
identity: HandoffIdentity = currentIdentity(),
|
||||
): Promise<{
|
||||
handoff: StagedReleaseHandoff;
|
||||
packagesByName: Map<string, Package>;
|
||||
}> {
|
||||
if (
|
||||
!isObject(value) ||
|
||||
value.version !== STAGED_RELEASE_VERSION ||
|
||||
value.repository !== identity.repository ||
|
||||
value.runId !== identity.runId ||
|
||||
value.sha !== identity.sha ||
|
||||
!Array.isArray(value.releases) ||
|
||||
value.releases.length === 0 ||
|
||||
!value.releases.every(isStagedReleaseEntry)
|
||||
) {
|
||||
throw new Error(
|
||||
"Invalid staged release artifact: version, origin, or release entries do not match this workflow run",
|
||||
);
|
||||
}
|
||||
|
||||
const handoff = value as StagedReleaseHandoff;
|
||||
const uniqueFields: Array<keyof StagedReleaseEntry> = [
|
||||
"packageName",
|
||||
"gitTag",
|
||||
"stageId",
|
||||
];
|
||||
for (const field of uniqueFields) {
|
||||
const values = handoff.releases.map((entry) => entry[field]);
|
||||
if (new Set(values).size !== values.length) {
|
||||
throw new Error(
|
||||
`Invalid staged release artifact: duplicate ${field} value`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const { packages, rootPackage, tool } = await getPackages(cwd);
|
||||
const packagesByName = new Map(
|
||||
[...packages, ...(rootPackage ? [rootPackage] : [])].map((pkg) => [
|
||||
pkg.packageJson.name,
|
||||
pkg,
|
||||
]),
|
||||
);
|
||||
for (const entry of handoff.releases) {
|
||||
const pkg = packagesByName.get(entry.packageName);
|
||||
if (!pkg || pkg.packageJson.version !== entry.version) {
|
||||
throw new Error(
|
||||
`Invalid staged release artifact: ${entry.packageName}@${entry.version} does not match the checked-out manifest`,
|
||||
);
|
||||
}
|
||||
if (entry.gitTag !== expectedGitTag(tool, entry)) {
|
||||
throw new Error(
|
||||
`Invalid staged release artifact: unexpected Git tag ${entry.gitTag}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return { handoff, packagesByName };
|
||||
}
|
||||
|
||||
export async function downloadAndValidateStagedRelease(
|
||||
artifactId: number,
|
||||
cwd: string,
|
||||
) {
|
||||
const tmpDir = process.env.RUNNER_TEMP ?? (await fs.realpath(os.tmpdir()));
|
||||
const artifactDir = await downloadArtifact(
|
||||
tmpDir,
|
||||
artifactId,
|
||||
"changeset-staged-release",
|
||||
);
|
||||
const handoffPath = path.join(artifactDir, STAGED_RELEASE_FILENAME);
|
||||
let value: unknown;
|
||||
try {
|
||||
value = JSON.parse(await fs.readFile(handoffPath, "utf8"));
|
||||
} catch (error) {
|
||||
throw new Error(`Failed to read staged release artifact ${artifactId}`, {
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
return validateStagedReleaseHandoff(value, cwd);
|
||||
}
|
||||
|
||||
function outputContainsVersion(output: string, version: string) {
|
||||
const values: unknown[] = [];
|
||||
for (const line of output.split("\n")) {
|
||||
if (!line.trim()) continue;
|
||||
try {
|
||||
values.push(JSON.parse(line));
|
||||
} catch {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
const contains = (value: unknown): boolean => {
|
||||
if (value === version) return true;
|
||||
if (Array.isArray(value)) return value.some(contains);
|
||||
if (isObject(value)) return Object.values(value).some(contains);
|
||||
return false;
|
||||
};
|
||||
return values.some(contains);
|
||||
}
|
||||
|
||||
async function isPublished(
|
||||
cwd: string,
|
||||
tool: Awaited<ReturnType<typeof getPackages>>["tool"],
|
||||
entry: StagedReleaseEntry,
|
||||
) {
|
||||
const spec = `${entry.packageName}@${entry.version}`;
|
||||
const command =
|
||||
tool.type === "pnpm" ? "pnpm" : tool.type === "yarn" ? "yarn" : "npm";
|
||||
const args =
|
||||
tool.type === "yarn"
|
||||
? ["npm", "info", spec, "--fields", "version", "--json"]
|
||||
: ["view", spec, "version", "--json"];
|
||||
const result = await getExecOutput(command, args, {
|
||||
cwd,
|
||||
ignoreReturnCode: true,
|
||||
silent: true,
|
||||
env: process.env as Record<string, string>,
|
||||
});
|
||||
return (
|
||||
result.exitCode === 0 && outputContainsVersion(result.stdout, entry.version)
|
||||
);
|
||||
}
|
||||
|
||||
export async function verifyPublished(
|
||||
releases: readonly StagedReleaseEntry[],
|
||||
cwd: string,
|
||||
options: { timeoutMs?: number; intervalMs?: number } = {},
|
||||
) {
|
||||
const timeoutMs = options.timeoutMs ?? 120_000;
|
||||
const intervalMs = options.intervalMs ?? 5_000;
|
||||
const deadline = Date.now() + timeoutMs;
|
||||
const { tool } = await getPackages(cwd);
|
||||
|
||||
while (true) {
|
||||
const results = await Promise.all(
|
||||
releases.map((release) => isPublished(cwd, tool, release)),
|
||||
);
|
||||
if (results.every(Boolean)) return;
|
||||
if (Date.now() >= deadline) {
|
||||
const missing = releases
|
||||
.filter((_, index) => !results[index])
|
||||
.map((release) => `${release.packageName}@${release.version}`);
|
||||
throw new Error(
|
||||
`Timed out waiting for approved packages to become visible: ${missing.join(", ")}`,
|
||||
);
|
||||
}
|
||||
await new Promise((resolve) =>
|
||||
setTimeout(resolve, Math.min(intervalMs, deadline - Date.now())),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async function ensureTag(github: GitHub, tag: string, sha: string) {
|
||||
try {
|
||||
const existing = await github.octokit.rest.git.getRef({
|
||||
...context.repo,
|
||||
ref: `tags/${tag}`,
|
||||
});
|
||||
if (existing.data.object.sha !== sha) {
|
||||
throw new Error(
|
||||
`Git tag ${tag} already exists at ${existing.data.object.sha}, expected ${sha}`,
|
||||
);
|
||||
}
|
||||
return;
|
||||
} catch (error) {
|
||||
if (!isHttpNotFound(error)) {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
await github.octokit.rest.git.createRef({
|
||||
...context.repo,
|
||||
ref: `refs/tags/${tag}`,
|
||||
sha,
|
||||
});
|
||||
}
|
||||
|
||||
async function ensureRelease(github: GitHub, pkg: Package, tagName: string) {
|
||||
try {
|
||||
await github.octokit.rest.repos.getReleaseByTag({
|
||||
...context.repo,
|
||||
tag: tagName,
|
||||
});
|
||||
return;
|
||||
} catch (error) {
|
||||
if (!isHttpNotFound(error)) {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
await createRelease(github.octokit, { pkg, tagName });
|
||||
}
|
||||
|
||||
export async function finalizeStagedRelease(options: {
|
||||
github: GitHub;
|
||||
handoff: StagedReleaseHandoff;
|
||||
packagesByName: Map<string, Package>;
|
||||
cwd: string;
|
||||
verify: boolean;
|
||||
}) {
|
||||
if (options.verify) {
|
||||
await verifyPublished(options.handoff.releases, options.cwd);
|
||||
}
|
||||
|
||||
for (const entry of options.handoff.releases) {
|
||||
const pkg = options.packagesByName.get(entry.packageName)!;
|
||||
await ensureTag(options.github, entry.gitTag, options.handoff.sha);
|
||||
await ensureRelease(options.github, pkg, entry.gitTag);
|
||||
}
|
||||
}
|
||||
+1
-53
@@ -1,11 +1,5 @@
|
||||
import { createFixture } from "fs-fixture";
|
||||
import { expect, test } from "vitest";
|
||||
import {
|
||||
BumpLevels,
|
||||
getChangelogEntry,
|
||||
sortTheThings,
|
||||
validateChangesetsCliVersion,
|
||||
} from "./utils.ts";
|
||||
import { BumpLevels, getChangelogEntry, sortTheThings } from "./utils.ts";
|
||||
|
||||
let changelog = `# @keystone-alpha/email
|
||||
|
||||
@@ -106,49 +100,3 @@ test("it sorts the things right", () => {
|
||||
];
|
||||
expect(things.sort(sortTheThings)).toMatchSnapshot();
|
||||
});
|
||||
|
||||
test("throws when the project declares Changesets CLI v2", async () => {
|
||||
await using fixture = await createFixture({
|
||||
"package.json": JSON.stringify({
|
||||
name: "project",
|
||||
devDependencies: { "@changesets/cli": "^2.29.7" },
|
||||
}),
|
||||
"package-lock.json": "",
|
||||
});
|
||||
|
||||
await expect(validateChangesetsCliVersion(fixture.path)).rejects.toThrow(
|
||||
"This version of the Changesets action is designed to work with Changesets CLI v3. Changesets CLI v2 is not supported; use Changesets action v1 instead, which is compatible with CLI v2.",
|
||||
);
|
||||
});
|
||||
|
||||
test("accepts a Changesets CLI v3 contract without an installed CLI", async () => {
|
||||
await using fixture = await createFixture({
|
||||
"package.json": JSON.stringify({
|
||||
name: "project",
|
||||
devDependencies: { "@changesets/cli": "^3.0.0" },
|
||||
}),
|
||||
"package-lock.json": "",
|
||||
});
|
||||
|
||||
await expect(
|
||||
validateChangesetsCliVersion(fixture.path),
|
||||
).resolves.toBeUndefined();
|
||||
});
|
||||
|
||||
test("throws when the project has Changesets CLI v2 installed", async () => {
|
||||
await using fixture = await createFixture({
|
||||
"package.json": JSON.stringify({
|
||||
name: "project",
|
||||
devDependencies: { "@changesets/cli": "^3.0.0" },
|
||||
}),
|
||||
"package-lock.json": "",
|
||||
"node_modules/@changesets/cli/package.json": JSON.stringify({
|
||||
name: "@changesets/cli",
|
||||
version: "2.29.7",
|
||||
}),
|
||||
});
|
||||
|
||||
await expect(validateChangesetsCliVersion(fixture.path)).rejects.toThrow(
|
||||
"This version of the Changesets action is designed to work with Changesets CLI v3. Changesets CLI v2 is not supported; use Changesets action v1 instead, which is compatible with CLI v2.",
|
||||
);
|
||||
});
|
||||
|
||||
@@ -10,8 +10,6 @@ import {
|
||||
type ExecOutput,
|
||||
} from "@actions/exec";
|
||||
import { getPackages, type Package } from "@manypkg/get-packages";
|
||||
import major from "semver/functions/major.js";
|
||||
import subset from "semver/ranges/subset.js";
|
||||
|
||||
const require = createRequire(import.meta.url);
|
||||
|
||||
@@ -137,16 +135,6 @@ export function getRequiredInput(name: string) {
|
||||
return core.getInput(name, { required: true });
|
||||
}
|
||||
|
||||
export function getOptionalBooleanInput(name: string) {
|
||||
const value = getOptionalInput(name);
|
||||
if (value === undefined) return undefined;
|
||||
if (value.toLowerCase() === "true") return true;
|
||||
if (value.toLowerCase() === "false") return false;
|
||||
throw new Error(
|
||||
`Invalid boolean input ${JSON.stringify(name)}: ${JSON.stringify(value)}`,
|
||||
);
|
||||
}
|
||||
|
||||
export function throwOnRenamedInputs(renames: Record<string, string>) {
|
||||
const references: Record<string, string> = {};
|
||||
|
||||
@@ -166,55 +154,6 @@ export function throwOnRenamedInputs(renames: Record<string, string>) {
|
||||
}
|
||||
}
|
||||
|
||||
const changesetsCliCompatibilityError =
|
||||
"This version of the Changesets action is designed to work with Changesets CLI v3. " +
|
||||
"Changesets CLI v2 is not supported; use Changesets action v1 instead, which is compatible with CLI v2.";
|
||||
|
||||
export async function validateChangesetsCliVersion(cwd: string) {
|
||||
const { rootPackage } = await getPackages(cwd);
|
||||
const packageJson = rootPackage?.packageJson;
|
||||
const declaredVersion =
|
||||
packageJson?.devDependencies?.["@changesets/cli"] ??
|
||||
packageJson?.dependencies?.["@changesets/cli"];
|
||||
|
||||
if (typeof declaredVersion === "string") {
|
||||
const range = declaredVersion.startsWith("workspace:")
|
||||
? declaredVersion.slice("workspace:".length)
|
||||
: declaredVersion;
|
||||
|
||||
let isV2 = false;
|
||||
|
||||
try {
|
||||
isV2 = subset(range, ">=2.0.0-0 <3.0.0-0", {
|
||||
includePrerelease: true,
|
||||
});
|
||||
} catch {
|
||||
// it could be a non-semver protocol
|
||||
}
|
||||
|
||||
if (isV2) {
|
||||
throw new Error(changesetsCliCompatibilityError);
|
||||
}
|
||||
}
|
||||
|
||||
let cliPackageJson;
|
||||
|
||||
try {
|
||||
cliPackageJson = require(
|
||||
require.resolve("@changesets/cli/package.json", { paths: [cwd] }),
|
||||
);
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
|
||||
if (
|
||||
typeof cliPackageJson.version === "string" &&
|
||||
major(cliPackageJson.version) === 2
|
||||
) {
|
||||
throw new Error(changesetsCliCompatibilityError);
|
||||
}
|
||||
}
|
||||
|
||||
function resolveChangesetsCli(cwd: string) {
|
||||
return require.resolve("@changesets/cli/bin.js", {
|
||||
paths: [cwd],
|
||||
|
||||
@@ -1,11 +1,7 @@
|
||||
import * as core from "@actions/core";
|
||||
import { GitHub } from "../github.ts";
|
||||
import { runVersion } from "../run.ts";
|
||||
import {
|
||||
getOptionalInput,
|
||||
getRequiredInput,
|
||||
validateChangesetsCliVersion,
|
||||
} from "../utils.ts";
|
||||
import { getOptionalInput, getRequiredInput } from "../utils.ts";
|
||||
|
||||
try {
|
||||
await main();
|
||||
@@ -14,10 +10,6 @@ try {
|
||||
}
|
||||
|
||||
async function main() {
|
||||
// If the user needs to change the cwd, set `working-directory` in the step instead
|
||||
const cwd = process.cwd();
|
||||
await validateChangesetsCliVersion(cwd);
|
||||
|
||||
const githubToken = getRequiredInput("github-token");
|
||||
const script = getOptionalInput("script");
|
||||
const commitMessage = getRequiredInput("commit-message");
|
||||
@@ -35,6 +27,9 @@ async function main() {
|
||||
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 github = new GitHub({
|
||||
cwd,
|
||||
githubToken,
|
||||
|
||||
Reference in New Issue
Block a user