UNPKG

myst-cli

Version:
73 lines (72 loc) 2.59 kB
import fs from 'node:fs'; import path from 'node:path'; import { castSession } from '../../session/cache.js'; import { addWarningForFile } from '../../utils/addWarningForFile.js'; /** * Write new bibtex file from citation renderer data and reference order * * Returns true if file was written */ export function writeBibtexFromCitationRenderers(session, output, content) { const order = content .map(({ references }) => { var _a, _b; return (_b = (_a = references.cite) === null || _a === void 0 ? void 0 : _a.order) !== null && _b !== void 0 ? _b : []; }) .flat(); if (!order.length) return false; const cache = castSession(session); const citationLookup = {}; Object.values(cache.$citationRenderers).forEach((renderers) => { Object.entries(renderers).forEach(([key, renderer]) => { citationLookup[key] = renderer.exportBibTeX(); }); }); const bibtexContent = []; order.forEach((key) => { if (bibtexContent.includes(citationLookup[key])) return; if (citationLookup[key]) { bibtexContent.push(citationLookup[key]); } else { addWarningForFile(session, output, `unknown citation ${key}`); } }); if (!bibtexContent.length) return false; if (!fs.existsSync(output)) fs.mkdirSync(path.dirname(output), { recursive: true }); fs.writeFileSync(output, bibtexContent.join('\n')); return true; } /** * Write new bibtex file with all remotely loaded DOI bibtex entries * * This bibtex file is unordered and includes a header indicating it may be * overwritten. * * Returns true if file was written */ export function writeRemoteDOIBibtex(session, output) { var _a; const cache = castSession(session); const bibtexContent = []; // Keep existing myst.doi.bib entries Object.values((_a = cache.$citationRenderers[output]) !== null && _a !== void 0 ? _a : {}).forEach((render) => { bibtexContent.push(render.exportBibTeX()); }); Object.values(cache.$doiRenderers).forEach(({ render, remote }) => { if (!remote) return; bibtexContent.push(render.exportBibTeX()); }); if (!bibtexContent.length) return false; bibtexContent.unshift('% AUTOGENERATED FILE - EDITS MAY BE LOST\n% To regenerate, run `myst build --doi-bib`\n'); if (!fs.existsSync(output)) fs.mkdirSync(path.dirname(output), { recursive: true }); fs.writeFileSync(output, bibtexContent.join('\n')); return true; }