Template-Engine/cli.mjs

78 lines
1.4 KiB
JavaScript
Raw Normal View History

2022-09-02 23:31:55 -07:00
import { write, close } from 'node:fs';
import { spawn } from 'node:child_process';
import { file } from 'tmp-promise';
2022-09-02 23:31:55 -07:00
import { renderFile } from './src/template_engine.mjs';
2022-09-02 23:31:55 -07:00
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)`
)
2022-09-02 23:31:55 -07:00
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);
2022-09-02 23:31:55 -07:00
}
// 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();
});