diff --git a/lib/pandoc.js b/lib/pandoc.js index 337949091932b6860fe06d7781be1e2e19405136..9f2b1fabc22b8fe1c8e2b68f7c41a2df85badd1a 100644 --- a/lib/pandoc.js +++ b/lib/pandoc.js @@ -39,6 +39,46 @@ export function getRevealJSResolver(url) { return (output) => path.relative(path.dirname(output.relative), url); } +/** + * @param {import("vinyl")} input + * @param {string} path + * @return {Promise<void>|never} + * @throws PluginError + */ +async function writeToDisk(input, path) { + if (input.isStream()) { + const write = fs.createWriteStream(path); + const done = new Promise((resolve, reject) => { + write.on("close", () => resolve()); + input.on("error", reject); + write.on("error", reject); + }); + input.contents.pipe(write); + return done; + } + + if (input.isBuffer()) { + return writeFile(path, input.contents, {}); + } + + throw new PluginError(PLUGIN_NAME, `cannot handle input ${input.inspect()}`); +} + +/** + * @param {import("vinyl")} input + * @return {import("vinyl")} + * @throws PluginError + */ +async function onDisk(input) { + if (await exists(input.path)) { + return input; + } + + const tmpFile = await mkTempFile(input); + await writeToDisk(input, tmpFile.path); + return tmpFile; +} + export default function pandoc(options = {}) { const { slideLevel, tocDepth, revealJSURL, variables } = merge( {}, @@ -57,31 +97,7 @@ export default function pandoc(options = {}) { output.extname = ".html"; output.contents = null; - if (!(await exists(input.path))) { - const tmpFile = await mkTempFile(input); - if (input.isStream()) { - const write = fs.createWriteStream(tmpFile.path); - try { - const done = new Promise((resolve, reject) => { - write.on("close", () => resolve()); - input.on("error", reject); - write.on("error", reject); - }); - input.contents.pipe(write); - await done; - } finally { - write.close(); - } - } else if (input.isBuffer()) { - await writeFile(tmpFile.path, input.contents, {}); - } else { - throw new PluginError( - PLUGIN_NAME, - `cannot handle input ${input.inspect()}` - ); - } - input = tmpFile; - } + const src = await onDisk(input); const args = [ "--from=markdown+backtick_code_blocks+pandoc_title_block+yaml_metadata_block", @@ -94,7 +110,7 @@ export default function pandoc(options = {}) { ...Object.getOwnPropertyNames(variables).map( (name) => `--variable=${name}:${variables[name]}` ), - input.path, + src.path, ]; const { stdout } = await exec(PLUGIN_NAME, "pandoc", args, {