CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
sagemathinc

Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.

GitHub Repository: sagemathinc/cocalc
Path: blob/master/src/packages/project/formatters/generic-format.ts
Views: 687
1
/*
2
* This file is part of CoCalc: Copyright © 2020 Sagemath, Inc.
3
* License: MS-RSL – see LICENSE.md for details
4
*/
5
6
import { writeFile, readFile, unlink } from "fs";
7
import { file } from "tmp";
8
import { once } from "@cocalc/util/async-utils";
9
import { callback } from "awaiting";
10
import { spawn } from "child_process";
11
12
interface Options {
13
command: string;
14
args: (inputPath) => string[];
15
input: string;
16
timeout_s?: number; // default of 30 seconds
17
}
18
19
export default async function genericFormat({
20
command,
21
args,
22
input,
23
timeout_s,
24
}: Options): Promise<string> {
25
// create input temp file
26
const inputPath: string = await callback(file);
27
try {
28
await callback(writeFile, inputPath, input);
29
30
// spawn the formatter
31
const child = spawn(command, args(inputPath));
32
33
// output stream capture:
34
let stdout: string = "";
35
let stderr: string = "";
36
child.stdout.on("data", (data) => (stdout += data.toString("utf-8")));
37
child.stderr.on("data", (data) => (stderr += data.toString("utf-8")));
38
// wait for subprocess to close.
39
const code = await once(child, "close", (timeout_s ?? 30) * 1000);
40
if (code[0]) throw Error(stderr);
41
// all fine, we read from the temp file:
42
return (await callback(readFile, inputPath)).toString("utf-8");
43
} finally {
44
await callback(unlink, inputPath);
45
}
46
}
47
48