2022-09-02 23:31:55 -07:00
|
|
|
|
2022-09-03 21:18:42 -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
|
|
|
|
2022-09-04 12:53:04 -07:00
|
|
|
import { renderFile } from './src/template_engine.mjs';
|
2022-09-02 23:31:55 -07:00
|
|
|
|
|
|
|
|
2022-09-03 21:18:42 -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);
|
|
|
|
}
|
|
|
|
|
2022-09-03 21:18:42 -07:00
|
|
|
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);
|
|
|
|
|
2022-09-05 16:49:15 -07:00
|
|
|
let rendered;
|
|
|
|
try {
|
|
|
|
rendered = await renderFile(fileName);
|
|
|
|
} catch (e) {
|
|
|
|
console.log("Error Rendering Template:")
|
|
|
|
console.log(e?.message || "Unknown Error");
|
|
|
|
process.exit(0);
|
|
|
|
}
|
2022-09-03 21:18:42 -07:00
|
|
|
|
|
|
|
if (compileOnly) {
|
|
|
|
process.stdout.write(rendered);
|
|
|
|
process.exit(0);
|
2022-09-02 23:31:55 -07:00
|
|
|
}
|
2022-09-03 21:18:42 -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();
|
|
|
|
});
|