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