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