setup-java/src/auth.ts

62 lines
1.7 KiB
TypeScript
Raw Normal View History

2019-11-16 01:01:13 +01: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';
export const M2_DIR = '.m2';
export const SETTINGS_FILE = 'settings.xml';
2019-11-28 21:40:45 +01:00
export async function configAuthentication(
id: string,
username: string,
password: string
) {
2019-11-28 21:40:08 +01:00
if (id && username && password) {
2019-11-28 21:54:29 +01:00
console.log(
`creating ${SETTINGS_FILE} with server-id: ${id}, username: ${username}, and a password`
);
2019-12-06 20:25:41 +01:00
const directory: string = path.join(os.homedir(), M2_DIR);
await io.mkdirP(directory);
core.debug(`created directory ${directory}`);
2019-11-28 21:40:08 +01:00
await write(directory, generate(id, username, password));
} else {
core.debug(
2019-11-28 21:54:29 +01:00
`no ${SETTINGS_FILE} without server-id: ${id}, username: ${username}, and a password`
);
}
2019-11-16 01:01:13 +01:00
}
// only exported for testing purposes
2019-11-28 21:40:08 +01:00
export function generate(id: string, username: string, password: string) {
return `
<settings>
<servers>
<server>
2019-11-28 21:40:08 +01:00
<id>${id}</id>
<username>${username}</username>
<password>${password}</password>
</server>
</servers>
</settings>
`;
2019-11-16 01:01:13 +01:00
}
async function write(directory: string, settings: string) {
2019-12-05 05:54:21 +01:00
const options = {encoding: 'utf-8', flag: 'wx'}; // 'wx': Like 'w' but fails if path exists
const location = path.join(directory, SETTINGS_FILE);
2019-12-06 20:28:17 +01:00
console.log(`writing ${location}`);
2019-12-05 05:54:21 +01:00
try {
2019-12-05 06:43:41 +01:00
return fs.writeFileSync(location, settings, options);
2019-12-05 05:54:21 +01:00
} catch (e) {
2019-12-06 20:32:51 +01:00
if (e.code == 'EEXIST') {
2019-12-06 20:28:34 +01:00
console.warn(`overwriting existing file ${location}`);
2019-12-06 20:32:51 +01:00
return fs.writeFileSync(location, settings, {
encoding: 'utf-8',
flag: 'w'
});
2019-12-05 05:54:21 +01:00
}
throw e;
}
2019-11-16 01:01:13 +01:00
}