Browse Source

Added --steps command line option

pull/20/head
Louis 11 years ago
parent
commit
038e0ecc15
  1. 34
      songbook
  2. 67
      songbook_core/build.py
  3. 11
      songbook_core/errors.py

34
songbook

@ -12,11 +12,21 @@ import os.path
import textwrap import textwrap
import sys import sys
from songbook_core.build import buildsongbook from songbook_core.build import buildsongbook, DEFAULT_STEPS
from songbook_core import __STR_VERSION__ from songbook_core import __STR_VERSION__
from songbook_core import errors from songbook_core import errors
# pylint: disable=too-few-public-methods
class ParseStepsAction(argparse.Action):
"""Argparse action to split a string into a list."""
def __call__(self, __parser, namespace, values, __option_string=None):
setattr(
namespace,
self.dest,
[value.strip() for value in values[0].split(',')],
)
def argument_parser(args): def argument_parser(args):
"""Parse argumnts""" """Parse argumnts"""
parser = argparse.ArgumentParser(description="A song book compiler") parser = argparse.ArgumentParser(description="A song book compiler")
@ -34,6 +44,19 @@ def argument_parser(args):
subdirectories are 'songs', 'img', 'latex', 'templates'. subdirectories are 'songs', 'img', 'latex', 'templates'.
""")) """))
parser.add_argument('--steps', '-s', nargs=1, type=str,
action=ParseStepsAction,
help=textwrap.dedent("""\
Steps to run. Default is "{steps}".
Available steps are:
"tex" produce .tex file from templates;
"pdf" compile .tex file;
"sbx" compile index files;
"clean" remove temporary files.
""".format(steps=','.join(DEFAULT_STEPS))),
default=DEFAULT_STEPS,
)
options = parser.parse_args(args) options = parser.parse_args(args)
return options return options
@ -71,8 +94,15 @@ def main():
) )
else: else:
songbook['datadir'] = os.path.dirname(songbook_path) songbook['datadir'] = os.path.dirname(songbook_path)
try: try:
buildsongbook(songbook, basename, interactive=True, logger=logger) buildsongbook(
songbook,
basename,
steps=options.steps,
interactive=True,
logger=logger,
)
except errors.SongbookError as error: except errors.SongbookError as error:
logger.error(error) logger.error(error)
sys.exit(1) sys.exit(1)

67
songbook_core/build.py

@ -23,6 +23,7 @@ DEFAULT_AUTHWORDS = {
"ignore": ["unknown"], "ignore": ["unknown"],
"sep": ["and"], "sep": ["and"],
} }
DEFAULT_STEPS = ['tex', 'pdf', 'sbx', 'pdf', 'clean']
# pylint: disable=too-few-public-methods # pylint: disable=too-few-public-methods
@ -137,31 +138,38 @@ def clean(basename):
] ]
for ext in generated_extensions: for ext in generated_extensions:
try: if os.path.isfile(basename + ext):
os.unlink(basename + ext) try:
except Exception as exception: os.unlink(basename + ext)
raise errors.CleaningError(basename + ext, exception) except Exception as exception:
raise errors.CleaningError(basename + ext, exception)
def buildsongbook( def buildsongbook(
raw_songbook, raw_songbook,
basename, basename,
steps=None,
interactive=False, interactive=False,
logger=logging.getLogger() logger=logging.getLogger(),
): ):
"""Build a songbook """Build a songbook
Arguments: Arguments:
- raw_songbook: Python representation of the .sb songbook configuration - raw_songbook: Python representation of the .sb songbook configuration
file. file.
- steps: list of steps to perform to compile songbook. Available steps are:
- tex: build .tex file from templates;
- pdf: compile .tex using pdflatex;
- sbx: compile song and author indexes;
- clean: remove temporary files.
- basename: basename of the songbook to be built. - basename: basename of the songbook to be built.
- interactive: in False, do not expect anything from stdin. - interactive: in False, do not expect anything from stdin.
""" """
songbook = Songbook(raw_songbook, basename) if steps is None:
with codecs.open("{}.tex".format(basename), 'w', 'utf-8') as output: steps = DEFAULT_STEPS
songbook.write_tex(output)
songbook = Songbook(raw_songbook, basename)
if not 'TEXINPUTS' in os.environ.keys(): if not 'TEXINPUTS' in os.environ.keys():
os.environ['TEXINPUTS'] = '' os.environ['TEXINPUTS'] = ''
os.environ['TEXINPUTS'] += os.pathsep + os.path.join( os.environ['TEXINPUTS'] += os.pathsep + os.path.join(
@ -179,22 +187,27 @@ def buildsongbook(
if not interactive: if not interactive:
pdflatex_options.append("-halt-on-error") pdflatex_options.append("-halt-on-error")
# First pdflatex pass # Compilation
if subprocess.call(["pdflatex"] + pdflatex_options + [basename]): for step in steps:
raise errors.LatexCompilationError(basename) if step == 'tex':
# Building .tex file from templates
# Make index with codecs.open("{}.tex".format(basename), 'w', 'utf-8') as output:
sxd_files = glob.glob("%s_*.sxd" % basename) songbook.write_tex(output)
for sxd_file in sxd_files: elif step == 'pdf':
logger.info("processing " + sxd_file) if subprocess.call(["pdflatex"] + pdflatex_options + [basename]):
idx = process_sxd(sxd_file) raise errors.LatexCompilationError(basename)
index_file = open(sxd_file[:-3] + "sbx", "w") elif step == 'sbx':
index_file.write(idx.entries_to_str().encode('utf8')) # Make index
index_file.close() sxd_files = glob.glob("%s_*.sxd" % basename)
for sxd_file in sxd_files:
# Second pdflatex pass logger.info("processing " + sxd_file)
if subprocess.call(["pdflatex"] + pdflatex_options + [basename]): idx = process_sxd(sxd_file)
raise errors.LatexCompilationError(basename) index_file = open(sxd_file[:-3] + "sbx", "w")
index_file.write(idx.entries_to_str().encode('utf8'))
# Cleaning index_file.close()
clean(basename) elif step == 'clean':
# Cleaning
clean(basename)
else:
# Unknown step name
raise errors.UnknownStep(step)

11
songbook_core/errors.py

@ -36,3 +36,14 @@ class CleaningError(SongbookError):
filename=self.filename, filename=self.filename,
exception=str(self.exception) exception=str(self.exception)
) )
class UnknownStep(SongbookError):
"""Unknown compilation step."""
def __init__(self, step):
super(UnknownStep, self).__init__()
self.step = step
def __str__(self):
return """Compilation step "{step}" unknown.""".format(step=self.step)

Loading…
Cancel
Save