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