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