]> git.lyx.org Git - lyx.git/blob - lib/scripts/docbook2epub.py
ePub: don't use glob.
[lyx.git] / lib / scripts / docbook2epub.py
1 # -*- coding: utf-8 -*-
2
3 # file docbook2epub.py
4 # This file is part of LyX, the document processor.
5 # Licence details can be found in the file COPYING.
6 #
7 # \author Thibaut Cuvelier
8 #
9 # Full author contact details are available in file CREDITS
10
11 # Usage:
12 #   python docbook2epub.py in.docbook out.epub
13
14 from __future__ import print_function
15
16 # import glob  # Not powerful enough before Python 3.5.
17 import os
18 import shutil
19 import sys
20 import tempfile
21 import zipfile
22
23 if __name__ == '__main__':
24     if len(sys.argv) != 4:
25         sys.exit(1)
26     own_path, java_path, input, output = sys.argv
27     script_folder = os.path.dirname(own_path) + '/../'
28
29     print('Generating ePub:')
30     print(own_path)
31     print(input)
32     print(output)
33
34     output_dir = tempfile.mkdtemp().replace('\\', '/')
35     print('Temporary output directory:')
36     print(output_dir)
37
38     # Start the XSLT transformation.
39     xslt = script_folder + 'docbook/epub3/chunk.xsl'
40     saxon_jar = script_folder + 'scripts/saxon6.5.5.jar'
41     saxon_params = 'base.dir=%s' % output_dir
42     command = '"' + java_path + '" -jar "' + saxon_jar + '" ' + input + ' ' + xslt + ' ' + saxon_params
43
44     print('XSLT style sheet to use:')
45     print(xslt)
46     print('Command to execute:')
47     print(command)
48
49     quoted_command = command
50     if os.name == 'nt':
51         # On Windows, it is typical to have spaces in folder names, and that requires to wrap the whole command
52         # in quotes. On Linux, this might create errors when starting the command.
53         quoted_command = '"' + command + '"'
54
55     if os.system(quoted_command) != 0:
56         print('docbook2epub fails')
57         shutil.rmtree(output_dir, ignore_errors=True)
58         sys.exit(1)
59
60     print('Generated ePub contents.')
61
62     # TODO: Copy the assets to the OEBPS/images/.
63
64     # Create the actual ePub file.
65     with zipfile.ZipFile(output, 'w', zipfile.ZIP_DEFLATED) as zip:
66         # Python 3.5 brings the `recursive` argument. For older versions, this trick is required...
67         # for file in glob.glob(output_dir + '/**/*', recursive=True):
68         for file in [os.path.join(dp, f) for dp, dn, filenames in os.walk(output_dir) for f in filenames]:
69             zip.write(file, os.path.relpath(file, output_dir), compress_type=zipfile.ZIP_STORED)
70
71     shutil.rmtree(output_dir)
72     print('Generated ePub.')