From d3f16d3bfe9b510c72a6616b34a55be1afc6f3d7 Mon Sep 17 00:00:00 2001 From: andreacavalli Date: Thu, 19 Mar 2020 00:31:37 +0100 Subject: [PATCH] Add 'scripting.js' --- scripting.js | 66 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 scripting.js diff --git a/scripting.js b/scripting.js new file mode 100644 index 0000000..0a90d6e --- /dev/null +++ b/scripting.js @@ -0,0 +1,66 @@ +#!/usr/bin/node + +const fs = require('fs'); +const execSync = require('child_process').execSync; +const spawn = require('child_process').spawn; + +async function bash(bashScript, options) { + var bashArgs = []; + if (options !== undefined) { + if (options.strict === true) { + bashArgs.push("-e"); + } + } + bashArgs.push("-"); + var child = spawn("bash", bashArgs); + child.stdin.setEncoding('utf-8'); + child.stdin.write(bashScript); + child.stdin.end(); + let data = ""; + for await (const chunk of child.stdout) { + data += chunk; + } + let error = ""; + for await (const chunk of child.stderr) { + error += chunk; + } + const exitCode = await new Promise( (resolve, reject) => { child.on('close', resolve); }); + + if (exitCode) { + throw new Error( `subprocess error exit ${exitCode}, ${error}`); + } + + return data; +} +function exec(text) { + return execSync(text)+''; +} +function print(text) { + process.stdout.write(text); +} +function println(text) { + process.stdout.write(text + '\n'); +} + +const scriptPath = process.argv[2]; +const args = process.argv.splice(3); + +const rawScriptContent = fs.readFileSync(scriptPath)+''; +const fixedScriptContent = rawScriptContent.substring(rawScriptContent.indexOf("\n") + 1); + +const scriptPrefix = `async () => {`; +const scriptSuffix = `}`; +var evaluatedScript = eval(scriptPrefix + fixedScriptContent + scriptSuffix); + + +// Cleanup variables +delete spawn; +delete fs; +delete execSync; +delete scriptPath; +delete rawScriptContent; +delete fixedScriptContent; +delete scriptPrefix; +delete scriptSuffix; + +evaluatedScript(); \ No newline at end of file