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/r-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 { writeFile, readFile, unlink } from "fs";6import { file } from "tmp";7import { callback } from "awaiting";8import { spawn } from "child_process";910interface ParserOptions {11parser?: string;12tabWidth?: number;13lineWidth?: number;14}1516function close(proc, cb): void {17proc.on("close", (code) => cb(undefined, code));18}1920function formatR(input_path: string) {21// in-place is fine, according to my tests22const expr = `suppressMessages(require(formatR)); tidy_source(source="${input_path}", file="${input_path}", indent=2, width.cutoff=80)`;23return spawn("R", ["--quiet", "--vanilla", "--no-save", "-e", expr]);24}2526export async function r_format(27input: string,28_: ParserOptions,29logger: any30): Promise<string> {31// create input temp file32const input_path: string = await callback(file);33try {34await callback(writeFile, input_path, input);3536// spawn the R formatter37const r_formatter = formatR(input_path);3839// stdout/err capture40let stdout: string = "";41let stderr: string = "";42// read data as it is produced.43r_formatter.stdout.on("data", (data) => (stdout += data.toString()));44r_formatter.stderr.on("data", (data) => (stderr += data.toString()));45// wait for subprocess to close.46const code = await callback(close, r_formatter);47if (code) {48const err_msg = `${stderr}`;49logger.debug(`R_FORMAT ${err_msg}`);50throw new Error(err_msg);51}5253// all fine, we read from the temp file54const output: Buffer = await callback(readFile, input_path);55const s: string = output.toString("utf-8");5657return s;58} finally {59unlink(input_path, () => {});60}61}626364