Files
monorepo/src-py/renatoxsr/utils/pandoc.py
T

45 lines
1.5 KiB
Python

#!/usr/bin/env python3
# vim: set ft=python ts=4 sw=4 et encoding=utf-8 :
# SPDX-FileCopyrightText: 2025-present RenatoXSR <renatoxsr@gmail.com>
# SPDX-License-Identifier: BSD-3-Clause-Clear
import errno, os, shutil, subprocess, sys
from pathlib import Path
from renatoxsr.logger import set_logger
logger = set_logger(__name__)
if "--debug" in sys.argv:
logger.setLevel("DEBUG")
def pandoc(
input_file: str | Path,
bin: str | Path = "pandoc",
output: str | Path = "-",
overwrite = False,
to="markdown",
) -> str:
logger.info("%s: from '%s' to '%s'", bin, input_file, output)
if not Path(bin).is_file():
which_bin = shutil.which(bin)
if not Path(which_bin).is_file():
raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT), bin)
fpath = Path(input_file)
if not fpath.is_file():
raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT), input_file)
outf = Path(output)
if output != "-" and outf.is_file() and not overwrite:
raise FileExistsError(errno.EEXIST, os.strerror(errno.EEXIST), outf)
cmd = [bin,
"--output", "-" if output=="-" else outf.resolve(),
"--write", to, fpath]
logger.debug("CMD %s", str(cmd))
proc = subprocess.run(cmd, text=True)
if proc.stderr:
logger.error(proc.stderr)
if proc.stdout and output != "-":
logger.info(proc.stdout)
else:
return(proc.stdout)