Drop lots of legacy code. Support Python 3.7-3.11.
[librarian.git] / src / librarian / command_line.py
1 # This file is part of Librarian, licensed under GNU Affero GPLv3 or later.
2 # Copyright © Fundacja Wolne Lektury. See NOTICE for more information.
3 #
4 import argparse
5 import os.path
6 from .builders import builders
7 from .document import WLDocument
8
9
10 def main(*args, **kwargs):
11     parser = argparse.ArgumentParser(description="PARSER DESCRIPTION")
12
13     parser.add_argument(
14         'builder',
15         choices=builders.keys(),
16         help="Builder"
17     )
18     parser.add_argument('input_file')
19     parser.add_argument(
20         '-o', '--output-file', metavar='FILE',
21         help='specifies the output file'
22     )
23     parser.add_argument(
24         '-O', '--output-dir', metavar='DIR',
25         help='specifies the directory for output'
26     )
27
28     # Specific 
29     parser.add_argument(
30         '-b', '--base-url', metavar="URL",
31         help="Base for relative URLs in documents (like image sources)"
32     )
33
34     parser.add_argument(
35         '--mp3',
36         metavar="FILE",
37         nargs="*",
38         help='specifies an MP3 file, if needed'
39     )
40
41     args = parser.parse_args()
42     builder = builders[args.builder]
43
44     if args.output_file:
45         output_file_path = args.output_file
46     else:
47         output_file_path = '.'.join((
48             os.path.splitext(args.input_file)[0],
49             builder.file_extension
50         ))
51         if args.output_dir:
52             output_file_path = '/'.join((
53                 args.output_dir,
54                 output_file_path.rsplit('/', 1)[-1]
55             ))
56
57     document = WLDocument(filename=args.input_file)
58
59     builder = builders[args.builder]
60     kwargs = {
61         "mp3": args.mp3,
62     }
63
64     output = document.build(builder, base_url=args.base_url, **kwargs)
65     with open(output_file_path, 'wb') as f:
66         f.write(output.get_bytes())