Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def test_get_pandoc_version(self):
assert "HOME" in os.environ, "No HOME set, this will error..."
version = pypandoc.get_pandoc_version()
self.assertTrue(isinstance(version, pypandoc.string_types))
major = int(version.split(".")[0])
# according to http://pandoc.org/releases.html there were only two versions 0.x ...
self.assertTrue(major in [0, 1, 2])
def has_pandoc(): # pragma: no cover
try:
import pypandoc
pypandoc.get_pandoc_version()
return True
except ImportError:
logger.debug("pypandoc is not installed.")
except FileNotFoundError:
logger.debug("pandoc is not installed.")
return False
def download_pandoc():
"""Download pandoc if not already installed"""
try:
# Check whether it is already installed
pypandoc.get_pandoc_version()
except OSError:
# Pandoc not installed. Let's download it silently.
with open(os.devnull, 'w') as devnull:
sys.stdout = devnull
pypandoc.download_pandoc()
sys.stdout = sys.__stdout__
# Hack to delete the downloaded file from the folder,
# otherwise it could get accidently committed to the repo
# by other scripts in the repo.
pf = sys.platform
if pf.startswith('linux'):
pf = 'linux'
url = pypandoc.pandoc_download._get_pandoc_urls()[0][pf]
filename = url.split('/')[-1]
os.remove(filename)
# render the template to a html string
template = get_template(template_src)
html = template.render(context)
# remove empty lines
html = os.linesep.join([line for line in html.splitlines() if line.strip()])
if format == 'html':
# create the response object
response = HttpResponse(html)
else:
if format == 'pdf':
# check pandoc version (the pdf arg changed to version 2)
if pypandoc.get_pandoc_version().split('.')[0] == '1':
args = ['-V', 'geometry:margin=1in', '--latex-engine=xelatex']
else:
args = ['-V', 'geometry:margin=1in', '--pdf-engine=xelatex']
content_disposition = 'filename="%s.%s"' % (title, format)
else:
args = []
content_disposition = 'attachment; filename="%s.%s"' % (title, format)
# use reference document for certain file formats
refdoc = set_export_reference_document(format)
if refdoc is not None and (format == 'docx' or format == 'odt'):
if pypandoc.get_pandoc_version().startswith("1"):
refdoc_param = '--reference-' + format + '=' + refdoc
args.extend([refdoc_param])
else:
temp_path = os.path.join(self.temp_root, base+EXTENSION)
self.log.debug('Creating temp file %s' % temp_path)
with io.open(temp_path, 'w', encoding='utf-8') as temp:
temp.write('\n'.join(markdown))
# extra arguments for pandoc
extra_args = ['--highlight-style', 'pygments', '-s', '-c', self.css,
'--template', self.template]
# use TOC if enabled
if self.info.use_TOC:
extra_args.append('--toc')
# use KaTex
if hasattr(pa, 'get_pandoc_version'):
version = LooseVersion(pa.get_pandoc_version())
if version < LooseVersion('1.13.2'):
self.log.warning("Pandoc version %s " % pa.get_pandoc_version(),
"has no support for KaTeX. Please install"
" at least version 1.13.2 for math support.")
else: # pragma: no cover
extra_args.append('--katex')
else: # pragma: no cover
self.log.warning("Pypandoc version is below 0.9.7, and does not "
"allow to check for Pandoc version. Please "
"update it with pip.")
# Apply pandoc to this markdown file, from pypandoc thin wrapper, and
# recover the html
html = pa.convert(temp_path, 'html', encoding='utf-8',
extra_args=extra_args)
def _has_pypandoc():
"""Check if pypandoc package available."""
try:
import pypandoc # noqa
# Import error raised only when function called
version = pypandoc.get_pandoc_version()
except (ImportError, OSError):
return None, None
else:
return True, version
def common_md():
print(f"Pandoc version: {pypandoc.get_pandoc_version()}")
print(f"Using docs directory: {DOCS_DIR}")
print(f"Using ops docs directory: {OP_DOCS_DIR}")
print()
html_op_list_template = env.get_template("html_op_list.jinja2.md")
html_op_table_template = env.get_template("html_op_table.jinja2.md")
pdf_op_table_template = env.get_template("pdf_op_table.jinja2.md")
pdf_op_extended_template = env.get_template("pdf_op_extended.jinja2.md")
intro = ""
intro += Path(DOCS_DIR / "intro.md") \
.read_text().replace("VERSION", TT_VERSION["tag"][1:]) + "\n\n"
intro += Path(DOCS_DIR / "whats_new.md").read_text() + "\n\n"
intro += Path(DOCS_DIR / "quickstart.md").read_text() + "\n\n"
intro += Path(DOCS_DIR / "keys.md").read_text() + "\n\n"
intro += Path(DOCS_DIR / "ops.md").read_text() + "\n\n"
with io.open(temp_path, 'w', encoding='utf-8') as temp:
temp.write('\n'.join(markdown))
# extra arguments for pandoc
extra_args = ['--highlight-style', 'pygments', '-s', '-c', self.css,
'--template', self.template]
# use TOC if enabled
if self.info.use_TOC:
extra_args.append('--toc')
# use KaTex
if hasattr(pa, 'get_pandoc_version'):
version = LooseVersion(pa.get_pandoc_version())
if version < LooseVersion('1.13.2'):
self.log.warning("Pandoc version %s " % pa.get_pandoc_version(),
"has no support for KaTeX. Please install"
" at least version 1.13.2 for math support.")
else: # pragma: no cover
extra_args.append('--katex')
else: # pragma: no cover
self.log.warning("Pypandoc version is below 0.9.7, and does not "
"allow to check for Pandoc version. Please "
"update it with pip.")
# Apply pandoc to this markdown file, from pypandoc thin wrapper, and
# recover the html
html = pa.convert(temp_path, 'html', encoding='utf-8',
extra_args=extra_args)
# Convert the windows ending of lines to simple line breaks (\r\n to
# \n)