-
Notifications
You must be signed in to change notification settings - Fork 21
/
build.py
executable file
·382 lines (298 loc) · 10.8 KB
/
build.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
#!/usr/bin/env python3
# This program is part of OParl and may be used to build the specification
import os
import shlex
import shutil
import subprocess
import sys
from argparse import ArgumentParser
from glob import glob
from os import path
from scripts.json_schema2markdown import schema_to_markdown
SPECIFICATION_BUILD_ACTIONS = [
'all',
'clean',
'test',
'live',
'html',
'pdf',
'odt',
'docx',
'txt',
'epub',
'archives',
'zip',
'gz',
'bz'
]
SPECIFICATION_BUILD_TOOLS = [
'pandoc',
'dot',
'xelatex',
'gs',
'convert',
'python3',
'tar',
'zip'
]
SPECIFICATION_BUILD_FLAGS = {
'gs': '-dQUIET -dSAFER -dBATCH -dNOPAUSE -sDisplayHandle=0 -sDEVICE=png16m -r600 -dTextAlphaBits=4',
'pandoc': '--from markdown --standalone --table-of-contents --toc-depth=2 --number-sections'
}
def configure_argument_parser():
parser = ArgumentParser(
prog='./build.py',
epilog='''
build.py is part of the OParl Specification and thus distributed
under the terms of the Creative Commons SA 4.0 License.
'''
)
parser.add_argument(
'--language',
'-l',
help='Specification language',
default='de',
action='store',
)
parser.add_argument(
'--version',
'-V',
help='This will be displayed as version in the specification. Defaults to `git desribe`',
action='store',
)
parser.add_argument(
'--print-basename',
help='This will output the base name used for build output',
action='store_true',
dest='print_basename'
)
parser.add_argument(
'--latex-template',
help='Change the latex template used for PDF generation',
action='store',
default='resources/template.tex'
)
parser.add_argument(
'--html-style',
help='Change the CSS file used for styling the HTML output',
action='store',
default='resources/html5.css'
)
parser.add_argument(
'--list-actions',
help='List available build actions',
dest='list_actions',
action='store_true'
)
parser.add_argument(
'action',
help='Build action to take, available actions are: {}'.format(', '.join(SPECIFICATION_BUILD_ACTIONS)),
action='store',
nargs='*'
)
return parser
def check_build_action(action):
if len(action) == 0:
return 'all'
if action[0] in SPECIFICATION_BUILD_ACTIONS:
return action[0]
raise Exception(
'Unknown build action: {}, choose one of: {}'.format(action, ', '.join(SPECIFICATION_BUILD_ACTIONS)))
def get_git_describe_version():
return subprocess.check_output('git describe', shell=True, universal_newlines=True).strip()
def check_available_tools():
tools = {}
for tool in SPECIFICATION_BUILD_TOOLS:
executable = shutil.which(tool)
if executable:
tools[tool] = executable
else:
raise Exception('{} not found, aborting.'.format(tool))
return tools
def get_filename_base(language, version):
return 'OParl-{}-{}'.format(version, language)
def prepare_builddir(filename_base):
os.makedirs('build/src/images')
os.makedirs('build/{}'.format(filename_base))
def prepare_schema(language):
language_file = 'schema/strings.yml'
if language != 'de':
language_file = 'locales/{}/schema/strings.yml'.format(language)
output_file = 'build/src/3-99-schema.md'
schema_to_markdown('schema', 'examples', output_file, language, language_file)
def prepare_markdown(language):
glob_pattern = 'src/*.md'
if language != 'de':
glob_pattern = 'locales/{}/src/*.md'.format(language)
files = glob(glob_pattern)
for f in files:
shutil.copy2(f, 'build/src/')
os.mkdir('build/extra')
with open('build/extra/detailed-version.md', 'w') as fp:
fp.write("Version {}\n".format(get_git_describe_version()))
def prepare_images(tools):
glob_pattern = 'src/images/*.*'
files = glob(glob_pattern)
for f in files:
convert_command = ''
filename, extension = os.path.splitext(f)
fout = path.join('build', 'src', 'images', os.path.basename(filename) + '.png')
shutil.copy2(f, fout)
if extension == '.pdf':
convert_command = '{} {} -sOutputFile={} -f {}'.format(
tools['gs'],
SPECIFICATION_BUILD_FLAGS['gs'],
fout,
f
)
if extension == '.dot':
convert_command = '{} -Tpng {} -o {}'.format(
tools['dot'],
f,
fout
)
if extension == '.svg':
convert_command = '{} {} {}'.format(
tools['convert'],
f,
fout
)
cmd = shlex.split(convert_command)
try:
subprocess.run(cmd, check=True)
except subprocess.CalledProcessError:
raise Exception(
'Errored on image prep for {}, please check the command:\n{}'.format(
f, convert_command
)
)
def create_symlinks(filename_base):
""" Allow having stable links when working on the spec """
os.makedirs('build/latest')
for specfile in os.listdir('build/{}'.format(filename_base)):
existing = os.path.abspath('build/{}/{}'.format(filename_base, specfile))
new = 'build/latest/oparl{}'.format(os.path.splitext(specfile)[-1])
os.symlink(existing, new)
def get_pandoc_version(pandoc_bin):
version_tuple = subprocess.getoutput('{} --version'.format(pandoc_bin)).split('\n')[0].split(' ')[1].split('.')
return [int(v) for v in version_tuple]
def run_pandoc(pandoc_bin, filename_base, output_format, extra_args='', extra_files=''):
output_file = 'build/{}/{}.{}'.format(filename_base, filename_base, output_format)
if path.exists(output_file):
return
source_files = glob('build/src/*.md')
source_files.sort(key=lambda file: path.basename(file))
# This gets the version into the titlepage of the pdf
detailed_version = '-M detailed-version={}'.format(get_git_describe_version())
# NOTE: Once we can safely assume pandoc 2.0, we can use resource-path
# for neater include management in the markdown files
# pandoc_command = '{} {} {} --resource-path=.:build/src -o {} {} {}'.format(
pandoc_command = '{} {} {} -o {} {} {} {}'.format(
pandoc_bin,
SPECIFICATION_BUILD_FLAGS['pandoc'],
extra_args,
output_file,
extra_files,
detailed_version,
' '.join(source_files)
)
cmd = shlex.split(pandoc_command)
try:
subprocess.run(cmd, check=True, stdout=sys.stdout, stderr=sys.stderr)
except subprocess.CalledProcessError:
raise Exception(
'Errored on pandoc: {}'.format(pandoc_command)
)
class Action:
@staticmethod
def clean():
shutil.rmtree('build', ignore_errors=True)
@staticmethod
def test():
# TODO: validate.py appears to be broken
pass
@staticmethod
def live(tools, _, filename_base):
args = '--to html5 --section-divs --no-highlight --template=resources/live.html'
run_pandoc(tools['pandoc'], filename_base, 'html', extra_args=args)
@staticmethod
def html(tools, options, filename_base):
args = '--to html5 --css {} --section-divs --self-contained'.format(options.html_style)
run_pandoc(tools['pandoc'], filename_base, 'html', extra_args=args,
extra_files='build/extra/detailed-version.md resources/lizenz-als-bild.md')
@staticmethod
def pdf(tools, options, filename_base):
args = '--pdf-engine=xelatex'
if get_pandoc_version(tools['pandoc'])[0] < 2:
args = '--latex-engine=xelatex'
args += ' --template {}'.format(options.latex_template)
run_pandoc(tools['pandoc'], filename_base, 'pdf', extra_args=args)
@staticmethod
def odt(tools, _, filename_base):
run_pandoc(tools['pandoc'], filename_base, 'odt',
extra_files='build/extra/detailed-version.md resources/lizenz-als-text.md')
@staticmethod
def docx(tools, _, filename_base):
run_pandoc(tools['pandoc'], filename_base, 'docx',
extra_files='build/extra/detailed-version.md resources/lizenz-als-text.md')
@staticmethod
def txt(tools, _, filename_base):
run_pandoc(tools['pandoc'], filename_base, 'txt')
@staticmethod
def epub(tools, _, filename_base):
run_pandoc(tools['pandoc'], filename_base, 'epub', extra_files='build/extra/detailed-version.md')
@staticmethod
def all(tools, options, filename_base):
Action.html(tools, options, filename_base)
Action.pdf(tools, options, filename_base)
Action.odt(tools, options, filename_base)
Action.docx(tools, options, filename_base)
Action.txt(tools, options, filename_base)
Action.epub(tools, options, filename_base)
@staticmethod
def zip(tools, options, filename_base):
Action.all(tools, options, filename_base)
archive_name = '{}.zip'.format(filename_base)
subprocess.run(['zip', '-qr', archive_name, filename_base], cwd='build')
@staticmethod
def gz(tools, options, filename_base):
Action.all(tools, options, filename_base)
archive_name = '{}.tar.gz'.format(filename_base)
subprocess.run(['tar', '-czf', archive_name, filename_base], cwd='build')
@staticmethod
def bz(tools, options, filename_base):
Action.all(tools, options, filename_base)
archive_name = '{}.tar.bz2'.format(filename_base)
subprocess.run(['tar', '-cjf', archive_name, filename_base], cwd='build')
@staticmethod
def archives(tools, options, filename_base):
Action.zip(tools, options, filename_base)
Action.gz(tools, options, filename_base)
Action.bz(tools, options, filename_base)
def main():
options = configure_argument_parser().parse_args()
action = check_build_action(options.action)
if options.version is None:
options.version = get_git_describe_version()
filename_base = get_filename_base(options.language, options.version)
if options.print_basename:
print(filename_base)
exit(0)
if options.list_actions:
for action in SPECIFICATION_BUILD_ACTIONS:
print('- ' + action)
exit()
tools = check_available_tools()
# always clean
Action.clean()
if action == 'clean':
exit(0)
prepare_builddir(filename_base)
prepare_schema(options.language)
prepare_markdown(options.language)
prepare_images(tools)
# Avoid much boilerplate
getattr(Action, action)(tools, options, filename_base)
create_symlinks(filename_base)
if __name__ == '__main__':
main()