@cocalc/project
Version:
CoCalc: project daemon
50 lines • 1.99 kB
JavaScript
;
/*
* This file is part of CoCalc: Copyright © 2020 Sagemath, Inc.
* License: AGPLv3 s.t. "Commons Clause" – see LICENSE.md for details
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.r_format = void 0;
const fs_1 = require("fs");
const tmp_1 = require("tmp");
const awaiting_1 = require("awaiting");
const child_process_1 = require("child_process");
function close(proc, cb) {
proc.on("close", (code) => cb(undefined, code));
}
function formatR(input_path) {
// in-place is fine, according to my tests
const expr = `suppressMessages(require(formatR)); tidy_source(source="${input_path}", file="${input_path}", indent=2, width.cutoff=80)`;
return (0, child_process_1.spawn)("R", ["--quiet", "--vanilla", "--no-save", "-e", expr]);
}
async function r_format(input, _, logger) {
// create input temp file
const input_path = await (0, awaiting_1.callback)(tmp_1.file);
try {
await (0, awaiting_1.callback)(fs_1.writeFile, input_path, input);
// spawn the R formatter
const r_formatter = formatR(input_path);
// stdout/err capture
let stdout = "";
let stderr = "";
// read data as it is produced.
r_formatter.stdout.on("data", (data) => (stdout += data.toString()));
r_formatter.stderr.on("data", (data) => (stderr += data.toString()));
// wait for subprocess to close.
const code = await (0, awaiting_1.callback)(close, r_formatter);
if (code) {
const err_msg = `${stderr}`;
logger.debug(`R_FORMAT ${err_msg}`);
throw new Error(err_msg);
}
// all fine, we read from the temp file
const output = await (0, awaiting_1.callback)(fs_1.readFile, input_path);
const s = output.toString("utf-8");
return s;
}
finally {
(0, fs_1.unlink)(input_path, () => { });
}
}
exports.r_format = r_format;
//# sourceMappingURL=r-format.js.map