Coverage for pyquickhelper/helpgen/pandoc_helper.py: 92%
24 statements
« prev ^ index » next coverage.py v7.2.7, created at 2023-06-03 02:21 +0200
« prev ^ index » next coverage.py v7.2.7, created at 2023-06-03 02:21 +0200
1"""
2@file
3@brief Helpers to call pandoc and convert documents
4"""
5import os
6from .conf_path_tools import find_pandoc_path
7from ..loghelper import noLOG, run_cmd
10def call_pandoc(params, fLOG=noLOG):
11 """
12 Call :epkg:`pandoc`.
14 @param params parameters
15 @param fLOG logging function
16 @return out, err
17 """
18 pandoc = os.path.join(find_pandoc_path(), "pandoc")
19 cmd = f'"{pandoc}" {params}'
20 out, err = run_cmd(cmd, wait=True, fLOG=fLOG)
21 if err is not None and "Cannot decode byte" in err:
22 raise RuntimeError( # pragma: no cover
23 f"Issue with pandoc:\n{cmd}\n--OUT--\n{out}\n--ERR--\n{err}")
24 return out, err
27def latex2rst(input, output, encoding="utf-8", fLOG=noLOG, temp_file=None):
28 """
29 convert a latex document into a rst document using pandoc
31 @param input input file
32 @param output output file
33 @param encoding encoding
34 @param temp_file temporary file
35 @param fLOG logging function
36 @return see @see fn call_pandoc
38 If the encoding is not utf-8, the function uses *temp_file* to store
39 the temporary conversion into utf-8.
40 """
41 if encoding not in ("utf-8", "utf8"):
42 with open(input, "r", encoding=encoding) as f:
43 content = f.read()
44 if temp_file is None:
45 raise ValueError("temp_file cannot be None, encoding is not utf-8 and a temporary " +
46 "file will be used to do the conversion.")
47 with open(temp_file, "w", encoding="utf-8") as f:
48 f.write(content)
49 input = temp_file
50 else:
51 temp_file = None
52 cmd = f'-s -t rst --toc "{input}" -o "{output}"'
53 out, err = call_pandoc(cmd, fLOG=fLOG)
54 if temp_file is not None:
55 os.remove(temp_file)
56 return out, err