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