/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
4000.4.1 by Colin D Bennett
Generate PDF version of the User Guide.
1
#!/usr/bin/python
2
#
3
# Modify reStructuredText 'image' directives by adding a percentage 'width'
4
# attribute so that the images are scaled to fit on the page when the document
5
# is renderd to LaTeX, and add a center alignment.
4000.4.5 by Colin D Bennett
Strip trailing whitespace.
6
#
4000.4.1 by Colin D Bennett
Generate PDF version of the User Guide.
7
# Also convert references to PNG images to use PDF files generated from SVG
8
# files if available.
9
#
10
# Without the explicit size specification, the images are ridiculously huge and
11
# most extend far off the right side of the page.
12
#
13
# Copyright (C) 2009 Colin D Bennett
14
#
15
# This program is free software; you can redistribute it and/or modify
16
# it under the terms of the GNU General Public License as published by
17
# the Free Software Foundation; either version 2 of the License, or
18
# (at your option) any later version.
19
#
20
# This program is distributed in the hope that it will be useful,
21
# but WITHOUT ANY WARRANTY; without even the implied warranty of
22
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
23
# GNU General Public License for more details.
24
#
25
# You should have received a copy of the GNU General Public License
26
# along with this program; if not, write to the Free Software
4183.7.1 by Sabin Iacob
update FSF mailing address
27
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
4000.4.1 by Colin D Bennett
Generate PDF version of the User Guide.
28
7183.2.1 by Martin
Fix E999 lint error for Python 2 flake8
29
from __future__ import print_function
30
4000.4.1 by Colin D Bennett
Generate PDF version of the User Guide.
31
import os
32
import re
33
import shutil
34
import sys
35
from sys import argv
36
from subprocess import call
37
38
verbose = False
39
7322.2.1 by Martin
Fix invalid escape sequence warnings in regexps
40
IMAGE_DIRECTIVE_PATTERN = re.compile(u'^..\\s+image::\\s+(.*)\\`\\s+$')
7183.2.1 by Martin
Fix E999 lint error for Python 2 flake8
41
DIRECTIVE_ELEMENT_PATTERN = re.compile(u'^\\s+:[^:]+:\\s+')
4000.4.1 by Colin D Bennett
Generate PDF version of the User Guide.
42
43
class Converter(object):
44
    def __init__(self, srcdir, destdir):
45
        self.srcdir = srcdir
46
        self.destdir = destdir
47
48
    # Process .txt files in sourcedir, generating output in destdir.
49
    def process_files(self):
50
        for filename in os.listdir(self.srcdir):
51
            # Process all text files in the current directory.
52
            if filename.endswith('.txt'):
53
                inpath = os.path.join(self.srcdir, filename)
54
                outpath = os.path.join(self.destdir, filename)
55
                self._process_file(inpath, outpath)
56
57
    def _process_file(self, inpath, outpath):
58
        infile = open(inpath, 'r')
59
        outfile = open(outpath, 'w')
60
        foundimg = False
61
        for line in infile:
62
            if foundimg and DIRECTIVE_ELEMENT_PATTERN.match(line) is None:
63
                if verbose:
64
                    print('Fixing image directive')
65
                # The preceding image directive has no elements.
66
                outfile.write(' :width: 85%\n')
67
                outfile.write(' :align: center\n')
68
            foundimg = False
69
70
            image_fixer = ImageFixer(self.srcdir, self.destdir)
71
            image_fixer_lambda = lambda match: image_fixer.substitute_pdf_image(match)
72
            line = IMAGE_DIRECTIVE_PATTERN.sub(image_fixer_lambda, line)
73
            directive_match = IMAGE_DIRECTIVE_PATTERN.match(line)
74
            if directive_match is not None:
75
                image_src = directive_match.group(1)
76
                if verbose:
6619.3.3 by Jelmer Vernooij
Apply 2to3 print fix.
77
                    print(('Image ' + image_src + ' in ' + filename
78
                          + ': ' + line.strip()))
4000.4.1 by Colin D Bennett
Generate PDF version of the User Guide.
79
80
                foundimg = True
81
            outfile.write(line)
82
        outfile.close()
83
        infile.close()
84
85
class ImageFixer(object):
86
    def __init__(self, srcdir, destdir):
87
        self.srcdir = srcdir
88
        self.destdir = destdir
89
90
    def substitute_pdf_image(self, match):
91
        prefix = match.string[:match.start(1)]
92
        newname = self.convert_image_to_pdf(match.group(1))
93
        suffix = match.string[match.end(1):]
94
        return prefix + newname + suffix
95
96
    def replace_extension(self, path, newext):
97
        if path.endswith(newext):
4000.4.5 by Colin D Bennett
Strip trailing whitespace.
98
            raise Exception("File '" + path + "' already has extension '"
7143.16.17 by Jelmer Vernooij
Fix E225.
99
                            + newext + "'")
4000.4.1 by Colin D Bennett
Generate PDF version of the User Guide.
100
        dot = path.rfind('.')
101
        if dot == -1:
102
            return path + newext
103
        else:
104
            return path[:dot] + newext
105
106
    # Possibly use an SVG alternative to a PNG image, converting the SVG image
107
    # to a PDF first.  Whether or not a conversion is made, the image to use is
108
    # written to the destination directory and the path to use in the RST #
109
    # source is returned.
110
    def convert_image_to_pdf(self, filename):
111
        # Make the directory structure for the image in the destination dir.
112
        image_dirname = os.path.dirname(filename)
113
        if image_dirname:
114
            image_dirpath = os.path.join(self.destdir, image_dirname)
115
            if not os.path.exists(image_dirpath):
116
                os.mkdir(image_dirpath)
117
118
        # Decide how to handle this image.
119
        if filename.endswith('.png'):
120
            # See if there is a vector alternative.
121
            svgfile = self.replace_extension(filename, '.svg')
122
            svgpath = os.path.join(self.srcdir, svgfile)
123
            if os.path.exists(svgpath):
124
                if verbose:
125
                    print('Using SVG alternative to PNG')
126
                # Convert SVG to PDF with Inkscape.
127
                pdffile = self.replace_extension(filename, '.pdf')
128
                pdfpath = os.path.join(self.destdir, pdffile)
129
                if call(['/usr/bin/inkscape',
130
                         '--export-pdf=' + pdfpath, svgpath]) != 0:
131
                    raise Exception("Conversion to pdf failed")
132
                return pdffile
4000.4.5 by Colin D Bennett
Strip trailing whitespace.
133
4000.4.1 by Colin D Bennett
Generate PDF version of the User Guide.
134
        # No conversion, just copy the file.
135
        srcpath = os.path.join(self.srcdir, filename)
136
        destpath = os.path.join(self.destdir, filename)
137
        shutil.copyfile(srcpath, destpath)
138
        return filename
139
140
if __name__ == '__main__':
141
    IN_DIR_OPT = '--in-dir='
142
    OUT_DIR_OPT = '--out-dir='
143
    srcdir = None
144
    destdir = None
145
146
    if len(argv) < 2:
6619.3.3 by Jelmer Vernooij
Apply 2to3 print fix.
147
        print(('Usage: ' + argv[0] + ' ' + IN_DIR_OPT + 'INDIR '
148
              + OUT_DIR_OPT + 'OUTDIR'))
149
        print()
4000.4.1 by Colin D Bennett
Generate PDF version of the User Guide.
150
        print('This will convert all .txt files in INDIR into file in OUTDIR')
151
        print('while adjusting the use of images and possibly converting SVG')
152
        print('images to PDF files so LaTeX can include them.')
153
        sys.exit(1)
4000.4.5 by Colin D Bennett
Strip trailing whitespace.
154
4000.4.1 by Colin D Bennett
Generate PDF version of the User Guide.
155
    for arg in argv[1:]:
156
        if arg == '-v' or arg == '--verbose':
157
            verbose = True
158
        elif arg.startswith(IN_DIR_OPT):
159
            srcdir = arg[len(IN_DIR_OPT):]
160
        elif arg.startswith(OUT_DIR_OPT):
161
            destdir = arg[len(OUT_DIR_OPT):]
162
        else:
6619.3.3 by Jelmer Vernooij
Apply 2to3 print fix.
163
            print(('Invalid argument ' + arg))
4000.4.1 by Colin D Bennett
Generate PDF version of the User Guide.
164
            sys.exit(1)
165
166
    if srcdir is None or destdir is None:
6619.3.3 by Jelmer Vernooij
Apply 2to3 print fix.
167
        print(('Please specify the ' + IN_DIR_OPT + ' and '
168
              + OUT_DIR_OPT + ' options.'))
4000.4.1 by Colin D Bennett
Generate PDF version of the User Guide.
169
        sys.exit(1)
170
171
    if not os.path.exists(destdir):
172
        os.mkdir(destdir)
173
    Converter(srcdir, destdir).process_files()
174
175
# vim: set ts=4 sw=4 et: