From fec475b5ef949d168a61db2ac59077ec566ccce3 Mon Sep 17 00:00:00 2001 From: Louis Date: Wed, 7 Oct 2015 15:46:11 +0200 Subject: [PATCH] Added a command line tool to convert between file formats --- patacrep/songs/chordpro/__init__.py | 16 ++++++---- patacrep/songs/convert/__main__.py | 48 +++++++++++++++++++++++++++++ 2 files changed, 58 insertions(+), 6 deletions(-) create mode 100644 patacrep/songs/convert/__main__.py diff --git a/patacrep/songs/chordpro/__init__.py b/patacrep/songs/chordpro/__init__.py index 6d4c0e39..e5579d97 100644 --- a/patacrep/songs/chordpro/__init__.py +++ b/patacrep/songs/chordpro/__init__.py @@ -1,8 +1,9 @@ """Chordpro parser""" from jinja2 import Environment, FileSystemLoader, contextfunction -import pkg_resources +import jinja2 import os +import pkg_resources from patacrep import encoding, files from patacrep.songs import Song @@ -63,11 +64,14 @@ class ChordproSong(Song): jinjaenv.filters['search_image'] = self.search_image jinjaenv.filters['search_partition'] = self.search_partition - return Renderer( - template=template, - encoding='utf8', - jinjaenv=jinjaenv, - ).template.render(context) + try: + return Renderer( + template=template, + encoding='utf8', + jinjaenv=jinjaenv, + ).template.render(context) + except jinja2.exceptions.TemplateNotFound: + raise NotImplementedError() @staticmethod @contextfunction diff --git a/patacrep/songs/convert/__main__.py b/patacrep/songs/convert/__main__.py new file mode 100644 index 00000000..5271637f --- /dev/null +++ b/patacrep/songs/convert/__main__.py @@ -0,0 +1,48 @@ +"""Conversion between formats + +See the :meth:`__usage` method for more information. +""" + +import logging +import sys + +from patacrep.build import DEFAULT_CONFIG +from patacrep import files + +LOGGER = logging.getLogger(__name__) + +def __usage(): + return "python3 -m patacrep.songs.convert chordpro latex FILE" + +if __name__ == "__main__": + if len(sys.argv) != 4: + LOGGER.error("Invalid number of arguments.") + LOGGER.error("Usage: %s", __usage()) + sys.exit(1) + + source = sys.argv[1] + dest = sys.argv[2] + file = sys.argv[3] + + song_parsers = files.load_plugins( + datadirs=DEFAULT_CONFIG.get('datadir', []), + root_modules=['songs'], + keyword='SONG_PARSERS', + ) + + if source not in song_parsers: + LOGGER.error( + "Unknown file format '%s'. Available ones are %s.", + source, + ", ".join(["'{}'".format(key) for key in song_parsers.keys()]) + ) + sys.exit(1) + + song = song_parsers[source](".", file, DEFAULT_CONFIG) + try: + print(song.render(dest)) + except NotImplementedError: + LOGGER.error("Cannot convert to format '%s'.", dest) + sys.exit(1) + + sys.exit(0)