From e46a47b54fce3d727cfc4248705a417d00c26bc2 Mon Sep 17 00:00:00 2001 From: Lenny Andreu Date: Sun, 18 May 2025 00:07:56 -0400 Subject: [PATCH] Add cli input handler Also check for directories Also add a small help --- cli.js | 59 +++++++++++++++++++++++++++++++++++++++++++--------------- 1 file changed, 44 insertions(+), 15 deletions(-) diff --git a/cli.js b/cli.js index 941bae3..3cd1e0d 100755 --- a/cli.js +++ b/cli.js @@ -1,36 +1,65 @@ -import { readFile, writeFile } from 'node:fs/promises'; +#!/usr/bin/env node + +import { readFile, writeFile, stat } from 'node:fs/promises'; +import { argv, exit } from 'node:process'; import { convert } from './magic.js'; -async function reader(path){ +async function reader(path) { try { - const contents = await readFile(path, { encoding: 'utf8' }); - // console.log(contents) - return contents; + const preFlighCheck = await stat(path); + const isUsable = preFlighCheck.isFile() && !preFlighCheck.isDirectory() + if (!isUsable) + return ""; + const contents = await readFile(path, { encoding: 'utf8' }); + return contents; } catch (err) { - console.error(err.message); + console.error(err.message); } } -async function writer(path, content){ +async function writer(path, content) { try { - await writeFile(path, content, { encoding: 'utf8' }); + const preFlighCheck = await stat(path); + const isUsable = preFlighCheck.isFile() && !preFlighCheck.isDirectory() + if (!isUsable) + return; + await writeFile(path, content, { encoding: 'utf8' }); } catch (err) { - console.error(err.message); + console.error(err.message); } } -function convertForConsole(convertFunction){ - return async function(filePath){ - const sourceFile = await reader("./systemd-unit.conf"); +function convertForConsole(convertFunction) { + return async function (filePath) { + const sourceFile = await reader(filePath); const converted = convertFunction(sourceFile); await writer("./init.conf", converted.result) } } -async function setup(){ +async function setup(input, output) { const convertFunction = convertForConsole(convert) - convertFunction(); + convertFunction(input); } -setup(); \ No newline at end of file +const [, , input, output] = argv; + +// print process.argv +// argv.forEach((val, index) => { +// console.log(`${index}: ${val}`); +// }); +// exit(0); +if (input === "-h" || input === '--help' || argv.length < 3) { + console.info(` +Convert systemd service unit to openrc + + usage: +cli.js + + example: +cli.js systemd.unit init.conf +`) + exit(); +} +setup(input, output); \ No newline at end of file