Template-Engine/cli.mjs

78 lines
1.4 KiB
JavaScript

import { write, close } from 'node:fs';
import { spawn } from 'node:child_process';
import { file } from 'tmp-promise';
import { renderFile } from './src/template_engine.mjs';
if (process.argv.length <= 2) {
console.error(
`Usage: n0m [options] template_file.n0m\n` +
`Options:\n` +
` -c compile (by default the script will be executed)`
)
process.exit(1);
}
let compileOnly = false;
const args = process.argv
.slice(2)
.filter(arg => {
if (arg.toLocaleLowerCase() === '-c') {
compileOnly = true;
return false;
}
return true;
});
const fileName = args[0];
const scriptArgs = args.slice(1);
const rendered = await renderFile(fileName);
if (compileOnly) {
process.stdout.write(rendered);
process.exit(0);
}
// Create temporary file
const { fd, path, cleanup } = await file({
mode: 0o744,
detachDescriptor: true
});
// Write script to temporary file and close file if successful
await new Promise((resolve, reject) => {
write(fd, rendered, async writeErr => {
if (writeErr) {
reject(writeErr);
return;
}
close(fd, (closeErr) => {
if (closeErr) {
reject(closeErr);
return;
}
resolve();
});
});
});
// Spawn child process to execute script
let child = spawn(
path,
scriptArgs, {
stdio: 'inherit',
argv0: fileName
}
);
// Clean up temporary files once the child exits
child.on('exit', async () => {
await cleanup();
});