From 6f5135b203d5101ecf2ef3eea53c5cc8bfad56c6 Mon Sep 17 00:00:00 2001 From: Nicola Molinari Date: Sat, 9 May 2020 00:03:53 +0200 Subject: [PATCH] fix: respect .npmrc if already present (#30) * fix: respect .npmrc if already present * Update dist file Co-authored-by: mitchellhamilton --- README.md | 20 ++++++++++++++++++++ dist/index.js | 2 +- index.ts | 14 ++++++++++---- 3 files changed, 31 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 97194bd..e0f0010 100644 --- a/README.md +++ b/README.md @@ -104,6 +104,26 @@ jobs: ``` +By default the GitHub Action creates a `.npmrc` file with the following content: + +``` +//registry.npmjs.org/:_authToken=${process.env.NPM_TOKEN} +``` + +However, if a `.npmrc` file is found, the GitHub Action does not recreate the file. This is useful if you need to configure the `.npmrc` file on your own. +For example, you can add a step before running the Changesets GitHub Action: + +```yml +- name: Creating .npmrc + run: | + cat << EOF > "$HOME/.npmrc" + email=my@email.com + //registry.npmjs.org/:_authToken=$NPM_TOKEN + EOF + env: + NPM_TOKEN: ${{ secrets.NPM_TOKEN }} +``` + #### With version script If you need to add additional logic to the version command, you can do so by using a version script. diff --git a/dist/index.js b/dist/index.js index 751e220..c4c4974 100644 --- a/dist/index.js +++ b/dist/index.js @@ -1219,5 +1219,5 @@ var e=require("./conversions"),n=require("./route"),r={},o=Object.keys(e);functi },{"chalk":"ug4C"}],"PCsh":[function(require,module,exports) { "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var e=c(require("@babel/runtime/helpers/esm/defineProperty")),r=l(require("fs-extra")),t=c(require("path")),n=c(require("@changesets/parse")),a=require("@changesets/git"),i=c(require("chalk")),o=c(require("p-filter")),s=require("@changesets/logger");function l(e){if(e&&e.__esModule)return e;var r={};if(null!=e)for(var t in e)if(Object.prototype.hasOwnProperty.call(e,t)){var n=Object.defineProperty&&Object.getOwnPropertyDescriptor?Object.getOwnPropertyDescriptor(e,t):{};n.get||n.set?Object.defineProperty(r,t,n):r[t]=e[t]}return r.default=e,r}function c(e){return e&&e.__esModule?e:{default:e}}let u=i.default.red("===============================IMPORTANT!==============================="),d=i.default.red("----------------------------------------------------------------------");async function f(e,n){const a=(await(0,o.default)(n,async n=>(await(0,r.lstat)(t.default.join(e,n))).isDirectory())).map(async n=>{const a=t.default.join(e,n,"changes.json"),[i,o]=await Promise.all([(0,r.readFile)(t.default.join(e,n,"changes.md"),"utf-8"),(0,r.readJson)(a)]);return{releases:o.releases,summary:i,id:n}});return Promise.all(a)}async function p(e,r){let t=await f(e,r);return 0===t.length?[]:((0,s.warn)(u),(0,s.warn)("There were old changesets from version 1 found"),(0,s.warn)("Theses are being applied now but the dependents graph may have changed"),(0,s.warn)("Make sure you validate all your dependencies"),(0,s.warn)("In a future major version, we will no longer apply these old changesets, and will instead throw here"),(0,s.warn)(d),t)}function h(e,r){var t=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);r&&(n=n.filter(function(r){return Object.getOwnPropertyDescriptor(e,r).enumerable})),t.push.apply(t,n)}return t}function w(r){for(var t=1;te.split("/")[1]);return e.filter(e=>n.includes(e))}async function g(e,a){let i,o=t.default.join(e,".changeset");try{i=await r.default.readdir(o)}catch(c){if("ENOENT"===c.code)throw new Error("There is no .changeset directory in this project");throw c}void 0!==a&&(i=await y(i,o,a));let s=p(o,i);const l=i.filter(e=>e.endsWith(".md")&&"README.md"!==e).map(async e=>{const a=await r.default.readFile(t.default.join(o,e),"utf-8");return w({},(0,n.default)(a),{id:e.replace(".md","")})});return[...await s,...await Promise.all(l)]}var O=g;exports.default=O; },{"@babel/runtime/helpers/esm/defineProperty":"9iDM","fs-extra":"rdZu","@changesets/parse":"boSt","@changesets/git":"It5m","chalk":"ug4C","p-filter":"PNks","@changesets/logger":"cocj"}],"7QCb":[function(require,module,exports) { -"use strict";function e(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);t&&(a=a.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),i.push.apply(i,a)}return i}function t(t){for(var a=1;a{let e=process.env.GITHUB_TOKEN;if(!e)return void r.setFailed("Please add the GITHUB_TOKEN to the changesets action");let i=`${s.context.repo.owner}/${s.context.repo.repo}`,a=s.context.ref.replace("refs/heads/",""),n=await h.readPreState(process.cwd()),f=void 0!==n&&"pre"===n.mode;const b=new s.GitHub(e);console.log("setting git user"),await o.exec("git",["config","--global","user.name",'"github-actions[bot]"']),await o.exec("git",["config","--global","user.email",'"github-actions[bot]@users.noreply.github.com"']),console.log("setting GitHub credentials"),await l.default.writeFile(`${process.env.HOME}/.netrc`,`machine github.com\nlogin github-actions[bot]\npassword ${e}`);let m=await d.default(process.cwd());if(f){let e=new Set(n.changesets);m=m.filter(t=>!e.has(t.id))}let w=0!==m.length,y={publishScript:r.getInput("publish"),versionScript:r.getInput("version"),commit:r.getInput("commit")||"Version Packages",prTitle:r.getInput("title")||"Version Packages"};if(r.setOutput("published","false"),r.setOutput("publishedPackages","[]"),w||y.publishScript){if(!w&&y.publishScript){console.log("No changesets found, attempting to publish any unpublished packages to npm");let e=await c.default({tools:["yarn","bolt","pnpm","root"]});if(!e)return r.setFailed("Could not find workspaces");let i=new Map(e.map(e=>[e.name,e]));l.default.writeFileSync(`${process.env.HOME}/.npmrc`,`//registry.npmjs.org/:_authToken=${process.env.NPM_TOKEN}`);let[n,...g]=y.publishScript.split(/\s+/),h=await p.execWithOutput(n,g);await o.exec("git",["pull","origin",a]),await o.exec("git",["push","origin",`HEAD:${a}`,"--tags"]);let d=/New tag:\s+(@[^/]+\/[^@]+|[^/]+)@([^\s]+)/,f=[];for(let t of h.stdout.split("\n")){let e=t.match(d);if(null===e)continue;let a=e[1],n=i.get(a);if(void 0===n)return r.setFailed("Workspace not found for "+a+". This is probably a bug in the action, please open an issue");f.push(n)}return await Promise.all(f.map(async e=>{try{let a=u.default.join(e.dir,"CHANGELOG.md"),n=await l.default.readFile(a,"utf8"),o=p.getChangelogEntry(n,e.config.version);if(!o)return r.setFailed(`Could not find changelog entry for ${e.name}@${e.config.version}`);await b.repos.createRelease(t({tag_name:`${e.name}@${e.config.version}`,body:o.content,prerelease:e.config.version.includes("-")},s.context.repo))}catch(i){if("ENOENT"!==i.code)throw i}})),void(f.length&&(r.setOutput("published","true"),r.setOutput("publishedPackages",JSON.stringify(f.map(e=>({name:e.name,version:e.config.version}))))))}if(w){let e=`changeset-release/${a}`,{stderr:r}=await p.execWithOutput("git",["checkout",e],{ignoreReturnCode:!0});if(!r.toString().includes(`Switched to a new branch '${e}'`)&&await o.exec("git",["checkout","-b",e]),await o.exec("git",["reset","--hard",s.context.sha]),y.versionScript){let[e,...t]=y.versionScript.split(/\s+/);await o.exec(e,t)}else{let e=await l.default.readJson(u.default.join("node_modules","@changesets","cli","package.json")),t=g.lt(e.version,"2.0.0")?"bump":"version";await o.exec("node",["./node_modules/@changesets/cli/bin.js",t])}let c=`repo:${i}+state:open+head:${e}+base:${a}`,h=b.search.issuesAndPullRequests({q:c}),d=await p.getChangedPackages(process.cwd()),m=(async()=>`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 ${y.publishScript?"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 ${a}, this PR will be updated.\n${f?`\n⚠️⚠️⚠️⚠️⚠️⚠️\n\n\`${a}\` 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 \`${a}\`.\n\n⚠️⚠️⚠️⚠️⚠️⚠️\n`:""}\n# Releases\n`+(await Promise.all(d.map(async e=>{let t=await l.default.readFile(u.default.join(e.dir,"CHANGELOG.md"),"utf8"),i=p.getChangelogEntry(t,e.config.version);return{highestLevel:i.highestLevel,private:!!e.config.private,content:`## ${e.name}@${e.config.version}\n\n`+i.content}}))).filter(e=>e).sort(p.sortTheThings).map(e=>e.content).join("\n "))();const w=`${y.prTitle}${f?` (${n.tag})`:""}`,v=`${y.commit}${f?` (${n.tag})`:""}`;await o.exec("git",["add","."]),await o.exec("git",["commit","-m",v]),await o.exec("git",["push","origin",e,"--force"]);let O=await h;console.log(JSON.stringify(O.data,null,2)),0===O.data.items.length?(console.log("creating pull request"),await b.pulls.create(t({base:a,head:e,title:w,body:await m},s.context.repo))):(b.pulls.update(t({pull_number:O.data.items[0].number,title:w,body:await m},s.context.repo)),console.log("pull request found"))}}else console.log("No changesets found")})().catch(e=>{console.error(e),r.setFailed(e.message)}); +"use strict";function e(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),i.push.apply(i,n)}return i}function t(t){for(var n=1;n{let e=process.env.GITHUB_TOKEN;if(!e)return void o.setFailed("Please add the GITHUB_TOKEN to the changesets action");let i=`${s.context.repo.owner}/${s.context.repo.repo}`,n=s.context.ref.replace("refs/heads/",""),a=await h.readPreState(process.cwd()),f=void 0!==a&&"pre"===a.mode;const b=new s.GitHub(e);console.log("setting git user"),await r.exec("git",["config","--global","user.name",'"github-actions[bot]"']),await r.exec("git",["config","--global","user.email",'"github-actions[bot]@users.noreply.github.com"']),console.log("setting GitHub credentials"),await l.default.writeFile(`${process.env.HOME}/.netrc`,`machine github.com\nlogin github-actions[bot]\npassword ${e}`);let m=await d.default(process.cwd());if(f){let e=new Set(a.changesets);m=m.filter(t=>!e.has(t.id))}let w=0!==m.length,y={publishScript:o.getInput("publish"),versionScript:o.getInput("version"),commit:o.getInput("commit")||"Version Packages",prTitle:o.getInput("title")||"Version Packages"};if(o.setOutput("published","false"),o.setOutput("publishedPackages","[]"),w||y.publishScript){if(!w&&y.publishScript){console.log("No changesets found, attempting to publish any unpublished packages to npm");let e=await c.default({tools:["yarn","bolt","pnpm","root"]});if(!e)return o.setFailed("Could not find workspaces");let i=new Map(e.map(e=>[e.name,e])),a=`${process.env.HOME}/.npmrc`;l.default.existsSync(a)?console.log("Found existing .npmrc file"):(console.log("No .npmrc file found, creating one"),l.default.writeFileSync(a,`//registry.npmjs.org/:_authToken=${process.env.NPM_TOKEN}`));let[g,...h]=y.publishScript.split(/\s+/),d=await p.execWithOutput(g,h);await r.exec("git",["pull","origin",n]),await r.exec("git",["push","origin",`HEAD:${n}`,"--tags"]);let f=/New tag:\s+(@[^/]+\/[^@]+|[^/]+)@([^\s]+)/,m=[];for(let t of d.stdout.split("\n")){let e=t.match(f);if(null===e)continue;let n=e[1],a=i.get(n);if(void 0===a)return o.setFailed("Workspace not found for "+n+". This is probably a bug in the action, please open an issue");m.push(a)}return await Promise.all(m.map(async e=>{try{let n=u.default.join(e.dir,"CHANGELOG.md"),a=await l.default.readFile(n,"utf8"),r=p.getChangelogEntry(a,e.config.version);if(!r)return o.setFailed(`Could not find changelog entry for ${e.name}@${e.config.version}`);await b.repos.createRelease(t({tag_name:`${e.name}@${e.config.version}`,body:r.content,prerelease:e.config.version.includes("-")},s.context.repo))}catch(i){if("ENOENT"!==i.code)throw i}})),void(m.length&&(o.setOutput("published","true"),o.setOutput("publishedPackages",JSON.stringify(m.map(e=>({name:e.name,version:e.config.version}))))))}if(w){let e=`changeset-release/${n}`,{stderr:o}=await p.execWithOutput("git",["checkout",e],{ignoreReturnCode:!0});if(!o.toString().includes(`Switched to a new branch '${e}'`)&&await r.exec("git",["checkout","-b",e]),await r.exec("git",["reset","--hard",s.context.sha]),y.versionScript){let[e,...t]=y.versionScript.split(/\s+/);await r.exec(e,t)}else{let e=await l.default.readJson(u.default.join("node_modules","@changesets","cli","package.json")),t=g.lt(e.version,"2.0.0")?"bump":"version";await r.exec("node",["./node_modules/@changesets/cli/bin.js",t])}let c=`repo:${i}+state:open+head:${e}+base:${n}`,h=b.search.issuesAndPullRequests({q:c}),d=await p.getChangedPackages(process.cwd()),m=(async()=>`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 ${y.publishScript?"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 ${n}, this PR will be updated.\n${f?`\n⚠️⚠️⚠️⚠️⚠️⚠️\n\n\`${n}\` 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 \`${n}\`.\n\n⚠️⚠️⚠️⚠️⚠️⚠️\n`:""}\n# Releases\n`+(await Promise.all(d.map(async e=>{let t=await l.default.readFile(u.default.join(e.dir,"CHANGELOG.md"),"utf8"),i=p.getChangelogEntry(t,e.config.version);return{highestLevel:i.highestLevel,private:!!e.config.private,content:`## ${e.name}@${e.config.version}\n\n`+i.content}}))).filter(e=>e).sort(p.sortTheThings).map(e=>e.content).join("\n "))();const w=`${y.prTitle}${f?` (${a.tag})`:""}`,v=`${y.commit}${f?` (${a.tag})`:""}`;await r.exec("git",["add","."]),await r.exec("git",["commit","-m",v]),await r.exec("git",["push","origin",e,"--force"]);let O=await h;console.log(JSON.stringify(O.data,null,2)),0===O.data.items.length?(console.log("creating pull request"),await b.pulls.create(t({base:n,head:e,title:w,body:await m},s.context.repo))):(b.pulls.update(t({pull_number:O.data.items[0].number,title:w,body:await m},s.context.repo)),console.log("pull request found"))}}else console.log("No changesets found")})().catch(e=>{console.error(e),o.setFailed(e.message)}); },{"@actions/core":"4FTV","@actions/exec":"utFe","@actions/github":"8Dol","fs-extra":"JTJ9","get-workspaces":"kAcF","./utils":"UnXq","semver":"aric","@changesets/pre":"jEAA","@changesets/read":"PCsh"}]},{},["7QCb"], null) \ No newline at end of file diff --git a/index.ts b/index.ts index 0d23a34..44d966f 100644 --- a/index.ts +++ b/index.ts @@ -85,10 +85,16 @@ import readChangesets from "@changesets/read"; let workspacesByName = new Map(workspaces.map(x => [x.name, x])); - fs.writeFileSync( - `${process.env.HOME}/.npmrc`, - `//registry.npmjs.org/:_authToken=${process.env.NPM_TOKEN}` - ); + let npmrcPath = `${process.env.HOME}/.npmrc` + if (fs.existsSync(npmrcPath)) { + console.log("Found existing .npmrc file"); + } else { + console.log("No .npmrc file found, creating one"); + fs.writeFileSync( + npmrcPath, + `//registry.npmjs.org/:_authToken=${process.env.NPM_TOKEN}` + ); + } let [publishCommand, ...publishArgs] = inputs.publishScript.split(/\s+/);