Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.
Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.
Path: blob/master/src/packages/project/formatters/rust-format.ts
Views: 687
/*1* This file is part of CoCalc: Copyright © 2020 Sagemath, Inc.2* License: MS-RSL – see LICENSE.md for details3*/45import { callback } from "awaiting";6import { spawn } from "child_process";7import { readFile, unlink, writeFile } from "node:fs";8import * as tmp from "tmp";910import { Options } from "./index";1112function close(proc, cb): void {13proc.on("close", (code) => cb(undefined, code));14}1516// ref: https://github.com/rust-lang/rustfmt ... but the configuration comes with project specific toml files1718function run_rustfmt(input_path: string) {19return spawn("rustfmt", [input_path]);20}2122function cleanup_error(out: string, tmpfn: string): string {23return out24.split("\n")25.filter((line) => line.indexOf(tmpfn) < 0)26.join("\n");27}2829export async function rust_format(30input: string,31options: Options,32logger: any33): Promise<string> {34// create input temp file35const input_path: string = await callback(tmp.file);36try {37// logger.debug(`rustfmt tmp file: ${input_path}`);38await callback(writeFile, input_path, input);3940// spawn the html formatter41let formatter;4243switch (options.parser) {44case "rustfmt":45formatter = run_rustfmt(input_path /*, logger*/);46break;47default:48throw Error(`Unknown Rust code formatting utility '${options.parser}'`);49}50// stdout/err capture51let stdout: string = "";52let stderr: string = "";53// read data as it is produced.54formatter.stdout.on("data", (data) => (stdout += data.toString()));55formatter.stderr.on("data", (data) => (stderr += data.toString()));56// wait for subprocess to close.57const code = await callback(close, formatter);58if (code >= 1) {59stdout = cleanup_error(stdout, input_path);60stderr = cleanup_error(stderr, input_path);61const err_msg = [stdout, stderr].filter((x) => !!x).join("\n");62logger.debug(`rustfmt error: ${err_msg}`);63throw Error(err_msg);64}6566// all fine, we read from the temp file67const output: Buffer = await callback(readFile, input_path);68const s: string = output.toString("utf-8");69// logger.debug(`rust_format output s ${s}`);70return s;71} finally {72unlink(input_path, () => {});73}74}757677