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)
50 action='store_true', dest='verbose', default=False,
51 help='print status messages to stdout')
53 '-o', '--output-file',
54 dest='output_file', metavar='FILE',
55 help='specifies the output file')
56 for option in cls.document_options + cls.format_options + cls.build_options:
59 options, input_filenames = parser.parse_args()
61 if len(input_filenames) < 1:
65 # Prepare additional args for document.
67 for option in cls.document_options:
68 document_args[option.name()] = option.value(options)
69 # Prepare additional args for format.
71 for option in cls.format_options:
72 format_args[option.name()] = option.value(options)
73 # Prepare additional args for build.
75 for option in cls.build_options:
76 build_args[option.name()] = option.value(options)
80 for main_input in input_filenames:
84 # Do the transformation.
85 doc = Document.from_file(main_input, **document_args)
86 format_ = cls.format_cls(doc, **format_args)
88 # Where to write output?
89 if not options.output_file:
90 output_file = os.path.splitext(main_input)[0] + '.' + format_.format_ext
94 output = format_.build(**build_args)
95 output.save_as(output_file)
98 print '%(file)s:%(name)s:%(message)s' % {
100 'name': e.__class__.__name__,