1
0
Fork 0
mirror of https://github.com/shimataro/ssh-key-action.git synced 2025-06-19 22:52:10 +10:00

add "if_key_exists" (#179)

* add "if_key_exists"

* add test

* fix flag

* fix SSH connection commands

* add test for if_key_exists=ignore

* add test for if_key_exists=fail

* add tests to Windows / macOS

* update CHANGELOG

* update badges

* update README

* fix README

* update README

* add tests for Docker containers
This commit is contained in:
shimataro 2021-03-18 20:57:28 +09:00 committed by GitHub
parent 8053198ce5
commit 88fb14d113
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
15 changed files with 1308 additions and 445 deletions

View file

@ -427,36 +427,16 @@ const core = __importStar(__nccwpck_require__(186));
*/
function main() {
try {
const files = [
{
name: core.getInput("name"),
contents: insertLf(core.getInput("key", {
required: true,
}), false, true),
options: {
mode: 0o400,
flag: "ax",
},
},
{
name: "known_hosts",
contents: insertLf(core.getInput("known_hosts", {
required: true,
}), true, true),
options: {
mode: 0o644,
flag: "a",
},
},
{
name: "config",
contents: insertLf(core.getInput("config"), true, true),
options: {
mode: 0o644,
flag: "a",
},
},
];
// parameters
const key = core.getInput("key", {
required: true,
});
const name = core.getInput("name");
const knownHosts = core.getInput("known_hosts", {
required: true,
});
const config = core.getInput("config");
const ifKeyExists = core.getInput("if_key_exists");
// create ".ssh" directory
const home = getHomeDirectory();
const dirName = path_1.default.resolve(home, ".ssh");
@ -464,6 +444,35 @@ function main() {
recursive: true,
mode: 0o700,
});
// files to be created
const files = [
{
name: "known_hosts",
contents: insertLf(knownHosts, true, true),
options: {
mode: 0o644,
flag: "a",
},
},
{
name: "config",
contents: insertLf(config, true, true),
options: {
mode: 0o644,
flag: "a",
},
},
];
if (shouldCreateKeyFile(path_1.default.join(dirName, name), ifKeyExists)) {
files.push({
name: name,
contents: insertLf(key, false, true),
options: {
mode: 0o400,
flag: "wx",
},
});
}
// create files
for (const file of files) {
const fileName = path_1.default.join(dirName, file.name);
@ -524,6 +533,30 @@ function insertLf(value, prepend, append) {
}
return affectedValue;
}
/**
* should create SSH key file?
* @param keyFilePath path of key file
* @param ifKeyExists action if SSH key exists
* @returns Yes/No
*/
function shouldCreateKeyFile(keyFilePath, ifKeyExists) {
if (!fs_1.default.existsSync(keyFilePath)) {
// should create if file does not exist
return true;
}
switch (ifKeyExists) {
case "replace":
// remove file and should create if replace
fs_1.default.unlinkSync(keyFilePath);
return true;
case "ignore":
// should NOT create if ignore
return false;
default:
// error otherwise
throw new Error(`SSH key is already installed. Set "if_key_exists" to "replace" or "ignore" in order to avoid this error.`);
}
}
main();