setup-java/src/auth.ts

88 lines
2.5 KiB
TypeScript
Raw Normal View History

2019-11-16 00:01:13 +00:00
import * as fs from 'fs';
import * as os from 'os';
import * as path from 'path';
import * as core from '@actions/core';
import * as io from '@actions/io';
2020-05-02 11:33:15 +00:00
import {create as xmlCreate} from 'xmlbuilder2';
import * as constants from './constants';
2019-11-16 00:01:13 +00:00
export const M2_DIR = '.m2';
export const SETTINGS_FILE = 'settings.xml';
2019-11-28 20:40:45 +00:00
export async function configAuthentication(
2020-05-02 11:33:15 +00:00
id: string,
username: string,
password: string,
gpgPassphrase: string | undefined = undefined
2019-11-28 20:40:45 +00:00
) {
2019-12-19 19:28:11 +00:00
console.log(
`creating ${SETTINGS_FILE} with server-id: ${id};`,
2020-05-02 11:33:15 +00:00
'environment variables:',
`username=\$${username},`,
`password=\$${password},`,
`and gpg-passphrase=${gpgPassphrase ? '$' + gpgPassphrase : null}`
2019-12-19 19:28:11 +00:00
);
// when an alternate m2 location is specified use only that location (no .m2 directory)
// otherwise use the home/.m2/ path
2020-05-02 11:33:15 +00:00
const settingsDirectory: string = path.join(
core.getInput(constants.INPUT_SETTINGS_PATH) || os.homedir(),
core.getInput(constants.INPUT_SETTINGS_PATH) ? '' : M2_DIR
2019-12-19 19:28:11 +00:00
);
2020-05-02 11:33:15 +00:00
await io.mkdirP(settingsDirectory);
core.debug(`created directory ${settingsDirectory}`);
await write(
settingsDirectory,
generate(id, username, password, gpgPassphrase)
);
2019-12-10 17:26:51 +00:00
}
2019-11-16 00:01:13 +00:00
// only exported for testing purposes
2019-12-19 19:28:11 +00:00
export function generate(
2020-05-02 11:33:15 +00:00
id: string,
username: string,
password: string,
gpgPassphrase: string | undefined = undefined
2019-12-19 19:28:11 +00:00
) {
2020-05-02 11:33:15 +00:00
const xmlObj: {[key: string]: any} = {
settings: {
'@xmlns': 'http://maven.apache.org/SETTINGS/1.0.0',
'@xmlns:xsi': 'http://www.w3.org/2001/XMLSchema-instance',
'@xsi:schemaLocation':
'http://maven.apache.org/SETTINGS/1.0.0 https://maven.apache.org/xsd/settings-1.0.0.xsd',
servers: {
server: [
{
id: id,
username: `\${env.${username}}`,
password: `\${env.${password}}`
}
]
}
}
};
if (gpgPassphrase) {
const gpgServer = {
id: 'gpg.passphrase',
passphrase: `\${env.${gpgPassphrase}}`
};
xmlObj.settings.servers.server.push(gpgServer);
}
return xmlCreate(xmlObj).end({headless: true, prettyPrint: true, width: 80});
2019-11-16 00:01:13 +00:00
}
async function write(directory: string, settings: string) {
const location = path.join(directory, SETTINGS_FILE);
2019-12-19 16:52:26 +00:00
if (fs.existsSync(location)) {
console.warn(`overwriting existing file ${location}`);
} else {
console.log(`writing ${location}`);
2019-12-05 04:54:21 +00:00
}
2019-12-19 16:52:26 +00:00
return fs.writeFileSync(location, settings, {
encoding: 'utf-8',
flag: 'w'
});
2019-11-16 00:01:13 +00:00
}