2 # -*- coding: utf-8 -*-
4 # This file is part of Librarian, licensed under GNU Affero GPLv3 or later.
5 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
10 from librarian import ParseError
11 from librarian.document import Document
15 """Option for optparse. Use it like `optparse.OptionParser.add_option`."""
16 def __init__(self, *names, **options):
18 self.options = options
20 def add(self, parser):
21 parser.add_option(*self.names, **self.options)
24 return self.options['dest']
26 def value(self, options):
27 return getattr(options, self.name())
30 class Book2Anything(object):
31 """A class for creating book2... scripts.
33 Subclass it for any format you want to convert to.
35 format_cls = None # A formats.Format subclass
36 document_options = [] # List of Option objects for document options.
37 format_options = [] # List of Option objects for format customization.
38 build_options = [] # List of Option objects for build options.
42 # Parse commandline arguments
43 usage = """Usage: %%prog [options] SOURCE [SOURCE...]
44 Convert SOURCE files to %s.""" % cls.format_cls.format_name
46 parser = optparse.OptionParser(usage=usage)
48 parser.add_option('-v', '--verbose',
49 action='store_true', dest='verbose', default=False,
50 help='print status messages to stdout')
51 parser.add_option('-o', '--output-file',
52 dest='output_file', metavar='FILE',
53 help='specifies the output file')
54 for option in cls.document_options + cls.format_options + cls.build_options:
57 options, input_filenames = parser.parse_args()
59 if len(input_filenames) < 1:
63 # Prepare additional args for document.
65 for option in cls.document_options:
66 document_args[option.name()] = option.value(options)
67 # Prepare additional args for format.
69 for option in cls.format_options:
70 format_args[option.name()] = option.value(options)
71 # Prepare additional args for build.
73 for option in cls.build_options:
74 build_args[option.name()] = option.value(options)
78 for main_input in input_filenames:
82 # Do the transformation.
83 doc = Document.from_file(main_input, **document_args)
84 format_ = cls.format_cls(doc, **format_args)
86 # Where to write output?
87 if not options.output_file:
88 output_file = os.path.splitext(main_input)[0] + '.' + format_.format_ext
92 output = format_.build(**build_args)
93 output.save_as(output_file)
96 print '%(file)s:%(name)s:%(message)s' % {
98 'name': e.__class__.__name__,