setup-node/src/authutil.ts

49 lines
1.7 KiB
TypeScript
Raw Normal View History

2019-08-05 23:51:04 +08:00
import * as fs from 'fs';
import * as os from 'os';
2019-08-05 23:35:39 +08:00
import * as path from 'path';
2019-08-05 23:51:04 +08:00
import * as core from '@actions/core';
2019-08-06 03:18:52 +08:00
import * as github from '@actions/github';
2019-08-05 23:35:39 +08:00
2019-08-06 01:12:37 +08:00
export function configAuthentication(registryUrl: string) {
// const npmrc: string = path.resolve(
// process.env['RUNNER_TEMP'] || process.cwd(),
// '.npmrc'
// );
const npmrc: string = path.resolve(process.cwd(), '.npmrc');
2019-08-05 23:35:39 +08:00
writeRegistryToFile(registryUrl, npmrc);
2019-08-05 23:35:39 +08:00
}
function writeRegistryToFile(registryUrl: string, fileLocation: string) {
2019-08-06 03:18:52 +08:00
let scope = core.getInput('scope');
if (!scope && registryUrl.indexOf('npm.pkg.github.com') > -1) {
scope = github.context.repo.owner;
}
if (scope && scope[0] != '@') {
scope = '@' + scope;
}
2019-08-05 23:51:04 +08:00
core.debug(`Setting auth in ${fileLocation}`);
2019-08-06 01:15:47 +08:00
let newContents: string = '';
2019-08-05 23:51:04 +08:00
if (fs.existsSync(fileLocation)) {
2019-08-06 01:12:37 +08:00
const curContents: string = fs.readFileSync(fileLocation, 'utf8');
2019-08-05 23:51:04 +08:00
curContents.split(os.EOL).forEach((line: string) => {
// Add current contents unless they are setting the registry
2019-08-06 01:12:37 +08:00
if (!line.toLowerCase().startsWith('registry')) {
2019-08-05 23:51:04 +08:00
newContents += line + os.EOL;
}
});
}
2019-08-06 03:18:52 +08:00
// Remove http: or https: from front of registry.
const authString =
registryUrl.replace(/(^\w+:|^)/, '') + `:_authToken=${NODE_AUTH_TOKEN}`;
2019-08-06 03:18:52 +08:00
const registryString = scope
? `${scope}:registry=${registryUrl}`
: `registry=${registryUrl}`;
2019-08-06 21:40:13 +08:00
newContents += `${registryString}${os.EOL}${authString}`;
2019-08-05 23:51:04 +08:00
fs.writeFileSync(fileLocation, newContents);
2019-08-06 23:52:15 +08:00
// core.exportVariable('NPM_CONFIG_USERCONFIG', fileLocation);
2019-08-06 21:47:51 +08:00
// Export empty node_auth_token so npm doesn't complain about not being able to find it
// core.exportVariable('NODE_AUTH_TOKEN', 'XXXXX-XXXXX-XXXXX-XXXXX');
2019-08-05 23:35:39 +08:00
}