This repository has been archived by the owner on Apr 29, 2019. It is now read-only.
forked from wannesm/adsphd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
run.py
executable file
·344 lines (284 loc) · 9.52 KB
/
run.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
#!/usr/bin/env python3
# encoding: utf-8
#
# Copyright (C), 2012-2014 by Wannes Meert, KU Leuven
#
# Very naive compilation script for the ADSPHD class.
#
# No file dependency checks are performed (use TeXnicCenter, Texmaker, latexmk,
# rubber, SCons, or make if you want such a feature).
#
import glob
import os
import re
import shlex
import sys
import argparse
from subprocess import *
## SETTINGS ##
mainfile = 'thesis.tex'
chaptersdir = 'chapters'
makebibliography = True
makeindex = True
makeglossary = True
makenomenclature = True
usebiblatex = False
biblatexbackend = 'biber' # alternative: bibtex
verbose = False
dry = False
apps = {}
### INITIALISATION ###
def initapplications():
"""Initialize the application commands and arguments for the different
platforms."""
global apps
# Unix and linux are the default setup
## *NIX ##
apps['pdflatex'] = App('pdflatex', '-interaction=nonstopmode -synctex=1 -shell-escape {basename}', verbose)
apps['bibtex'] = App('bibtex', '--min-crossref=100 {basename}', verbose)
apps['biber'] = App('biber', '{basename}', verbose)
apps['glossary'] = App('makeindex', '{basename}.glo -s {basename}.ist -t {basename}.glg -o {basename}.gls', verbose)
apps['nomenclature']= App('makeindex', '{basename}.nlo -s nomencl.ist -o {basename}.nls', verbose)
apps['pdfviewer'] = App('acroread', '{pdffile}', verbose)
apps['remove'] = App('rm', '-f {cleanfiles}', verbose)
if sys.platform == 'darwin':
## Mac OS X ##
apps['pdfviewer'] = App('open', '{pdffile}', verbose)
elif sys.platform == 'win32' or sys.platform == 'cygwin':
## Windows ##
## TODO: does not yet work
pass
## DERIVED SETTINGS ##
settings = {'basename':'', 'cleanfiles':'', 'pdffile':''}
settings['basename'] = os.path.splitext(mainfile)[0]
settings['cleanfiles'] = " ".join([settings['basename']+ext for ext in ['.toc','.aux','.log','.bbl','.blg','.log','.lof','.lot','.ilg','.out','.glo','.gls','.nlo','.nls','.brf','.ist','.glg','.synctexgz','.tgz','.idx','.ind','-blx.bib','.fdb_latexmk','.synctex.gz','.run.xml','.bcf']])
settings['pdffile'] = settings['basename']+'.pdf'
#print(settings)
## COMPILE ##
knowntargets = dict()
def target(targetname = None):
def decorate(f):
global knowntargets
name = targetname if targetname else f.__name__
knowntargets[name] = f
return f
return decorate
## TARGETS ##
@target()
def test():
"""Verify the settings in run.py"""
allok = testSettings()
if allok:
print("Your settings appear to be consistent.")
@target()
def compile():
"""Build thesis.pdf"""
testSettings()
latex()
def latex():
global apps
rerun = False
print('#### LATEX ####')
apps['pdflatex'].run(settings, 'Latex failed')
if makebibliography:
rerun = True
if usebiblatex and biblatexbackend == 'biber':
print('#### BIBER ####')
apps['biber'].run(settings, 'Biber failed')
else:
print('#### BIBTEX ####')
apps['bibtex'].run(settings, 'Bibtex failed')
if makeindex:
rerun = True
print('#### INDEX ####')
if makeglossary:
# List of abbreviations
rerun = True
print('#### GLOSSARY ####')
apps['glossary'].run(settings, 'Creating glossary failed')
if makenomenclature:
# List of symbols
rerun = True
print('#### NOMENCLATURE ####')
apps['nomenclature'].run(settings, 'Creating glossary failed')
if rerun:
print('#### LATEX ####')
apps['pdflatex'].run(settings, 'Rerunning Latex failed')
print('#### LATEX ####')
apps['pdflatex'].run(settings, 'Rerunning Latex failed')
@target()
def clean():
"""Remove the auxiliary files created by Latex."""
global apps
apps['remove'].run(settings, 'Removing auxiliary files failed')
@target()
def realclean():
"""Remove all files created by Latex."""
global apps
clean()
newsettings = dict(settings)
newsettings['cleanfiles'] = 'thesis.pdf thesis.dvi thesis.ps'
apps['remove'].run(newsettings, 'Removing pdf files failed.')
@target()
def newchapter():
"""Create the necessary files for a new chapter."""
chaptername = ""
validchaptername = re.compile(r'^[a-zA-Z0-9_.]+$')
while validchaptername.match(chaptername) == None:
chaptername = input("New chapter file name (only a-z, A-Z, 0-9 or _): ")
newdirpath = os.path.join(chaptersdir, chaptername)
print("Creating new directory: "+newdirpath)
if not os.path.exists(newdirpath):
os.makedirs(newdirpath)
newfilepath = os.path.join(newdirpath,chaptername+".tex")
print("Creating new tex-file: "+newfilepath)
newfile = open(newfilepath, 'w')
print("\\chapter{This is "+chaptername+"}\\label{ch:"+chaptername+"}\n", file=newfile)
print("\n\\ldots\n\n\n\n\
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\
% Keep the following \\cleardoublepage at the end of this file, \n\
% otherwise \\includeonly includes empty pages.\n\
\\cleardoublepage\n", file=newfile)
newfile.close()
@target()
def view():
"""Open the generated pdf file in a pdf viewer."""
print("Opening "+settings['pdffile'])
apps['pdfviewer'].run(settings, 'Opening pdf failed.')
@target()
def targets():
"""Print overview of available targets."""
print("Targets:")
targetdocs = [(target,f.__doc__) for (target,f) in knowntargets.items()]
maxl = max((len(t) for (t,d) in targetdocs))
targetdocs.sort()
for (target,doc) in targetdocs:
s = "- {:<"+str(maxl)+"} {}"
if doc == None:
doc = ''
print(s.format(target,doc))
## AUXILIARY ##
def testSettings():
"""Verify whether run.py is using the expected settings based on
thesis.tex.
"""
allok = True
allok = allok and testBiblatex()
allok = allok and testNomenclature()
allok = allok and testGlossary()
return allok
def testBiblatex():
"""Test whether the main tex file includes biblatex and if this is
consistent with the settings in run.py
"""
global usebiblatex
allok = True
isusingbiblatex = False
pattern = re.compile(r'^\\documentclass.*biblatex*.*$')
with open(mainfile, 'r') as f:
for line in f:
if pattern.search(line) != None:
isusingbiblatex = True
if not usebiblatex:
print("Warning: It appears you are using biblatex while this setting in run.py is set to false.\n---> Continuing with biblatex set to true.\n")
allok = False
usebiblatex = True
return allok
if not isusingbiblatex and usebiblatex:
print("WARNING: It appears you are not using biblatex while this setting in run.py is set to true.\n---> Continuing with biblatex set to false.\n")
usebiblatex = False
allok = False
return allok
def testNomenclature():
"""Check whether the nomenclature settings are consistent."""
allok = True
texfile = open(mainfile, 'r')
pattern = re.compile(r'^\s*\\usepackage.*{nomencl}.*')
found = False
for line in texfile:
if pattern.search(line) != None:
found = True
if not found and makenomenclature:
print("\nWARNING: Trying to build the nomenclature but you have not include the nomencl Latex package.\n")
allok = False
if found and not makenomenclature:
print("\nWARNING: You have included the nomencl Latex package but in the run.py script this step is not activated.\n")
allok = False
return allok
def testGlossary():
"""Check whether the glossary settings are consistent."""
allok = True
texfile = open(mainfile, 'r')
pattern = re.compile(r'^\s*\\usepackage.*{glossary.*')
found = False
for line in texfile:
if pattern.search(line) != None:
found = True
if not found and makeglossary:
print("\nWARNING: Trying to build the glossary but you have not include the glossary Latex package.\n")
allok = False
if found and not makeglossary:
print("\nWARNING: You have included the glossary Latex package but in the run.py script this step is not activated.\n")
allok = False
return allok
## APPLICATION ##
class App:
def __init__(self, b, o, v=False):
self.binary = b
self.options = o
self.verbose = v
def run(self, settings, errmsg):
""" Run the command for the given settings.
Required settings:
- basename
- cleanfiles
:returns: Return code
"""
returncode = 1
try:
cmd = self.options.format(**settings)
args = shlex.split(cmd)
print("Running: "+self.binary+" "+" ".join(args))
if not dry:
returncode = check_call([self.binary] + args)
except CalledProcessError as err:
print(sys.argv[0].split("/")[-1] + ": "+errmsg+" (exitcode "+str(err.returncode)+")", file=sys.stderr)
return returncode
## COMMAND LINE INTERFACE ##
class Usage(Exception):
def __init__(self, msg):
self.msg = msg
def main(argv=None):
global verbose
global dry
parser = argparse.ArgumentParser(
description='''
Naive compilation script for the ADSPhD class. No file dependency checks
are performed. Use TeXnicCenter, Texmaker, latexmk, rubber, SCons or
make for such a feature.''',
epilog='''
Settings: Open run.py with a text editor and change values in the settings
definition
''')
parser.add_argument('--verbose', '-v', action='count', help='Verbose output')
parser.add_argument('--targets', '-T', action='store_true', help='Print available targets')
parser.add_argument('--dry', '-d', action='store_true', help='Dry run to see commands without executing them')
parser.add_argument('target', nargs='*', help='Targets')
args = parser.parse_args(argv)
verbose = args.verbose
dry = args.dry
if args.targets:
targets()
return
initapplications()
if len(args.target) == 0:
print("No targets given, using default target: compile")
compile()
for target in args.target:
print("Target: "+target)
if target in knowntargets:
knowntargets[target]()
else:
print("Unknown target")
if __name__ == "__main__":
sys.exit(main())