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