1 | 'use strict';
|
2 |
|
3 | const debug = require(`debug`)(`set-npm-auth-token-for-ci`);
|
4 | const fs = require(`fs`);
|
5 | const localOrHomeNpmrc = require(`local-or-home-npmrc`);
|
6 | const registryUrl = require(`registry-url`);
|
7 | const path = require(`path`);
|
8 |
|
9 |
|
10 | module.exports = () => setNpmAuthTokenForCI(fs, registryUrl);
|
11 | module.exports.setNpmAuthTokenForCI = setNpmAuthTokenForCI;
|
12 |
|
13 | function 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 |
|
20 |
|
21 |
|
22 |
|
23 | try {
|
24 | contents = fs.readFileSync(npmrcFile).toString();
|
25 | } catch (error) {}
|
26 |
|
27 |
|
28 |
|
29 |
|
30 |
|
31 |
|
32 |
|
33 |
|
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 | }
|