-
Notifications
You must be signed in to change notification settings - Fork 3
/
build.py
916 lines (724 loc) · 29 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
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
"""Build all the desired documents from the Sonata wiki.
"""
# configuration:
import config
# imports:
import os
import glob
import re
import string
import shutil
import pickle
import subprocess
import pypandoc
from pprint import pprint as pp
from collections import defaultdict
import itertools
import argparse
import tarfile
import hunspell
import wikiconnector as wiki
import path_checksum
from bibtexHandler import processBibtex
import wikiBib
import section
DEFAULT_FIGURE_WIDTH = 0.75 # n\textwidth
# global variables
bibtexkeys = [] # ugly hack to make this global :-/
def ensure_dir(path):
try:
os.makedirs(path)
except OSError:
if not os.path.isdir(path):
raise
def download(target, output, category=None, embedded_elements=True):
try:
wiki.download(target=target,
output=output,
category=category,
embedded_elements=embedded_elements)
except:
pass
def processUML(doc, directory):
"""extract any included UML, put them in the UML dir,
write the reduced document back with an input command
"""
print "UMLing ", doc, " in ", directory
filename = os.path.join(directory,
doc + '.md')
umldir = os.path.join(
os.path.abspath(os.path.join(directory,
os.pardir)),
'uml')
print filename, umldir
# read the file:
with open(filename, 'r') as f:
data = f.read()
i = 1
m = re.search("<uml>(.*?)</uml>", data, re.S)
while (m):
# try to extract the title, to use for the caption:
title_match = re.search("^title (.*)$",
m.group(1),
re.M)
if title_match:
title_text = title_match.group(1)
else:
title_text = "UML figure (no caption provided)"
# remove title_text from contents written to UML file
# (we only want Latex figure captions)
umlcontent = str(m.group(1)).replace("title " + title_text, "")
# write uml to file for further processing by plantUML
umlfile = doc + "_" + str(i)
with open(os.path.join(umldir,
umlfile + '.uml'),
'w') as umlhandle:
umlhandle.write("@startuml")
umlhandle.write(umlcontent)
umlhandle.write("@enduml")
if True:
# trigger the generation of the actual UML figure
subprocess.call(['java',
'-jar',
'../../plantuml.jar',
'-teps',
umlfile+'.uml'],
cwd=umldir)
data = string.replace(data, m.group(0),
"[[File:" + umlfile +
".eps|" + title_text + "]]",
1)
i += 1
m = re.search("<uml>(.*?)</uml>", data, re.S)
with open(filename, 'w') as f:
f.write(data)
def processRawFile(doc, directory):
"""Check whether the file qualifies as a raw file.
If so, just copy it to the tex directory without further handling.
Returns True is raw, False if not.
"""
# add further tests here if desired:
isRawFile = doc.endswith('.bib')
print "raw: ", doc, isRawFile, directory
if isRawFile:
srcFilename = os.path.join(directory,
doc)
destFilename = os.path.abspath(
os.path.join(directory,
'..',
'tex',
doc))
print srcFilename, destFilename
shutil.copy(srcFilename, destFilename)
return isRawFile
def processPandoc(doc, directory):
def guessFormat(filename):
"""Try to guess whether the file contains
clean mediawiki syntax or messed-up HTML markup from
the stupid Rich Editor
"""
with open (filename, 'r') as f:
text = f.read()
htmlCount = len(re.findall("< *h[1-9] *>", text))
wikiCount = len(re.findall("=+.+=+", text))
if htmlCount > wikiCount:
frmt = "html"
else:
frmt = "mediawiki"
print "guessing format: ", filename, frmt
return frmt
print "pandoc ", doc, directory
filename = os.path.join(directory,
doc + '.md')
outfile = os.path.join(
os.path.join(
os.path.abspath(os.path.join(directory,
os.pardir)),
'tex'),
doc + '.tex')
filters = [os.path.join(
os.getcwd(),
'linkFilter.py'),
]
output = pypandoc.convert(filename,
format=guessFormat(filename),
to='latex',
filters=filters,
extra_args=['--chapters'],
outputfile=outfile)
print "padnoc output", output
assert output == ""
def processFile(doc, directory, umlFlag, spellcheckFlag, spellCheckDict):
"""process file doc in directory. Currently defined processing steps:
- check whether it is a raw file, then just copy it and do nothing else
- extract all included umls and run them thorugh plant uml
- run pandoc on the remaining file
"""
if not processRawFile(doc, directory):
if umlFlag:
processUML(doc, directory)
if spellcheckFlag:
processSpellcheck(doc, directory, spellCheckDict)
processPandoc(doc, directory)
def prepareDirectory(docname, filelist, appendixlist,
properties, rawlatex):
# put the latex main document into the directory
shutil.copy('templates/main.tex',
os.path.join(docname,
'tex'))
shutil.copy('templates/documentProperties.tex',
os.path.join(docname,
'tex'))
shutil.copy('templates/logo.jpg',
os.path.join(docname,
'tex'))
shutil.copy('templates/sonata-logo-large.png',
os.path.join(docname,
'tex'))
# prepare the additional properties:
print "writing properties"
with open(os.path.join(docname,
'tex',
'moreProperties.tex'),
'w') as propFile:
if properties:
for k, v in properties:
propFile.write(
'\\providecommand{{\\{}}}{{{}}}\n\\renewcommand{{\\{}}}{{{}}}\n'
.format(
k, v, k, v
))
# and any raw LaTeX we are given:
if rawlatex:
print rawlatex
with open(os.path.join(docname,
'tex',
'rawtex.tex'),
'w') as rawtex:
rawtex.write('\n'.join(rawlatex))
# write the include instructions for the chapters:
with open(os.path.join(docname,
'tex',
'includer.tex'),
'w') as includer:
if rawlatex:
includer.write('\\input{rawtex}\n')
for f in filelist:
includer.write('\\input{' + f + '}\n')
# write the appendixlist:
with open(os.path.join(docname,
'tex',
'appendixlist.tex'),
'w') as appendixfile:
appendixfile.write('% appendix\n\n')
print "appendix: ", appendixlist, filelist
for f in appendixlist:
appendixfile.write('\\input{' + f + '}\n')
def processCiteKeys(doc):
"""Turn all the autorefs to bibkeys into cites.
input:
- doc is a latex document
- global variable: bibtexkeys, contains all the keys found in the bibfiles
output:
- the rewritten doc
"""
global bibtexkeys
# because autoref has the underscores translated to -,
# (done by the linkFilter.py filter)
# we have to do the same thing here to the bibtexkeys.
newbibkeys = [re.sub('_', '-', x) for x in bibtexkeys]
# print "bibtexkeys: ", newbibkeys
pattern = 'autoref{(' + '|'.join(newbibkeys) + ')}'
doc = re.sub(pattern, 'cite{\\1}', doc)
# and now we have to replace them back to the underscore version,
# which is the one that is in the bibtex file, probably
# (this is far too complicated - need a better way to deal with
# the bloody stupid inconstiency of autoref vs label generation)
deltaKeys = [(x, y)
for (x, y) in zip(bibtexkeys, newbibkeys)
if not x == y]
# print "delatakeys: ", deltaKeys
for orgkey, wrongkey in deltaKeys:
# we need to lower-case the citation key for the bib file
# because the references get all lower-cased by linkFilter
# (this is becuase the mediawiki reader lower-cases all the
# labels for headings, and there is no easy way to distinguish
# links to headings from links to references )
o = '\\cite{' + orgkey.lower() + '}'
w = '\\cite{' + wrongkey + '}'
doc = doc.replace(w, o)
return doc
def insertFilenameLabel(doc, filename):
print "inserting: ", filename
# get basename, remove extension
f = os.path.basename(filename)
f = os.path.splitext(f)[0]
f = re.sub('_', '-', f)
f = f.lower()
tmp = re.sub(
"((subsubsection|subsection|section|chapter|paragraph|subparagraph){.*?})",
"\\1\\label{" + f + "}", doc,
count=1,
flags=re.DOTALL)
return tmp
def preProcessLatex(docdir):
"""Because of limitations in pondoc's mediawiki parser
and Mediawiki's markup syntax, we need a few tricks
to get the right LaTeX for figure and table crossreferencing
as well as table column styles
"""
def replace_tablehead(m):
print m
print "======"
print m.group(1)
print "-----"
print m.group(2)
print "-----"
print m.group(3)
print "-----"
print m.group(4)
print "======"
caption = m.group(2)
label = m.group(3).lower()
width = m.group(4)
width = re.sub(r'\\{', '{', width)
width = re.sub(r'\\}', '}', width)
# support percentage statements in table column widths:
width = re.sub(r'p\s*{\s*([0-9]+)\s*\\%\s*}', 'p{.\\1\\\\textwidth}', width, re.S)
print "width: ", width
print "======"
if caption:
res = r"\begin{{longtable}}[c]{{{}}} \caption{{{}}}\label{{{}}}\tabularnewline".format(
width,
caption,
label,
)
else:
res = r"\begin{{longtable}}[c]{{{}}}\tabularnewline".format(
width,
)
print res
return res
print "preprocessing in ", docdir
for f in glob.glob(os.path.join(docdir, '*.tex')):
if f.endswith('main.tex'):
continue
print "copying ", f
shutil.copy(f, f+'.bak')
with open(f, 'r') as fhandle:
doc = fhandle.read()
# first, let's see if there is a table head with a caption, and labal, and position marks
doc = re.sub(r'\\begin{longtable}\[c\]{(.*?)}\n\\caption{(.*?)\\#(.*?)\\#(.*?)}\\tabularnewline',
# r'\\begin{longtable}[c]{\4}\caption{\2}\label{\3}\tabularnewline',
replace_tablehead,
doc,
flags=re.S)
# allow to manually add horizontal rules to a wiki table by adding {midrule} to the end of the last cell of a row (a not so nice solution, but we need it quick)
doc = doc.replace("\\{midrule\\}\\tabularnewline", "\\tabularnewline\\midrule")
# second, lets create labels from the text after a hashmark of a caption:
doc = re.sub(r'\\includegraphics{(.*?)}\n\\caption{(.*?)(\\#(.*?))(\\#(.*?))?}',
# r'\caption{\1}\label{\3}',
lambda m: r'\includegraphics[width={3}\textwidth]{{{0}}}\caption{{{1}}}\label{{{2}}}'.format(
m.group(1),
m.group(2),
m.group(4).lower(),
str(DEFAULT_FIGURE_WIDTH) if m.group(5) is None else m.group(5).replace("\#", "")), # the replace is dirty here, better solution?
doc,
flags=re.S)
# third: there might be undersscorces in labels. right in principle, but
# they get escaped by pandoc with an \ . We have to remove the backslash here
doc = re.sub(r'\\label{(.*?)}',
lambda m: '\label{' + re.sub(r'\\', '', m.group(1)) + '}',
doc)
# looks not necessary on account of autoref:
# # foruth, turn any \url references into proper refs, unless they point to a true http
# doc = re.sub('\url{(?!http://)(.+?)}', '\\ref{\\1}', doc, flags=re.S)
# handle cites
doc = processCiteKeys(doc)
# insert a label with the file name after the first section
doc = insertFilenameLabel(doc, f)
with open(f, 'w') as fhandle:
fhandle.write(doc)
def update_custom_dictionary(hobj, dict_wiki_page_name="Spellchecker_Dict"):
"""
Download custom dictionary from wiki (if available) and add
the given words to our local spell checker dictionary.
Spell check dictionary location: http://wiki.host.tld/index.php/Spellchecker_Dict
"""
print "Updating custom spell check dictionary using %r" % dict_wiki_page_name
# fetch
download(dict_wiki_page_name, "/tmp/", None, False)
# load
with open("/tmp/%s.md" % dict_wiki_page_name, 'r') as f:
lines = f.readlines()
for l in lines:
l = l.strip("\n *-+")
if l.isalpha():
if not hobj.spell(l):
# word is not in dict, lets add it
hobj.add(l)
print "added %r" % l
print "update done."
def processSpellcheck(doc, directory, spellCheckDict):
# do spell check
try:
hobj = hunspell.HunSpell('/usr/share/hunspell/%s.dic' % spellCheckDict, '/usr/share/hunspell/%s.aff' % spellCheckDict)
except:
print "Error: Dictionary %r not found." % spellCheckDict
return
# check wiki for custom dictionary
update_custom_dictionary(hobj) # ugly to call it for each document :-/
file = os.path.join(directory, doc) + ".md"
print "Doing spell check on %r" % file
# read md file
lines = list()
out_lines = list()
with open(file, 'r') as f:
lines = f.readlines()
for line in lines:
words = line.strip("\n").split(" ")
out_words = list()
for w in words:
# generate a version of the word that does not contain any non-alpha characters
w_striped = w.strip(".:;,!?'_-")
if w_striped.isalpha():
if not hobj.spell(w_striped):
print "Spelling mistake: %r" % w_striped
# mark mistake! we need to stick to simple ASCII chars, things like <strike> could break the latex document if they occur, e.g., in headings
w = w.replace(w_striped, "??%s??" % w_striped)
out_words.append(w)
out_lines.append(" ".join(out_words))
# write back
with open(file, 'w') as f:
f.write("\n".join(out_lines))
def processLatex(docname):
def oneRunLatex(docname):
e = None
try:
subprocess.check_output(
['pdflatex',
'-shell-escape',
'-interaction=nonstopmode',
'main.tex'],
stderr=subprocess.STDOUT,
cwd=os.path.join(docname, 'tex'),
)
except subprocess.CalledProcessError as e:
print e, e.output
pass
return e
def oneRunBibtex(docname):
e = None
try:
subprocess.check_output(
['bibtex',
'main'],
stderr=subprocess.STDOUT,
cwd=os.path.join(docname, 'tex'),
)
except subprocess.CalledProcessError as e:
print e, e.output
pass
return e
e = None
try:
print "latex first pass"
e = oneRunLatex(docname)
print "bibtex"
e = oneRunBibtex(docname)
print "latex second pass"
e = oneRunLatex(docname)
print "latex third pass"
e = oneRunLatex(docname)
except Exception as e:
print e
return e
def processDocument(docname,
fingerprint,
downloadFlag,
latexFlag,
umlFlag,
embeddedElemetsFlag,
spellcheckFlag):
global bibtexkeys
print "========================================"
print "processing document: ", docname
if downloadFlag:
# note: we never download embedded elements from control page
# as this might point to producedd PDF or tar files.
# we do that in more fine-grained manner below
download(target=docname,
output=docname,
#embedded_elements=embeddedElemetsFlag,
embedded_elements=False,
)
# make sure that at least md subdirectory is empty
# later on, might remove all other stuff as well
# (only clear, when folder already exists)
# but only when actually downloading things!! not in debug mode!
if os.path.exists(os.path.join(docname, 'md')):
shutil.rmtree(os.path.join(docname, 'md'))
ensure_dir(os.path.join(docname, 'figures'))
ensure_dir(os.path.join(docname, 'uml'))
ensure_dir(os.path.join(docname, 'md'))
ensure_dir(os.path.join(docname, 'tex'))
bibdir = os.path.join(docname, 'bib')
ensure_dir(bibdir)
filelist = []
# now grab the files/wiki pages for this document:
with open(os.path.join(docname,
docname + '.md'),
'r') as doc:
doclines = doc.read()
# doctoc = section.getSectionLines(doclines, 'TOC')
# docprop = section.getSectionLines(doclines, 'Properties')
doclatex = section.getSectionLines(doclines, 'Latex')
# docbibtex = section.getSectionLines(doclines, 'Bibtex')
# docwikibib = section.getSectionLines(doclines, 'Wikibib')
#=============================================
# process any additional properties:
properties = section.getProperties(doclines, 'Properties')
# try to extract property values needed by generator script
propSpellCheck = "off"
propSpellCheckDict = "en_GB"
try:
propSpellCheck = dict(properties).get("spellCheck", "off")
propSpellCheckDict = dict(properties).get("spellCheckDict", "en_GB")
except:
pass
if spellcheckFlag and "on" in propSpellCheck:
spellcheckFlag = True
else:
spellcheckFlag = False
# --------------------------------------------
# handle abstract, ensure there is always a possibly empty file
section.writeSectionContent(
doclines, 'Abstract',
os.path.join(docname,
'md',
'propertiesAbstract.md'))
processFile('propertiesAbstract',
os.path.join(docname, 'md'),
umlFlag,
spellcheckFlag, propSpellCheckDict)
# -------------------------------------------
# handle bibtex entries
bibtex = ""
# there should always be an even empty bib.bib in tex folder
with open(os.path.join(docname,
'tex', "bib.bib"),
'w') as bh:
bh.write('% empty bibtex file\n')
bibtexkeys = []
for f in section.downloadSectionFiles(doclines,
'Bibtex',
bibdir,
downloadFlag,
embeddedElemetsFlag):
print "bibtex: ", f
with open(os.path.join(bibdir, f+'.md'), 'r') as fh:
bibtex += fh.read()
bibtexkeys = processBibtex(docname, bibtex)
for doc in section.downloadSectionFiles(doclines,
'Wikibib',
bibdir,
downloadFlag,
embeddedElemetsFlag):
bibtexkeys += wikiBib.wikibib(infile=os.path.join(bibdir,
doc + '.md'),
outfile=os.path.join(docname,
'tex',
'bib.bib'))
print "bibtexkeys (2):", bibtexkeys
#--------------------------------------------------
# process the toc: which files to download, include?
mddir = os.path.join(docname, 'md')
filelist = section.downloadSectionFiles(doclines,
'TOC',
mddir,
downloadFlag,
embeddedElemetsFlag)
for doc in filelist:
print "processing: >>", doc
processFile(doc, mddir, umlFlag, spellcheckFlag, propSpellCheckDict)
# similar for possible appendices:
appendixlist = section.downloadSectionFiles(doclines,
'Appendix',
mddir,
downloadFlag,
embeddedElemetsFlag)
for doc in appendixlist:
print "processing: >>", doc
processFile(doc, mddir, umlFlag, spellcheckFlag, propSpellCheckDict)
#=============================================
# copy figures to figures directory, fix spaces in file name!
figextensions = ['png', 'jpg', 'jpeg', 'eps', 'pdf', 'PNG', 'JPG', 'JPEG', 'EPS', 'PDF']
figurefiles = list(itertools.chain.from_iterable(
[glob.glob(os.path.join(docname,
'md',
'*.' + ext))
for ext in figextensions]))
# just the filenames, not the paths:
figurefiles = [os.path.basename(f) for f in figurefiles]
# and copy the figures to the figures directory,
# replace spaces by underscores:
for f in figurefiles:
shutil.copy(os.path.join(docname, 'md', f),
os.path.join(docname, 'figures', re.sub(' ', '_', f)))
print figurefiles
#===========================================
# start the actual processing
# prepare directory
prepareDirectory(docname, filelist, appendixlist, properties, doclatex)
# check against fingerpint
newfingerprint = path_checksum.path_checksum(
[os.path.join(docname, 'md')])
print "fingerprints: ", fingerprint, newfingerprint
# which latexing actions do we have to perform?
e = None
if (not fingerprint == newfingerprint):
preProcessLatex(os.path.join(docname, 'tex'))
if latexFlag:
e = processLatex(docname)
else:
print "nothing to be done in ", docname
return e, newfingerprint
# report the results back: stdout, pdf file
def setup_cli_parser():
"""
Command-line switches, mostly to help with debugging.
"""
parser=argparse.ArgumentParser(
description="Translate a set of Mediwiki into PDF via pandoc and LaTeX.")
parser.add_argument("--download",
dest="download",
default=False,
action="store_true",
help="Download from the given wiki (default: False)",
)
parser.add_argument("--document",
dest="document",
default=None,
help="Only process the given document"
)
parser.add_argument("--latex",
dest="latex",
default=False,
action="store_true",
help="Run LaTeX (default: False)",
)
parser.add_argument("--upload",
dest="upload",
default=False,
action="store_true",
help="Upload resulting PDF to wiki (default: False)",
)
parser.add_argument("--ignore-fingerprint",
dest="ignoreFingerprint",
default=False,
action="store_true",
help="Ignore fingerprint, always process (default: False)",
)
parser.add_argument("--uml",
dest="uml",
default=False,
action="store_true",
help="Run the plantuml conversion script (default: False)"
)
parser.add_argument("--spellcheck",
dest="spellcheck",
default=False,
action="store_true",
help="Run hunspell and highlight typos in the generated PDF (default: False)"
)
parser.add_argument("-p",
dest="production",
default=False,
action="store_true",
help="Set all switches to values for a production run."
)
parser.add_argument("--no-elements",
dest="noEmbeddedElements",
default=False,
action="store_true",
help="Do not download embedded elements (e.g. images from wiki pages) (default: False)",
)
return parser
def get_documentlist(document, downloadFlag, embeddedElemetsFlag):
"""Determine documents to process.
Command-line args takes precedence over anything
that could be downloaded.
"""
if document:
return [document]
documentlist = []
if downloadFlag:
# start the download
print "downloading documentlist"
download(target=config.DOCUMENTLIST,
output="DocumentList", embedded_elements=embeddedElemetsFlag)
# process the downloaded documentlist:
fname = os.path.join('DocumentList',
config.DOCUMENTLIST + '.md')
with open(fname,
'r') as f:
documentlist = section.linesFromBulletlist(f.readlines())
return documentlist
def main(args):
# initialize wiki connection
try:
if args.download:
wiki.setup_connection(host=config.WIKIROOT,
user=config.USER,
password=config.PASSWORD)
except:
print "Connection to remote wiki broken. Stopping."
exit(1)
# try to get the fingerprints:
try:
with open('fingerprints', 'r') as fp:
fingerprints = pickle.load(fp)
except:
fingerprints = defaultdict(str)
# iterate over the documents contained in documentlist:
for line in get_documentlist(args.document,
args.download,
not args.noEmbeddedElements):
# if we are to ignore fingerprints, let's just pass in a stupid
# value:
e, newfp = processDocument(line,
(fingerprints[line]
if not args.ignoreFingerprint
else None),
args.download,
args.latex,
args.uml,
not args.noEmbeddedElements,
args.spellcheck)
if ((not fingerprints[line] == newfp) or
(args.ignoreFingerprint)):
if args.upload:
# produce tarfile of the produced latex and figure documents
with tarfile.open(os.path.join(line, line+'-latex.tgz'),
'w:gz') as tar:
tar.add(os.path.join(line, 'tex'))
tar.add(os.path.join(line, 'figures'))
tar.add(os.path.join(line, 'bib'))
tar.add(os.path.join(line, 'uml'))
wiki.upload_document(line, e)
fingerprints[line] = newfp
with open('fingerprints', 'w') as fp:
pickle.dump(fingerprints, fp)
if __name__ == '__main__':
parser = setup_cli_parser()
args = parser.parse_args()
if args.production:
args.download = True
args.document = None
args.latex = True
args.upload = True
args.ignoreFingerprint = False
args.uml = True
args.noEmbeddedElements = False
args.spellcheck = True
main(args)