]> Shamusworld >> Repos - ardour-manual/blob - build.py
Adding PDF generation
[ardour-manual] / build.py
1 #!/usr/bin/python3
2 #
3 # Script to take the master document and ancillary files and create the
4 # finished manual/website.
5 #
6 # by James Hammons
7 # (C) 2017 Underground Software
8 #
9
10 # Remnants (could go into the master document as the first header)
11
12 import os
13 import re
14 import shutil
15 import argparse
16
17
18 # Global vars
19 global_bootstrap_path = '/bootstrap-3.3.7'
20 global_page_title = 'The Ardour Manual'
21 global_site_dir = './website/'
22 global_githuburl = 'https://github.com/Ardour/manual/edit/master/include/'
23 global_screen_template = 'page-template.html'
24 global_onepage_template = 'onepage-template.html'
25 global_pdf_template = 'pdf-template.html'
26 global_master_doc = 'master-doc.txt'
27
28 # This matches all *non* letter/number, ' ', '.', '-', and '_' chars
29 cleanString = re.compile(r'[^a-zA-Z0-9 \._-]+')
30 # This matches new 'unbreakable' links, up to the closing quote or anchor
31 findLinks = re.compile(r'"@@[^#"]*[#"]')
32
33 #
34 # Create an all lowercase filename without special characters and with spaces
35 # replaced with dashes.
36 #
37 def MakeFilename(s):
38         global cleanString
39         # Clean up the file name, removing all non letter/number or " .-_" chars.
40         # Also, convert to lower case and replace all spaces with dashes.
41         fn = cleanString.sub('', s).lower().replace(' ', '-')
42         # Double dashes can creep in from the above replacement, so we check for
43         # that here.
44         fn = fn.replace('--', '-')
45
46         return fn
47
48
49 #
50 # Parse headers into a dictionary
51 #
52 def ParseHeader(fileObj):
53         header = {}
54
55         while (True):
56                 hdrLine = fileObj.readline().rstrip('\r\n')
57
58                 # Break out of the loop if we hit the end of header marker
59                 if hdrLine.startswith('---'):
60                         break
61
62                 # Check to see that we have a well-formed header construct
63                 match = re.findall(': ', hdrLine)
64
65                 if match:
66                         # Parse out foo: bar pairs & put into header dictionary
67                         a = re.split(': ', hdrLine, 1)
68                         header[a[0]] = a[1]
69
70         return header
71
72
73 #
74 # Turn a "part" name into an int
75 #
76 def PartToLevel(s):
77         level = -1
78         lvl = {'part': 0, 'chapter': 1, 'subchapter': 2}
79         if s in lvl:
80                 return lvl[s]
81         else:
82                 return -1
83
84
85 #
86 # Converts a integer to a roman number
87 #
88 def num2roman(num):
89         num_map = [(1000, 'M'), (900, 'CM'), (500, 'D'), (400, 'CD'), (100, 'C'), (90, 'XC'), (50, 'L'), (40, 'XL'), (10, 'X'), (9, 'IX'), (5, 'V'), (4, 'IV'), (1, 'I')]
90         roman = ''
91
92         while num > 0:
93                 for i, r in num_map:
94                         while num >= i:
95                                 roman += r
96                                 num -= i
97
98         return roman
99
100 #
101 # Capture the master document's structure (and content, if any) in a list
102 #
103 def GetFileStructure():
104         fs = []
105         fnames = [None]*6
106         content = ''
107         grab = False
108         mf = open(global_master_doc)
109
110         for ln in mf:
111                 if ln.startswith('---'):
112                         # First, stuff any content that we may have read into the current
113                         # header's dictionary
114                         if grab:
115                                 fs[-1]['content'] = content
116                                 grab = False
117                                 content = ''
118
119                         # Then, get the new header and do things to it
120                         hdr = ParseHeader(mf)
121                         level = PartToLevel(hdr['part'])
122                         hdr['level'] = level
123                         fnames[level] = MakeFilename(hdr['title'])
124
125                         # Ickyness--user specified URIs
126                         if 'uri' in hdr:
127                                 hdr['filename'] = hdr['uri']
128                         else:
129                                 fullName = ''
130
131                                 for i in range(level + 1):
132                                         fullName = fullName + fnames[i] + '/'
133
134                                 # Strip trailing '/' on filename
135                                 hdr['filename'] = fullName[:-1]
136
137                         fs.append(hdr)
138
139                         if ('include' not in hdr) and (level > 0):
140                                 grab = True
141                 else:
142                         if grab:
143                                 content = content + ln
144
145         # Catch the last file, since it would be missed above
146         if grab:
147                 fs[-1]['content'] = content
148
149         mf.close()
150         return fs
151
152
153 #
154 # Determine if a particular node has child nodes
155 #
156 def HaveChildren(fs, pos):
157         # If we're at the end of the list, there can be no children
158         if pos == len(fs) - 1:
159                 return False
160
161         # If the next node is at a lower level than the current node, we have
162         # children.
163         if fs[pos]['level'] < fs[pos + 1]['level']:
164                 return True
165
166         # Otherwise, no children at this node.
167         return False
168
169
170 #
171 # Get the children at this level, and return them in a list
172 #
173 def GetChildren(fs, pos):
174         children = []
175         pos = pos + 1
176         childLevel =  fs[pos]['level']
177
178         while fs[pos]['level'] >= childLevel:
179                 if fs[pos]['level'] == childLevel:
180                         children.append(pos)
181
182                 pos = pos + 1
183
184                 # Sanity check
185                 if pos == len(fs):
186                         break
187
188         return children
189
190
191 #
192 # Get the parent at this level
193 #
194 def GetParent(fs, pos):
195         thisLevel =  fs[pos]['level']
196         pos = pos - 1
197
198         while pos >= 0 and fs[pos]['level'] >= thisLevel:
199                 pos = pos - 1
200
201         return pos
202
203 #
204 # Change the hierarchy of titles : h1->hn, h2->hn+1, etc... n being delta-1
205 #
206 def reheader(txt, delta):
207         for i in range(6, 0, -1):
208                 txt = txt.replace('<h' + str(i),'<h' + str(i+delta))
209                 txt = txt.replace('</h' + str(i),'</h' + str(i+delta))
210         return txt
211
212 #
213 # Creates the BreadCrumbs
214 #
215 def GetBreadCrumbs(fs, pos):
216         breadcrumbs = '<li class="active">'+ fs[pos]['title'] + '</li>'
217
218         while pos >= 0:
219                 pos = GetParent(fs, pos)
220
221                 if pos >= 0:
222                         breadcrumbs='<li><a href="/' + fs[pos]['filename'] + '/">'+ fs[pos]['title'] + '</a></li>'+ breadcrumbs
223
224         breadcrumbs = '<ul class="breadcrumb"><li><a href="/toc/index.html">Home</a></li>' + breadcrumbs + '</ul>'
225         return breadcrumbs
226
227
228 #
229 # Make an array of children attached to each node in the file structure
230 # (It's a quasi-tree structure, and can be traversed as such.)
231 #
232 def FindChildren(fs):
233         childArray = []
234
235         for i in range(len(fs)):
236                 if HaveChildren(fs, i):
237                         childArray.append(GetChildren(fs, i))
238                 else:
239                         childArray.append([])
240
241         return childArray
242
243
244 #
245 # Make an array of the top level nodes in the file structure
246 #
247 def FindTopLevelNodes(fs):
248         level0 = []
249
250         for i in range(len(fs)):
251                 if fs[i]['level'] == 0:
252                         level0.append(i)
253
254         return level0
255
256
257 #
258 # Find all header links and create a dictionary out of them
259 #
260 def FindInternalLinks(fs):
261         linkDict = {}
262
263         for hdr in fs:
264                 if 'link' in hdr:
265                         linkDict['"@@' + hdr['link'] + '"'] = '"/' + hdr['filename'] + '/"'
266                         linkDict['"@@' + hdr['link'] + '#'] = '"/' + hdr['filename'] + '/index.html#'
267
268
269         return linkDict
270
271 #
272 # Same as above, but create anchors (for the one-page version)
273 #
274 def FindInternalAnchors(fs):
275         linkDict = {}
276
277         for hdr in fs:
278                 if 'link' in hdr:
279                         linkDict['"@@' + hdr['link'] + '"'] = '"#' + hdr['link'] + '"'
280                         linkDict['"@@' + hdr['link'] + '#'] = '"#' + hdr['link'] + '"'
281
282
283         return linkDict
284
285
286 #
287 # Internal links are of the form '@@link-name', which are references to the
288 # 'link:' field in the part header. We have to find all occurrences and replace
289 # them with the appropriate link.
290 #
291 def FixInternalLinks(links, content, title):
292         global findLinks
293         match = findLinks.findall(content)
294         missing = []
295
296         if len(match) > 0:
297                 for s in match:
298                         if s in links:
299                                 content = content.replace(s, links[s])
300                         else:
301                                 missing.append(s)
302
303         # Report missing link targets to the user (if any)
304         if len(missing) > 0:
305                 print('\nMissing link target' + ('s' if len(missing) > 1 else '') + ' in "' + title + '":')
306
307                 for s in missing:
308                         print('  ' + s)
309
310                 print()
311
312         return content
313
314
315 #
316 # Recursively build a list of links based on the location of the page we're
317 # looking at currently
318 #
319 def BuildList(lst, fs, pagePos, cList):
320         content = '\n\n<ul>\n'
321
322         for i in range(len(lst)):
323                 curPos = lst[i]
324                 nextPos = lst[i + 1] if i + 1 < len(lst) else len(fs)
325
326                 active = ' class=active' if curPos == pagePos else ''
327                 menuTitle = fs[curPos]['menu_title'] if 'menu_title' in fs[curPos] else fs[curPos]['title']
328                 content = content + '<li' + active + '><a href="/' + fs[curPos]['filename'] + '/">' + menuTitle + '</a></li>'
329
330                 # If the current page is our page, and it has children, enumerate them
331                 if curPos == pagePos:
332                         if len(cList[curPos]) > 0:
333                                 content = content + BuildList(cList[curPos], fs, -1, cList)
334
335                 # Otherwise, if our page lies between the current one and the next,
336                 # build a list of links from those nodes one level down.
337                 elif (pagePos > curPos) and (pagePos < nextPos):
338                         content = content + BuildList(cList[curPos], fs, pagePos, cList)
339
340         content = content + '\n</ul>\n'
341
342         return content
343
344
345 #
346 # Builds the sidebar for the one-page version
347 #
348 def BuildOnePageSidebar(fs):
349
350         content = '\n\n<ul class="toc" style="white-space:nowrap;">\n'
351         lvl = 0
352         levelNums = [0]*3
353
354         for i in range(len(fs)):
355                 # Handle Part/Chapter/subchapter/section/subsection numbering
356                 level = fs[i]['level']
357                 if level < 2:
358                         levelNums[2] = 0
359                 levelNums[level] = levelNums[level] + 1;
360                 j = level
361                 txtlevel = ''
362                 while j > 0:  #level 0 is the part number which is not shown
363                         txtlevel = str(levelNums[j]) + '.' + txtlevel
364                         j = j-1
365                 if len(txtlevel) > 0:
366                         txtlevel = txtlevel[:-1] + ' - '
367
368                 if 'link' in fs[i]:
369                         anchor = fs[i]['link']
370                 else:
371                         anchor = fs[i]['filename']
372
373                 while lvl < level:
374                         content = content + '<ul style="white-space:nowrap;">\n'
375                         lvl = lvl + 1
376                 while lvl > level:
377                         content = content + '</ul>\n'
378                         lvl = lvl - 1
379
380                 content = content + '<li><a href="#' + anchor + '">' + txtlevel + fs[i]['title'] + '</a></li>\n'
381
382         content = content + '</ul>\n'
383
384         return content
385
386
387 #
388 # Create link sidebar given a position in the list.
389 #
390 def CreateLinkSidebar(fs, pos, childList):
391
392         # Build the list recursively from the top level nodes
393         content = BuildList(FindTopLevelNodes(fs), fs, pos, childList)
394         # Shove the TOC link and one file link at the top...
395         active = ' class=active' if pos<0 else ''
396         content = content.replace('<ul>','<ul><li' + active + '><a href="/toc/">Table of Contents</a></li>\n',1)
397
398         return content
399
400 # Preliminaries
401
402 # We have command line arguments now, so deal with them
403 parser = argparse.ArgumentParser(description='A build script for the Ardour Manual')
404 parser.add_argument('-v', '--verbose', action='store_true', help='Display the high-level structure of the manual')
405 parser.add_argument('-q', '--quiet', action='store_true', help='Suppress all output (overrides -v)')
406 parser.add_argument('-d', '--devmode', action='store_true', help='Add content to pages to help developers debug them')
407 args = parser.parse_args()
408 verbose = args.verbose
409 quiet = args.quiet
410 devmode = args.devmode
411
412 if quiet:
413         verbose = False
414
415 level = 0
416 fileCount = 0
417 levelNums = [0]*3
418 lastFile = ''
419 page = ''
420 onepage = ''
421 pdfpage = ''
422 toc = ''
423 pageNumber = 0
424
425
426
427 if not quiet and devmode:
428         print('Devmode active: scribbling extra junk to the manual...')
429
430 if os.access(global_site_dir, os.F_OK):
431         if not quiet:
432                 print('Removing stale HTML data...')
433
434         shutil.rmtree(global_site_dir)
435
436 shutil.copytree('./source', global_site_dir)
437
438
439 # Read the template, and fix the stuff that's fixed for all pages
440 temp = open(global_screen_template)
441 template = temp.read()
442 temp.close()
443 template = template.replace('{{page.bootstrap_path}}', global_bootstrap_path)
444 template = template.replace('{{page.page_title}}', global_page_title)
445
446 # Same as above, but for the One-page version
447 temp = open(global_onepage_template)
448 onepage = temp.read()
449 temp.close()
450 onepage = onepage.replace('{{page.bootstrap_path}}', global_bootstrap_path)
451 onepage = onepage.replace('{{page.page_title}}', global_page_title)
452
453 # Same as above, but for the PDF version
454 temp = open(global_pdf_template)
455 pdfpage = temp.read()
456 temp.close()
457 pdfpage = pdfpage.replace('{{page.page_title}}', global_page_title)
458
459 # Parse out the master document's structure into a dictionary list
460 fileStruct = GetFileStructure()
461
462 # Build a quasi-tree structure listing children at level + 1 for each node
463 nodeChildren = FindChildren(fileStruct)
464
465 # Create a dictionary for translation of internal links to real links
466 links = FindInternalLinks(fileStruct)
467 oplinks = FindInternalAnchors(fileStruct)
468
469 if not quiet:
470         print('Found ' + str(len(links)) + ' internal link target', end='')
471         print('.') if len(links) == 1 else print('s.')
472
473 if not quiet:
474         master = open(global_master_doc)
475         firstLine = master.readline().rstrip('\r\n')
476         master.close()
477
478         if firstLine == '<!-- exploded -->':
479                 print('Parsing exploded file...')
480         elif firstLine == '<!-- imploded -->':
481                 print('Parsing imploded file...')
482         else:
483                 print('Parsing unknown type...')
484
485 # Here we go!
486
487 for header in fileStruct:
488         fileCount = fileCount + 1
489         content = ''
490         more = ''
491
492         lastLevel = level
493         level = header['level']
494
495         # Handle Part/Chapter/subchapter numbering
496         if level < 2:
497                 levelNums[2] = 0
498         levelNums[level] = levelNums[level] + 1;
499
500         # This is totally unnecessary, but nice; besides which, you can capture
501         # the output to a file to look at later if you like :-)
502         if verbose:
503                 for i in range(level):
504                         print('\t', end='')
505
506                 if (level == 0):
507                         print('\nPart ' + num2roman(levelNums[0]) + ': ', end='')
508                 elif (level == 1):
509                         print('\n\tChapter ' + str(levelNums[1]) + ': ', end='')
510
511                 print(header['title'])
512
513         # Handle TOC scriblings and one-page titles...
514         opl = ''
515         if 'link' in header:
516                 opl = ' id="' + header['link'] + '"'
517         else:
518                 opl = ' id="' + header['filename'] + '"'
519
520         if level == 0:
521                 toc = toc + '<h2>Part ' + num2roman(levelNums[level]) + ': ' + header['title'] + '</h2>\n';
522                 oph = '<h1 class="clear"' + opl +'>Part ' + num2roman(levelNums[level]) + ' - ' + header['title'] + '</h1>\n';
523         elif level == 1:
524                 toc = toc + '\t<p class="chapter">Ch. ' + str(levelNums[level]) + ':&nbsp;&nbsp;<a href="/' + header['filename'] + '/">' + header['title'] + '</a></p>\n'
525                 oph = '<h2 class="clear"' + opl +'>' + str(levelNums[level]) + ' - ' + header['title'] + '</h3>\n';
526         elif level == 2:
527                 toc = toc + '\t\t<p class="subchapter"><a href="/' + header['filename'] + '/">' + header['title'] + '</a></p>\n'
528                 oph = '<h3 class="clear"' + opl +'>' + str(levelNums[level-1]) + '.' + str(levelNums[level]) + ' - ' + header['title'] + '</h3>\n';
529
530         # Make the 'this thing contains...' stuff
531         if HaveChildren(fileStruct, pageNumber):
532                 pages = GetChildren(fileStruct, pageNumber)
533
534                 for pg in pages:
535                         more = more + '<li>' + '<a href="/' + fileStruct[pg]['filename'] + '/">' + fileStruct[pg]['title'] + '</a>' + '</li>\n'
536
537                 more = '<div id=subtopics>\n' + '<h2>This section contains the following topics:</h2>\n' + '<ul>\n' + more + '</ul>\n' + '</div>\n'
538
539         parent = GetParent(fileStruct, pageNumber)
540
541         # Make the 'Previous', 'Up' & 'Next' content
542         nLink = ''
543         pLink = ''
544         uLink = ''
545
546         if pageNumber > 0:
547                 pLink = '<li class="previous"><a title="' + fileStruct[pageNumber - 1]['title'] + '" href="/' + fileStruct[pageNumber - 1]['filename'] + '/" class="previous"> &larr; Previous </a></li>'
548
549         if pageNumber < len(fileStruct) - 1:
550                 nLink = '<li class="next"><a title="' + fileStruct[pageNumber + 1]['title'] + '" href="/' + fileStruct[pageNumber + 1]['filename'] + '/" class="next"> Next &rarr; </a></li>'
551
552         if level > 0:
553                 uLink = '<li><a title="' + fileStruct[parent]['title'] + '" href="/' + fileStruct[parent]['filename'] + '/" class="active"> &uarr; Up </a></li>'
554         else:
555                 uLink = '<li><a title="Ardour Table of Contents" href="/toc/index.html" class="active"> &uarr; Up </a></li>'
556
557         prevnext = '<ul class="pager">' + pLink + uLink + nLink + '</ul>'
558
559         # Make the BreadCrumbs
560         breadcrumbs = GetBreadCrumbs(fileStruct, pageNumber)
561
562         # Create the link sidebar
563         sidebar = CreateLinkSidebar(fileStruct, pageNumber, nodeChildren)
564
565         # Parts DO NOT have any content, they are ONLY an organizing construct!
566         # Chapters, subchapters, sections & subsections can all have content,
567         # but the basic fundamental organizing unit WRT content is still the
568         # chapter.
569         githubedit = ''
570         if level > 0:
571                 if 'include' in header:
572                         srcFile = open('include/' + header['include'])
573                         githubedit = '<span style="float:right;"><a title="Edit in GitHub" href="' + global_githuburl + header['include'] + '"><img src="/images/github.png" alt="Edit in GitHub"/></a></span>'
574                         content = srcFile.read()
575                         srcFile.close()
576
577                         # Get rid of any extant header in the include file
578                         # (once this is accepted, we can nuke this bit, as content files
579                         # will not have any headers or footers in them)
580                         content = re.sub('---.*\n(.*\n)*---.*\n', '', content)
581                         content = content.replace('{% children %}', '')
582
583                 else:
584                         if 'content' in header:
585                                 content = header['content']
586                         else:
587                                 content = '[something went wrong]'
588
589         # Add header information to the page if in dev mode
590         if devmode:
591                 devnote ='<aside style="background-color:indigo; color:white;">'
592                 if 'filename' in header:
593                         devnote = devnote + 'filename: ' + header['filename'] + '<br>'
594                 if 'include' in header:
595                         devnote = devnote + 'include: ' + header['include'] + '<br>'
596                 if 'link' in header:
597                         devnote = devnote + 'link: ' + header['link'] + '<br>'
598                 content = devnote + '</aside>' + content
599
600         # ----- One page and PDF version -----
601
602         # Fix up any internal links
603         opcontent = FixInternalLinks(oplinks, content, header['title'])
604         opcontent = reheader(opcontent, 2)
605
606         # Set up the actual page from the template
607         onepage = onepage.replace('{{ content }}', oph + '\n' + opcontent + '\n{{ content }}')
608         pdfpage = pdfpage.replace('{{ content }}', oph + '\n' + opcontent + '\n{{ content }}')
609
610         # ----- Normal version -----
611
612         # Fix up any internal links
613         content = FixInternalLinks(links, content, header['title'])
614
615         # Set up the actual page from the template
616         if 'style' not in header:
617                 page = re.sub("{% if page.style %}.*\n.*\n{% endif %}.*\n", "", template)
618         else:
619                 page = template.replace('{{page.style}}', header['style'])
620                 page = page.replace('{% if page.style %}', '')
621                 page = page.replace('{% endif %}', '')
622
623         page = page.replace('{{ page.title }}', header['title'])
624         page = page.replace('{% tree %}', sidebar)
625         page = page.replace('{% prevnext %}', prevnext)
626         page = page.replace('{% githubedit %}', githubedit)
627         page = page.replace('{% breadcrumbs %}', breadcrumbs)
628         page = page.replace('{{ content }}', content + more)
629
630         # Create the directory for the index.html file to go into (we use makedirs,
631         # because we have to in order to accomodate the 'uri' keyword)
632         os.makedirs(global_site_dir + header['filename'], 0o775, exist_ok=True)
633
634         # Finally, write the file!
635         destFile = open(global_site_dir + header['filename'] + '/index.html', 'w')
636         destFile.write(page)
637         destFile.close()
638
639         # Save filename for next header...
640         lastFile = header['filename']
641         pageNumber = pageNumber + 1
642
643 # Finally, create the TOC
644 sidebar = CreateLinkSidebar(fileStruct, -1, nodeChildren)
645
646 page = re.sub("{% if page.style %}.*\n.*\n{% endif %}.*\n", "", template)
647 page = page.replace('{{ page.title }}', 'Ardour Table of Contents')
648 page = page.replace('{% tree %}', sidebar)
649 page = page.replace('{{ content }}', toc)
650 page = page.replace('{% prevnext %}', '')
651 page = page.replace('{% githubedit %}', '')
652 page = page.replace('{% breadcrumbs %}', '')
653
654 os.mkdir(global_site_dir + 'toc', 0o775)
655 tocFile = open(global_site_dir + 'toc/index.html', 'w')
656 tocFile.write(page)
657 tocFile.close()
658
659 # Create the one-page version of the documentation
660 onepageFile = open(global_site_dir + 'ardourmanual.html', 'w')
661 opsidebar = BuildOnePageSidebar(fileStruct) # create the link sidebar
662 onepage = onepage.replace('{% tree %}', opsidebar)
663 onepage = onepage.replace('{{ content }}', '') # cleans up the last spaceholder
664 onepageFile.write(onepage)
665 onepageFile.close()
666
667 if not quiet:
668         print('Generating the PDF...')
669 # Create the PDF version of the documentation
670 pdfpageFile = open(global_site_dir + 'pdf.html', 'w')
671 pdfpage = pdfpage.replace('{% tree %}', opsidebar) # create the TOC
672 pdfpage = pdfpage.replace('{{ content }}', '') # cleans up the last spaceholder
673 pdfpageFile.write(pdfpage)
674 pdfpageFile.close()
675
676 from weasyprint import HTML
677 doc = HTML(filename = global_site_dir + 'pdf.html') #, base_url = os.path.dirname(os.path.realpath(__file__)))
678 doc.write_pdf(global_site_dir + 'manual.pdf')
679
680 if not quiet:
681         print('Processed ' + str(fileCount) + ' files.')