Overrides test in feed

This commit is contained in:
Benjamin Bertrand 2017-04-16 16:58:36 +03:00
parent ca0eb160a5
commit 710928869d
2 changed files with 15 additions and 6 deletions

View File

@ -2,6 +2,7 @@
# encoding: utf-8
from .texenv import texenv
from .pytex import *
# -----------------------------
# Reglages pour 'vim'

View File

@ -28,25 +28,33 @@ def update_export_dict(new_dict):
EXPORT_DICT.update(new_dict)
def feed(template, data, output, force=0):
def feed(template, data, output="", force=0):
""" Feed template with data to output
:param template: jinja2 template with textenv environment
:param data: Data dictionnary
:param output: name of the output file
(by default: tpl is replaced by a 2 digits number)
:param force: Override is the output already exists
"""
logger.info(f"Getting template {template}")
tpl = texenv.get_template(template)
output_p = Path(output)
if not output:
num = 1
output_p = Path(template).replace('tpl', f'{num:02d}')
while output.exists() or not force:
logger.debug(f"{output_p} exists. Try next one")
num += 1
output_p = Path(template).replace('tpl', f'{num:02d}')
elif not force:
logger.error(f"{output} exists. Use force=1 do override it")
raise ValueError(f"{output} exists. Use force=1 do override it")
output_dir = output_p.dirname()
if not output_dir.exists():
output_dir.mkdir()
if output_p.exists() and not force:
logger.error(f"{output} exists. Use force=1 do override it")
raise ValueError(f"{output} exists. Use force=1 do override it")
with open(output, "w") as output_f:
output_f.write(tpl.render(**EXPORT_DICT, **data))
logger.info(f"{template} has been rendered to {output}.")