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/r-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 { callback } from "awaiting";
9
import { spawn } from "child_process";
10
11
interface ParserOptions {
12
parser?: string;
13
tabWidth?: number;
14
lineWidth?: number;
15
}
16
17
function close(proc, cb): void {
18
proc.on("close", (code) => cb(undefined, code));
19
}
20
21
function formatR(input_path: string) {
22
// in-place is fine, according to my tests
23
const expr = `suppressMessages(require(formatR)); tidy_source(source="${input_path}", file="${input_path}", indent=2, width.cutoff=80)`;
24
return spawn("R", ["--quiet", "--vanilla", "--no-save", "-e", expr]);
25
}
26
27
export async function r_format(
28
input: string,
29
_: ParserOptions,
30
logger: any
31
): Promise<string> {
32
// create input temp file
33
const input_path: string = await callback(file);
34
try {
35
await callback(writeFile, input_path, input);
36
37
// spawn the R formatter
38
const r_formatter = formatR(input_path);
39
40
// stdout/err capture
41
let stdout: string = "";
42
let stderr: string = "";
43
// read data as it is produced.
44
r_formatter.stdout.on("data", (data) => (stdout += data.toString()));
45
r_formatter.stderr.on("data", (data) => (stderr += data.toString()));
46
// wait for subprocess to close.
47
const code = await callback(close, r_formatter);
48
if (code) {
49
const err_msg = `${stderr}`;
50
logger.debug(`R_FORMAT ${err_msg}`);
51
throw new Error(err_msg);
52
}
53
54
// all fine, we read from the temp file
55
const output: Buffer = await callback(readFile, input_path);
56
const s: string = output.toString("utf-8");
57
58
return s;
59
} finally {
60
unlink(input_path, () => {});
61
}
62
}
63
64