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/bib-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 { callback } from "awaiting";
7
import { readFile, unlink, writeFile } from "node:fs";
8
import * as tmp from "tmp";
9
10
import { executeCode } from "@cocalc/backend/execute-code";
11
12
interface ParserOptions {
13
parser: string;
14
}
15
16
// ref: man biber
17
18
async function biber(input_path, output_path) {
19
const args = [
20
"--tool",
21
"--output-align",
22
"--output-indent=2",
23
"--output-fieldcase=lower",
24
"--output-file",
25
output_path,
26
input_path,
27
];
28
29
return await executeCode({
30
command: "biber",
31
args: args,
32
err_on_exit: false,
33
bash: false,
34
timeout: 20,
35
});
36
}
37
38
export async function bib_format(
39
input: string,
40
options: ParserOptions,
41
logger: any
42
): Promise<string> {
43
// create input temp file
44
const input_path: string = await callback(tmp.file);
45
const output_path: string = await callback(tmp.file);
46
try {
47
await callback(writeFile, input_path, input);
48
49
// spawn the bibtex formatter
50
let bib_formatter;
51
try {
52
switch (options.parser) {
53
case "bib-biber":
54
bib_formatter = await biber(input_path, output_path);
55
break;
56
default:
57
throw Error(`Unknown XML formatter utility '${options.parser}'`);
58
}
59
} catch (e) {
60
logger.debug(`Calling Bibtex formatter raised ${e}`);
61
throw new Error(
62
`Bibtex formatter broken or not available. Is '${options.parser}' installed?`
63
);
64
}
65
66
const { exit_code, stdout, stderr } = bib_formatter;
67
const code = exit_code;
68
69
const problem = code >= 1;
70
if (problem) {
71
const msg = `Bibtex formatter "${options.parser}" exited with code ${code}\nOutput:\n${stdout}\n${stderr}`;
72
throw Error(msg);
73
}
74
75
// all fine, we read from the temp file
76
const output: Buffer = await callback(readFile, output_path);
77
const s: string = output.toString("utf-8");
78
return s;
79
} finally {
80
// logger.debug(`bibtex formatter done, unlinking ${input_path}`);
81
unlink(input_path, () => {});
82
unlink(output_path, () => {});
83
}
84
}
85
86