Skip to content
This repository was archived by the owner on Sep 19, 2025. It is now read-only.

Commit 3466bf3

Browse files
Merge pull request #248 from google/add-npm-token
Setup npmrc to allow publication from github actions
2 parents e76c0fd + 5e5939b commit 3466bf3

File tree

1 file changed

+29
-2
lines changed

1 file changed

+29
-2
lines changed

build-scripts/publish.js

Lines changed: 29 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ const path = require('path');
2929
const runCommand = require('./run-command');
3030

3131
const packagesDirPath = path.resolve(__dirname, '../packages');
32+
const npmrcPath = path.resolve(process.env.HOME, '.npmrc');
3233

3334
async function isPackageVersionPublished(packageName, version) {
3435
return fetch(`https://registry.npmjs.org/${encodeURI(packageName)}/${version}`)
@@ -38,8 +39,9 @@ async function isPackageVersionPublished(packageName, version) {
3839
async function isValidPackagePath(packageDir) {
3940
const packageJsonPath = `${packageDir}/package.json`;
4041
try {
42+
// check to see if the file already exists - if so do nothing
4143
await fs.stat(packageJsonPath);
42-
return true
44+
return true;
4345
} catch {
4446
return false;
4547
}
@@ -52,6 +54,29 @@ async function getPackageInfo(packageDir) {
5254
};
5355
}
5456

57+
let npmrcCleanupRequired = false;
58+
async function setupNpm() {
59+
try {
60+
await fs.stat(npmrcPath);
61+
return;
62+
} catch { }
63+
// For npm publication to work, the NPM token must be stored in the .npmrc file in the user home directory
64+
if (process.env.GITHUB_ACTIONS && process.env.NPM_TOKEN) {
65+
await fs.writeFile(
66+
path.resolve(process.env.HOME, '.npmrc'),
67+
`//registry.npmjs.org/:_authToken=${process.env.NPM_TOKEN}\n`,
68+
'utf8');
69+
npmrcCleanupRequired = true;
70+
}
71+
}
72+
73+
async function cleanupNpmrc() {
74+
if (!npmrcCleanupRequired) {
75+
return;
76+
}
77+
await fs.unlink(npmrcPath);
78+
}
79+
5580
async function publishPackagesIfNeeded(packageInfo) {
5681
const pkgJson = packageInfo.pkg;
5782
const isAlreadyPublished = await isPackageVersionPublished(pkgJson.name, pkgJson.version);
@@ -112,4 +137,6 @@ async function publishPackagesIfNeeded(packageInfo) {
112137
throw new Error('Unable to publish packages: cyclical dependencies encountered.');
113138
}
114139
}
115-
})().catch((e) => { throw e });
140+
})().catch((e) => {
141+
throw e;
142+
}).finally(cleanupNpmrc);

0 commit comments

Comments
 (0)