3 # Script to take the master document and ancillary files and create the
4 # finished manual/website.
7 # (C) 2017 Underground Software
10 # Remnants (could go into the master document as the first header)
12 #bootstrap_path: /bootstrap-2.2.2
13 #page_title: The Ardour Manual
22 # Create an all lowercase filename without special characters and with spaces
23 # replaced with dashes.
26 # Cleans up the file name, removing all non ASCII or .-_ chars
27 fn = re.sub(r'[^.\-_a-zA-Z0-9 ]', '', s)
29 fn = fn.replace(' ', '-')
34 # Parse headers into a dictionary
36 def ParseHeader(fileObj):
40 hdrLine = fileObj.readline().rstrip('\r\n')
42 # Break out of the loop if we hit the end of header marker
43 if hdrLine.startswith('---'):
46 # Parse out foo: bar pairs & put into header dictionary
47 a = re.split(': ', hdrLine, 1)
54 # Turn a "part" name into an int
63 elif s == 'subchapter':
67 elif s == 'subsection':
74 # Capture the master document's structure (and content, if any) in a list
76 def GetFileStructure():
81 mf = open('master-doc.txt')
84 if ln.startswith('---'):
85 # First, stuff any content that we may have read into the current
88 fs[-1]['content'] = content
92 # Then, get the new header and do things to it
94 level = PartToLevel(hdr['part'])
96 fnames[level] = MakeFilename(hdr['title'])
99 for i in range(level + 1):
100 fullName = fullName + fnames[i] + '/'
102 hdr['filename'] = fullName.rstrip('/')
105 if ('include' not in hdr) and (level > 0):
109 content = content + ln
111 # Catch the last file, since it would be missed above
113 fs[-1]['content'] = content
120 # Determine if a particular node has child nodes
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:
127 # If the next node is at a lower level than the current node, we have
129 if fs[pos]['level'] < fs[pos + 1]['level']:
132 # Otherwise, no children at this node.
137 # Get the children at this level, and return them in a list
139 def GetChildren(fs, pos):
142 childLevel = fs[pos]['level']
144 while fs[pos]['level'] >= childLevel:
145 if fs[pos]['level'] == childLevel:
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.)
161 def FindChildren(fs):
164 for i in range(len(fs)):
165 if HaveChildren(fs, i):
166 childArray.append(GetChildren(fs, i))
168 childArray.append([])
174 # Make an array of the top level nodes in the file structure
176 def FindTopLevelNodes(fs):
179 for i in range(len(fs)):
180 if fs[i]['level'] == 0:
187 # Find all header links and create a dictionary out of them
189 def FindInternalLinks(fs):
194 linkDict['@@' + hdr['link']] = '/' + hdr['filename'] + '/'
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.
204 def FixInternalLinks(links, content, title):
206 # Make key1|key2|key3|... out of our links keys
207 pattern = re.compile('|'.join(links.keys()))
209 # Use a lambda callback to substitute each occurance found
210 result = pattern.sub(lambda x: links[x.group()], content)
212 # Check for missing link targets, and report them to the user
213 match = re.findall('"@@.*"', result)
216 print('\nMissing link target' + ('s' if len(match) > 1 else '') + ' in "' + title + '":')
227 # Recursively build a list of links based on the location of the page we're
228 # looking at currently
230 def BuildList(lst, fs, pagePos, cList):
231 content = '\n\n<dl>\n'
233 for i in range(len(lst)):
235 nextPos = lst[i + 1] if i + 1 < len(lst) else len(fs)
237 active = ' class=active' if curPos == pagePos else ''
238 content = content + '<dt' + active + '><a href="/' + fs[curPos]['filename'] + '/">' + fs[curPos]['title'] + '</a></dt><dd' + active + '>'
240 # If the current page is our page, and it has children, enumerate them
241 if curPos == pagePos:
242 if len(cList[curPos]) > 0:
243 content = content + BuildList(cList[curPos], fs, -1, cList)
245 # Otherwise, if our page lies between the current one and the next,
246 # build a list of links from those nodes one level down.
247 elif (pagePos > curPos) and (pagePos < nextPos):
248 content = content + BuildList(cList[curPos], fs, pagePos, cList)
250 content = content + '</dd>\n'
252 content = content + '</dl>\n'
257 # Create link sidebar given a position in the list.
259 def CreateLinkSidebar(fs, pos, childList):
261 # Build the list recursively from the top level nodes
262 content = BuildList(FindTopLevelNodes(fs), fs, pos, childList)
263 # Shove the TOC link in the top...
264 content = content[:7] + '<dt><a href="/toc/">Table of Contents</a></dt><dd></dd>\n' + content[7:]
271 # We have command line arguments now, so deal with them
272 parser = argparse.ArgumentParser(description='A build script for the Ardour Manual')
273 parser.add_argument('-v', '--verbose', action='store_true', help='Display the high-level structure of the manual')
274 parser.add_argument('-q', '--quiet', action='store_true', help='Suppress all output (overrides -v)')
275 args = parser.parse_args()
276 verbose = args.verbose
283 roman = [ '0', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X',
284 'XI', 'XII', 'XIII', 'XIV', 'XV', 'XVI', 'XVII', 'XVIII', 'XIX', 'XX',
285 'XXI', 'XXII', 'XXIII', 'XXIV', 'XXV', 'XXVI', 'XXVII', 'XXVIII', 'XXIX', 'XXX' ]
296 siteDir = './website/'
298 if os.access(siteDir, os.F_OK):
300 print('Removing stale HTML data...')
302 shutil.rmtree(siteDir)
304 shutil.copytree('./source', siteDir)
306 # Yeah, need to make a symlink in include/ too :-P
307 # [this will go away when the rewrite happens]
308 if (os.access('include/_manual', os.F_OK) == False):
309 os.symlink('../_manual/', 'include/_manual')
312 # Read the template, and fix the stuff that's fixed for all pages
313 temp = open('page-template.txt')
314 template = temp.read()
317 template = template.replace('{{page.bootstrap_path}}', '/bootstrap-2.2.2')
318 template = template.replace('{{page.page_title}}', 'The Ardour Manual')
321 # Parse out the master docuemnt's structure into a dictionary list
322 fileStruct = GetFileStructure()
324 # Build a quasi-tree structure listing children at level + 1 for each node
325 nodeChildren = FindChildren(fileStruct)
327 # Create a dictionary for translation of internal links to real links
328 links = FindInternalLinks(fileStruct)
331 print('Found ' + str(len(links)) + ' internal link target', end='')
332 print('.') if len(links) == 1 else print('s.')
335 master = open('master-doc.txt')
336 firstLine = master.readline().rstrip('\r\n')
339 if firstLine == '<!-- exploded -->':
340 print('Parsing exploded file...')
341 elif firstLine == '<!-- imploded -->':
342 print('Parsing imploded file...')
344 print('Parsing unknown type...')
348 for header in fileStruct:
349 fileCount = fileCount + 1
354 level = header['level']
356 # Handle Part/Chapter/subchapter/section/subsection numbering
366 levelNums[level] = levelNums[level] + 1;
368 # This is totally unnecessary, but nice; besides which, you can capture
369 # the output to a file to look at later if you like :-)
371 for i in range(level):
375 print('\nPart ' + roman[levelNums[0]] + ': ', end='')
377 print('\n\tChapter ' + str(levelNums[1]) + ': ', end='')
379 print(header['title'])
381 # Handle TOC scriblings...
383 toc = toc + '<h2>Part ' + roman[levelNums[level]] + ': ' + header['title'] + '</h2>\n';
385 toc = toc + ' <p id=chapter>Ch. ' + str(levelNums[level]) + ': <a href="/' + header['filename'] + '/">' + header['title'] + '</a></p>\n'
387 toc = toc + ' <a id=subchapter href="/' + header['filename'] + '/">' + header['title'] + '</a><br>\n'
389 toc = toc + ' <a id=subchapter href="/' + header['filename'] + '/">' + header['title'] + '</a><br>\n'
391 toc = toc + ' <a id=subchapter href="/' + header['filename'] + '/">' + header['title'] + '</a><br>\n'
393 # Make the 'this thing contains...' stuff
394 if HaveChildren(fileStruct, pageNumber):
395 pages = GetChildren(fileStruct, pageNumber)
398 more = more + '<li>' + '<a href="/' + fileStruct[pg]['filename'] + '/">' + fileStruct[pg]['title'] + '</a>' + '</li>\n'
400 more = '<div id=subtopics>\n' + '<h2>This section contains the following topics:</h2>\n' + '<ul>\n' + more + '</ul>\n' + '</div>\n'
402 # Make the 'Previous' & 'Next' content
407 pLink = '<li><a title="' + fileStruct[pageNumber - 1]['title'] + '" href="/' + fileStruct[pageNumber - 1]['filename'] + '" class="previous"> < Previous </a></li>'
409 if pageNumber < len(fileStruct) - 1:
410 nLink = '<li><a title="' + fileStruct[pageNumber + 1]['title'] + '" href="/' + fileStruct[pageNumber + 1]['filename'] + '" class="next"> Next > </a></li>'
412 prevnext = '<ul class=pager>' + pLink + nLink + '</ul>'
414 # Create the link sidebar
415 sidebar = CreateLinkSidebar(fileStruct, pageNumber, nodeChildren)
417 # Parts DO NOT have any content, they are ONLY an organizing construct!
418 # Chapters, subchapters, sections & subsections can all have content,
419 # but the basic fundamental organizing unit WRT content is still the
422 if 'include' in header:
423 srcFile = open('include/' + header['include'])
424 content = srcFile.read()
427 # Get rid of any extant header in the include file
428 # (once this is accepted, we can nuke this bit, as content files
429 # will not have any headers or footers in them)
430 content = re.sub('---.*\n(.*\n)*---.*\n', '', content)
431 content = content.replace('{% children %}', '')
434 if 'content' in header:
435 content = header['content']
437 content = '[something went wrong]'
439 # Fix up any internal links
440 content = FixInternalLinks(links, content, header['title'])
442 # Set up the actual page from the template
443 if 'style' not in header:
444 page = re.sub("{% if page.style %}.*\n.*\n{% endif %}.*\n", "", template)
446 page = template.replace('{{page.style}}', header['style'])
447 page = page.replace('{% if page.style %}', '')
448 page = page.replace('{% endif %}', '')
450 page = page.replace('{{ page.title }}', header['title'])
451 page = page.replace('{% tree %}', sidebar)
452 page = page.replace('{% prevnext %}', prevnext)
453 page = page.replace('{{ content }}', content + more)
455 # Create the directory for the index.html file to go into
456 os.mkdir(siteDir + header['filename'], 0o775)
458 # Finally, write the file!
459 destFile = open(siteDir + header['filename'] + '/index.html', 'w')
463 # Save filename for next header...
464 lastFile = header['filename']
465 pageNumber = pageNumber + 1
467 # Finally, create the TOC
468 sidebar = CreateLinkSidebar(fileStruct, -1, nodeChildren)
470 page = re.sub("{% if page.style %}.*\n.*\n{% endif %}.*\n", "", template)
471 page = page.replace('{{ page.title }}', 'Ardour Table of Contents')
472 page = page.replace('{% tree %}', sidebar)
473 page = page.replace('{{ content }}', toc)
474 page = page.replace('{% prevnext %}', '')
476 os.mkdir(siteDir + 'toc', 0o775)
477 tocFile = open(siteDir + 'toc/index.html', 'w')
482 print('Processed ' + str(fileCount) + ' files.')