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/xml-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 * as tmp from "tmp";7import { callback } from "awaiting";8import { executeCode } from "@cocalc/backend/execute-code";910interface ParserOptions {11parser: string;12}1314// ref: http://tidy.sourceforge.net/docs/quickref.html1516async function tidy(input_path) {17const args = [18"-modify",19"-xml",20"--indent",21"yes",22"--vertical-space",23"yes",24"--indent-spaces",25"2", // tune that if we let users ever choose the indentation26"--wrap",27"80",28"--sort-attributes",29"alpha",30"--quiet",31"yes",32"--write-back",33"yes",34"--show-warnings",35"no", // enable it, if we want to show warnings upon exit code == 136"--tidy-mark",37"no",38input_path,39];4041return await executeCode({42command: "tidy",43args: args,44err_on_exit: false,45bash: false,46timeout: 15,47});48}4950export async function xml_format(51input: string,52options: ParserOptions,53logger: any54): Promise<string> {55// create input temp file56const input_path: string = await callback(tmp.file);57try {58await callback(writeFile, input_path, input);5960// spawn the html formatter61let xml_formatter;62try {63switch (options.parser) {64case "xml-tidy":65xml_formatter = await tidy(input_path);66break;67default:68throw Error(`Unknown XML formatter utility '${options.parser}'`);69}70} catch (e) {71logger.debug(`Calling XML formatter raised ${e}`);72throw new Error(73`XML formatter broken or not available. Is '${options.parser}' installed?`74);75}7677const { exit_code, stdout, stderr } = xml_formatter;78const code = exit_code;7980const problem = options.parser === "xml-tidy" ? code >= 2 : code >= 1;81if (problem) {82const msg = `XML formatter "${options.parser}" exited with code ${code}\nOutput:\n${stdout}\n${stderr}`;83throw Error(msg);84}8586// all fine, we read from the temp file87const output: Buffer = await callback(readFile, input_path);88const s: string = output.toString("utf-8");89return s;90} finally {91// logger.debug(`xml formatter done, unlinking ${input_path}`);92unlink(input_path, () => {});93}94}959697