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