UNPKG

2.41 kBJavaScriptView Raw
1'use strict';
2
3const debug = require(`debug`)(`set-npm-auth-token-for-ci`);
4const fs = require(`fs`);
5const localOrHomeNpmrc = require(`local-or-home-npmrc`);
6const registryUrl = require(`registry-url`);
7const path = require(`path`);
8
9/* istanbul ignore next */
10module.exports = () => setNpmAuthTokenForCI(fs, registryUrl);
11module.exports.setNpmAuthTokenForCI = setNpmAuthTokenForCI;
12
13function setNpmAuthTokenForCI (fs, registryUrl) {
14 const packageContents = JSON.parse(fs.readFileSync(path.join(process.cwd(), `package.json`)).toString());
15
16 const npmrcFile = localOrHomeNpmrc();
17 let contents = '';
18
19 // Attempt to read the `.npmrc` file. `local-or-home-npmrc` will always return back a path to the user's `~/.npmrc`
20 // file if no `.npmrc` file exists locally or in the user's home directory. So let's try reading the path provided
21 // by `local-or-home-npmrc`, and if that fails, ignore the error, assume an empty file, and then write to
22 // that file later.
23 try {
24 contents = fs.readFileSync(npmrcFile).toString();
25 } catch (error) {}
26
27 // If set, prefer the value of the `packageConfig.registry` property over the value of the registry as set
28 // in the user's `.npmrc` file.
29 //
30 // In one scenario, a package may fetch its dependencies from a virtual registry that is an overlay of a private
31 // registry over the public npm registry. Yet, that package is configured to publish directly to the private registry
32 // URL. To account for this scenario we need to get the value of the private registry URL and configure it within
33 // the `.npmrc` file.
34 let registry;
35 if (packageContents.publishConfig && packageContents.publishConfig.registry) {
36 registry = packageContents.publishConfig.registry;
37 registry = registry.slice(-1) === `/` ? registry : `${registry}/`;
38 } else {
39 const scope = packageContents.name.split(`/`)[0];
40 registry = registryUrl(scope);
41 }
42
43 debug(`using ${registry} registry for current package`);
44
45 const authTokenString = `${registry.replace(/^https?:/, ``)}:_authToken=\${NPM_TOKEN}`;
46
47 debug(`will set authentication token string in ${npmrcFile}`);
48
49 if (contents.indexOf(authTokenString) !== -1) {
50 return debug(`npmrc file, ${npmrcFile}, is already setup correctly`);
51 }
52
53 debug(`writing authentication token string, ${authTokenString}, to ${npmrcFile}`);
54
55 fs.writeFileSync(npmrcFile, `${contents}\n${authTokenString}\n`);
56}