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

use module files (#252)

* use module

* detect files to be restore automatically

* use esbuild

* drop ncc

* add comments

* refactor
This commit is contained in:
shimataro 2023-10-11 04:35:20 +09:00 committed by GitHub
parent 31d4b8b483
commit 6948892be9
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
11 changed files with 775 additions and 3346 deletions

72
src/common.ts Normal file
View file

@ -0,0 +1,72 @@
import * as fs from "fs";
import * as path from "path";
import * as core from "@actions/core";
/** state name of backup suffix */
const STATE_BACKUP_SUFFIX = "backup-suffix";
/**
* create backup suffix name
* @param dirName directory to back up
* @returns backup suffix
*/
export function createBackupSuffix(dirName: string): string {
if (!fs.existsSync(dirName)) {
// do nothing if directory does not exist
return "";
}
const backupSuffix = `.bak-${Date.now()}`;
core.saveState(STATE_BACKUP_SUFFIX, backupSuffix);
return backupSuffix;
}
/**
* get backup suffix name
* @returns backup suffix (if not, empty string)
*/
export function getBackupSuffix(): string {
return core.getState(STATE_BACKUP_SUFFIX);
}
/**
* get SSH directory
* @returns SSH directory name
*/
export function getSshDirectory(): string {
return path.resolve(getHomeDirectory(), ".ssh");
}
/**
* get home directory
* @returns home directory name
*/
function getHomeDirectory(): string {
const homeEnv = getHomeEnv();
const home = process.env[homeEnv];
if (home === undefined) {
throw Error(`${homeEnv} is not defined`);
}
if (home === "/github/home") {
// Docker container
return "/root";
}
return home;
}
/**
* get HOME environment name
* @returns HOME environment name
*/
function getHomeEnv(): string {
if (process.platform === "win32") {
// Windows
return "USERPROFILE";
}
// macOS / Linux
return "HOME";
}

View file

@ -1,17 +1,23 @@
import fs from "fs";
import path from "path";
import * as fs from "fs";
import * as path from "path";
import * as core from "@actions/core";
import * as common from "./common";
/** file creation info */
interface FileInfo {
/** file name */
name: string;
/** file contents */
contents: string;
/** creation options */
options: fs.WriteFileOptions;
mustNotExist: boolean; // file must not exist when creating
/** file must not exist when creating */
mustNotExist: boolean;
}
const STATE_BACKUP_SUFFIX = "backup-suffix";
/** default known_hosts */
const KNOWN_HOSTS = [
"github.com ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQCj7ndNxQowgcQnjshcLrqPEiiphnt+VTTvDP6mHBL9j1aNUkY4Ue1gvwnGLVlOhGeYrnZaMgRK6+PKCUXaDbC7qtbW8gIkhL7aGCsOr/C56SJMy/BCZfxd1nWzAOxSDPgVsmerOBYfNqltV9/hWCqBywINIR+5dIg6JTJ72pcEpEjcYgXkE2YEFXV1JHnsKgbLWNlhScqb2UmyRkQyytRLtL+38TGxkxCflmO+5Z8CSSNY7GidjMIZ7Q4zMjA2n1nGrlTDkzwDCsw+wqFPGQA179cnfGWOWRVruj16z6XyvxvjJwbz0wQZ75XK5tKSb7FNyeIEs4TT4jk+S4dhPeAUC5y+bDYirYgM4GC7uEnztnZyaVWQ7B381AK4Qdrwt51ZqExKbQpTUNn+EjqoTwvqNj4kqx5QUCI0ThS/YkOxJCXmPUWZbhjpCg56i+2aB6CmK2JGhn57K5mj0MNdBXA4/WnwH6XoPWJzK5Nyu2zB3nAZp+S5hpQs+p1vN1/wsjk=",
];
@ -27,36 +33,7 @@ try {
/**
* main function
*/
function main(): void {
if (!isPost()) {
setup();
setPost();
} else {
cleanup();
}
}
/**
* is post process?
* @returns Yes/No
*/
function isPost(): boolean {
return Boolean(core.getState("isPost"));
}
/**
* update post state
*/
function setPost(): void {
core.saveState("isPost", "true");
}
/**
* setup function
*/
function setup(): void {
const backupSuffix = generateBackupSuffix();
export function main(): void {
// parameters
const key = core.getInput("key", {
required: true,
@ -69,7 +46,12 @@ function setup(): void {
const ifKeyExists = core.getInput("if_key_exists");
// create ".ssh" directory
const sshDirName = createSshDirectory();
const sshDirName = common.getSshDirectory();
const backupSuffix = common.createBackupSuffix(sshDirName);
fs.mkdirSync(sshDirName, {
recursive: true,
mode: 0o700,
});
// files to be created
const files: FileInfo[] = [
@ -119,41 +101,10 @@ function setup(): void {
console.log(`SSH key has been stored to ${sshDirName} successfully.`);
if (backedUpFileNames.length > 0) {
console.log(`Following files are backed up in suffix "${backupSuffix}"; ${backedUpFileNames.join(", ")}.`);
console.log(`Following files are backed up in suffix "${backupSuffix}"; ${backedUpFileNames.join(", ")}`);
}
}
/**
* cleanup function
*/
function cleanup(): void {
const backupSuffix = core.getState(STATE_BACKUP_SUFFIX);
if (backupSuffix === "") {
// remove ".ssh" directory if suffix is not set
const sshDirName = removeSshDirectory();
console.log(`SSH key in ${sshDirName} has been removed successfully.`);
} else {
restore(backupSuffix);
}
}
/**
* generate backup suffix name
* @returns backup suffix
*/
function generateBackupSuffix(): string {
const dirName = getSshDirectory();
if (!fs.existsSync(dirName)) {
// do nothing if .ssh does not exist
return "";
}
const backupSuffix = `.bak-${Date.now()}`;
core.saveState(STATE_BACKUP_SUFFIX, backupSuffix);
return backupSuffix;
}
/**
* back up file
* @param fileName file to back up
@ -179,97 +130,6 @@ function backup(fileName: string, backupSuffix: string, removeOrig: boolean): bo
return true;
}
/**
* restore files
* @param backupSuffix suffix of backup directory
*/
function restore(backupSuffix: string): void {
const dirName = getSshDirectory();
const keyFileName = core.getInput("name");
const restoredFileNames: string[] = [];
for (const fileName of ["known_hosts", "config", keyFileName]) {
const pathNameOrg = path.join(dirName, fileName);
const pathNameBak = `${pathNameOrg}${backupSuffix}`;
if (!fs.existsSync(pathNameBak)) {
continue;
}
fs.rmSync(pathNameOrg);
fs.renameSync(pathNameBak, pathNameOrg);
restoredFileNames.push(fileName);
}
console.log(`Following files in suffix "${backupSuffix}" are restored; ${restoredFileNames.join(", ")}`);
}
/**
* create ".ssh" directory
* @returns directory name
*/
function createSshDirectory(): string {
const dirName = getSshDirectory();
fs.mkdirSync(dirName, {
recursive: true,
mode: 0o700,
});
return dirName;
}
/**
* remove ".ssh" directory
* @returns removed directory name
*/
function removeSshDirectory(): string {
const dirName = getSshDirectory();
fs.rmSync(dirName, {
recursive: true,
force: true,
});
return dirName;
}
/**
* get SSH directory
* @returns SSH directory name
*/
function getSshDirectory(): string {
return path.resolve(getHomeDirectory(), ".ssh");
}
/**
* get home directory
* @returns home directory name
*/
function getHomeDirectory(): string {
const homeEnv = getHomeEnv();
const home = process.env[homeEnv];
if (home === undefined) {
throw Error(`${homeEnv} is not defined`);
}
if (home === "/github/home") {
// Docker container
return "/root";
}
return home;
}
/**
* get HOME environment name
* @returns HOME environment name
*/
function getHomeEnv(): string {
if (process.platform === "win32") {
// Windows
return "USERPROFILE";
}
// macOS / Linux
return "HOME";
}
/**
* prepend/append LF to value if not empty
* @param value the value to insert LF

66
src/post.ts Normal file
View file

@ -0,0 +1,66 @@
import * as fs from "fs";
import * as path from "path";
import * as core from "@actions/core";
import * as common from "./common";
try {
post();
} catch (err) {
if (err instanceof Error) {
core.setFailed(err);
}
}
/**
* cleanup function
*/
export function post(): void {
const backupSuffix = common.getBackupSuffix();
if (backupSuffix === "") {
// remove ".ssh" directory if suffix is not set
removeSshDirectory();
} else {
// restore files from backup suffix
restore(backupSuffix);
}
}
/**
* remove ".ssh" directory
*/
function removeSshDirectory(): void {
const dirName = common.getSshDirectory();
fs.rmSync(dirName, {
recursive: true,
force: true,
});
console.log(`SSH key in ${dirName} has been removed successfully.`);
}
/**
* restore files from backups
* @param backupSuffix suffix of backup directory
*/
function restore(backupSuffix: string): void {
const dirName = common.getSshDirectory();
const restoredFileNames: string[] = [];
const entries = fs.readdirSync(dirName)
.filter((entry) => {
// skip if not a backed-up file
return entry.endsWith(backupSuffix);
});
for (const entry of entries) {
const entryOrg = entry.substring(0, entry.length - backupSuffix.length);
const pathNameOrg = path.join(dirName, entryOrg);
const pathNameBak = path.join(dirName, entry);
fs.rmSync(pathNameOrg);
fs.renameSync(pathNameBak, pathNameOrg);
restoredFileNames.push(entryOrg);
}
console.log(`Following files in suffix "${backupSuffix}" are restored; ${restoredFileNames.join(", ")}`);
}