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/gofmt.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://golang.org/cmd/gofmt/ ... but there isn't anything to configure1718function run_gofmt(input_path: string) {19const args = ["-w", input_path];20return spawn("gofmt", args);21}2223function cleanup_error(err: string, tmpfn: string): string {24const ret: string[] = [];25for (let line of err.split("\n")) {26if (line.startsWith(tmpfn)) {27line = line.slice(tmpfn.length + 1);28}29ret.push(line);30}31return ret.join("\n");32}3334export async function gofmt(35input: string,36options: Options,37logger: any38): Promise<string> {39// create input temp file40const input_path: string = await callback(tmp.file);41try {42// logger.debug(`gofmt tmp file: ${input_path}`);43await callback(writeFile, input_path, input);4445// spawn the html formatter46let formatter;4748switch (options.parser) {49case "gofmt":50formatter = run_gofmt(input_path /*, logger*/);51break;52default:53throw Error(`Unknown Go code formatting utility '${options.parser}'`);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);63if (code >= 1) {64stdout = cleanup_error(stdout, input_path);65stderr = cleanup_error(stderr, input_path);66const err_msg = `Gofmt code formatting utility "${options.parser}" exited with code ${code}\nOutput:\n${stdout}\n${stderr}`;67logger.debug(`gofmt error: ${err_msg}`);68throw Error(err_msg);69}7071// all fine, we read from the temp file72const output: Buffer = await callback(readFile, input_path);73const s: string = output.toString("utf-8");74// logger.debug(`gofmt_format output s ${s}`);7576return s;77} finally {78unlink(input_path, () => {});79}80}818283