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/clang-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 "node:child_process";7import { readFile, unlink, writeFile } from "node:fs";8import { file as tmp_file } from "tmp";910import { Options } from "./index";1112function close(proc, cb): void {13proc.on("close", (code) => cb(undefined, code));14}1516// ref: https://clang.llvm.org/docs/ClangFormat.html1718function run_clang_format(19input_path: string,20indent: number /*, logger: any*/21) {22const style = `-style={BasedOnStyle: google, IndentWidth: ${indent}}`;23// See https://github.com/sagemathinc/cocalc/issues/5419 for why we disable sort-includes!24const args = ["--sort-includes=0", "-i", style, input_path];25// logger.debug(`run_clang_format args: [${args}]`);26return spawn("clang-format", args);27}2829export async function clang_format(30input: string,31ext: string,32options: Options,33logger: any34): Promise<string> {35// create input temp file36// we have to set the correct filename extension, because clang format uses it37const input_path: string = await callback(tmp_file, { postfix: `.${ext}` });38try {39// logger.debug(`clang_format tmp file: ${input_path}`);40await callback(writeFile, input_path, input);4142// spawn the c formatter43let formatter;44const indent = options.tabWidth || 2;4546switch (options.parser) {47case "clang-format":48formatter = run_clang_format(input_path, indent /*, logger*/);49break;50default:51throw Error(52`Unknown C/C++ code formatting utility '${options.parser}'`53);54}55// stdout/err capture56let stdout: string = "";57let stderr: string = "";58// read data as it is produced.59formatter.stdout.on("data", (data) => (stdout += data.toString()));60formatter.stderr.on("data", (data) => (stderr += data.toString()));61// wait for subprocess to close.62const code = await callback(close, formatter);6364if (code >= 1) {65const err_msg = `C/C++ code formatting utility "${options.parser}" exited with code ${code}\nOutput:\n${stdout}\n${stderr}`;66logger.debug(`clang-format error: ${err_msg}`);67throw Error(err_msg);68}6970// all fine, we read from the temp file71const output: Buffer = await callback(readFile, input_path);7273const s: string = output.toString("utf-8");74// logger.debug(`clang_format output s ${s}`);7576return s;77} finally {78unlink(input_path, () => {});79}80}818283