Feat: from optparse to click

This commit is contained in:
Bertrand Benjamin 2019-12-23 09:10:42 +01:00
parent 39785cb617
commit b40b114bb4
2 changed files with 121 additions and 119 deletions

View File

@ -2,11 +2,101 @@
# encoding: utf-8 # encoding: utf-8
from .bopytex import main import click
import logging
from .bopytex import produce_and_compile
main() formatter = logging.Formatter("%(name)s :: %(levelname)s :: %(message)s")
steam_handler = logging.StreamHandler()
steam_handler.setLevel(logging.DEBUG)
steam_handler.setFormatter(formatter)
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
logger.addHandler(steam_handler)
@click.command()
@click.argument(
"template",
type=click.Path(exists=True),
nargs=1,
#help="File with the template. The name should have the following form tpl_... .",
)
@click.option(
"-w",
"--working-dir",
type=click.Path(exists=True),
help="Where fed templates and compiled files will be placed",
)
@click.option(
"-s",
"--students-csv",
type=str,
default='',
help="CSV containing list of students names",
)
@click.option(
"-d",
"--dirty",
is_flag=True,
default=False,
help="Do not clean after compilation",
)
@click.option(
"-n",
"--no-compile",
is_flag=True,
default=False,
help="Do not compile source code",
)
@click.option(
"-N",
"--number_subjects",
type=int,
default=1,
help="The number of subjects to make",
)
@click.option(
"-j",
"--no-join",
is_flag=True,
default=False,
help="Do not join pdfs to a single pdf and remove individuals",
)
@click.option(
"-O",
"--only-corr",
is_flag=True,
default=False,
help="Create and compile only correction from existing subjects",
)
@click.option(
"-c",
"--corr",
is_flag=True,
default=False,
help="Create and compile correction while making subjects",
)
@click.option(
"-C",
"--crazy",
is_flag=True,
default=False,
help="Crazy mode. Tries and tries again until template feeding success!",
)
def cli(**options):
""" Bopytex
Feed the template (tpl_...) and then compile it with latex.
"""
logger.debug(f"CI parser gets {options}")
produce_and_compile(options)
if __name__ == "__main__":
cli()
# ----------------------------- # -----------------------------
# Reglages pour 'vim' # Reglages pour 'vim'
# vim:set autoindent expandtab tabstop=4 shiftwidth=4: # vim:set autoindent expandtab tabstop=4 shiftwidth=4:

View File

@ -8,10 +8,8 @@ Producing then compiling templates
import csv import csv
import os import os
import logging import logging
import optparse
import sys
from path import Path from pathlib import Path
import pytex import pytex
from mapytex import Expression, Integer, Decimal from mapytex import Expression, Integer, Decimal
import bopytex.filters as filters import bopytex.filters as filters
@ -47,18 +45,18 @@ def setup():
def get_working_dir(options): def get_working_dir(options):
""" Get the working directory """ """ Get the working directory """
if options.working_dir: if options["working_dir"]:
working_dir = Path(options.working_dir) working_dir = Path(options["working_dir"])
else: else:
try: try:
template = Path(options.template) template = Path(options["template"])
except TypeError: except TypeError:
raise ValueError( raise ValueError(
"Need to set the working directory \ "Need to set the working directory \
or to give a template" or to give a template"
) )
else: else:
working_dir = template.dirname() working_dir = template.parent
logger.debug(f"The output directory will be {working_dir}") logger.debug(f"The output directory will be {working_dir}")
return working_dir return working_dir
@ -113,39 +111,48 @@ def produce_and_compile(options):
""" """
working_dir = get_working_dir(options) working_dir = get_working_dir(options)
if options.only_corr: if options["only_corr"]:
options.corr = True options["corr"] = True
tex_files = working_dir.files("[0-9]*_*.tex") tex_files = working_dir.files("[0-9]*_*.tex")
else: else:
template = Path(options.template).name template = Path(options["template"]).name
logger.debug(f"Template will be {template}") logger.debug(f"Template will be {template}")
if options.student_csv: if options["students_csv"]:
list_infos = [ list_infos = [
{"num": f"{i+1:02d}", "name": s} {"num": f"{i+1:02d}", "name": s}
for (i, s) in enumerate(extract_student_csv(options.student_csv)) for (i, s) in enumerate(extract_student_csv(options["students_csv"]))
] ]
else: else:
list_infos = [{"num": f"{i+1:02d}"} for i in range(options.num_subj)] list_infos = [
{"num": f"{i+1:02d}"} for i in range(options["number_subjects"])
]
tex_files = [] tex_files = []
for infos in list_infos: for infos in list_infos:
dest = working_dir / Path(template.replace("tpl", infos["num"])) dest = working_dir / Path(template.replace("tpl", infos["num"]))
logger.debug(f"Feeding template toward {dest}") logger.debug(f"Feeding template toward {dest}")
tex_files.append(dest) tex_files.append(dest)
if options.crazy: if options["crazy"]:
while True: while True:
try: try:
pytex.feed(working_dir / template, {"infos": infos}, output=dest, force=1) pytex.feed(
working_dir / template,
{"infos": infos},
output=dest,
force=1,
)
except: except:
pass pass
else: else:
break break
else: else:
pytex.feed(working_dir / template, {"infos": infos}, output=dest, force=1) pytex.feed(
working_dir / template, {"infos": infos}, output=dest, force=1
)
logger.debug(f"{dest} fed") logger.debug(f"{dest} fed")
if not options.no_compil: if not options["no_compil"]:
pdf_files = [] pdf_files = []
for texfile in tex_files: for texfile in tex_files:
logger.debug(f"Start compiling {texfile}") logger.debug(f"Start compiling {texfile}")
@ -154,7 +161,7 @@ def produce_and_compile(options):
pdf_files.append(str(texfile[:-4] + ".pdf")) pdf_files.append(str(texfile[:-4] + ".pdf"))
logger.debug(f"Compiled files : {pdf_files}") logger.debug(f"Compiled files : {pdf_files}")
if not options.no_join and not options.no_compil: if not options["no_join"] and not options["no_compil"]:
pdfjoin( pdfjoin(
pdf_files, pdf_files,
template.replace("tpl", "all").replace(".tex", ".pdf"), template.replace("tpl", "all").replace(".tex", ".pdf"),
@ -162,18 +169,18 @@ def produce_and_compile(options):
rm_pdfs=1, rm_pdfs=1,
) )
if options.corr: if options["corr"]:
pdf_files = [] pdf_files = []
for texfile in tex_files: for texfile in tex_files:
corr_fname = activate_printanswers(texfile) corr_fname = activate_printanswers(texfile)
if not options.no_compil: if not options["no_compil"]:
logger.debug(f"Start compiling {texfile}") logger.debug(f"Start compiling {texfile}")
pytex.pdflatex(corr_fname) pytex.pdflatex(corr_fname)
logger.debug(f"End compiling {texfile}") logger.debug(f"End compiling {texfile}")
pdf_files.append(str(corr_fname[:-4] + ".pdf")) pdf_files.append(str(corr_fname[:-4] + ".pdf"))
deactivate_printanswers(corr_fname) deactivate_printanswers(corr_fname)
if not options.no_join and not options.no_compil: if not options["no_join"] and not options["no_compil"]:
pdfjoin( pdfjoin(
pdf_files, pdf_files,
template.replace("tpl", "corr").replace(".tex", ".pdf"), template.replace("tpl", "corr").replace(".tex", ".pdf"),
@ -181,105 +188,10 @@ def produce_and_compile(options):
rm_pdfs=1, rm_pdfs=1,
) )
if not options.dirty: if not options["dirty"]:
pytex.clean(working_dir) pytex.clean(working_dir)
def main():
setup()
parser = optparse.OptionParser()
parser.add_option(
"-t",
"--template",
action="store",
type="string",
dest="template",
help="File with the template. The name should have the following form tpl_... .",
)
parser.add_option(
"-w",
"--working-dir",
action="store",
type="string",
dest="working_dir",
help="Where fed templates and compiled files will be placed",
)
parser.add_option(
"-N",
"--number_subjects",
action="store",
type="int",
dest="num_subj",
default=1,
help="The number of subjects to make",
)
parser.add_option(
"-s",
"--students",
action="store",
type="string",
dest="student_csv",
help="CSV containing list of students names",
)
parser.add_option(
"-d",
"--dirty",
action="store_true",
dest="dirty",
help="Do not clean after compilation",
)
parser.add_option(
"-n",
"--no-compile",
action="store_true",
dest="no_compil",
help="Do not compile source code",
)
parser.add_option(
"-j",
"--no-join",
action="store_true",
dest="no_join",
help="Do not join pdf and clean single pdf",
)
parser.add_option(
"-O",
"--only-corr",
action="store_true",
dest="only_corr",
help="Create and compile only correction from existing subjects",
)
parser.add_option(
"-c",
"--corr",
action="store_true",
dest="corr",
help="Create and compile correction while making subjects",
)
parser.add_option(
"-C",
"--crazy",
action="store_true",
dest="crazy",
help="Crazy mode. Tries and tries again until template feeding success!",
)
(options, _) = parser.parse_args()
logger.debug(f"CI parser gets {options}")
if not options.template:
print("I need a template!")
sys.exit(0)
produce_and_compile(options)
if __name__ == "__main__":
main()
# ----------------------------- # -----------------------------
# Reglages pour 'vim' # Reglages pour 'vim'
# vim:set autoindent expandtab tabstop=4 shiftwidth=4: # vim:set autoindent expandtab tabstop=4 shiftwidth=4: