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 # This RE is shitty, but I can't think of a better one right now
27 fn = re.sub("[?!'&#:;_*()/\\,.]+", "", 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):
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)
216 # Recursively build a list of links based on the location of the page we're
217 # looking at currently
219 def BuildList(lst, fs, pagePos, cList):
220 content = '\n\n<dl>\n'
222 for i in range(len(lst)):
224 nextPos = lst[i + 1] if i + 1 < len(lst) else len(fs)
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 + '>'
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)
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)
239 content = content + '</dd>\n'
241 content = content + '</dl>\n'
246 # Create link sidebar given a position in the list.
248 def CreateLinkSidebar(fs, pos, childList):
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:]
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
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' ]
285 siteDir = './website/'
287 if os.access(siteDir, os.F_OK):
289 print('Removing stale HTML data...')
291 shutil.rmtree(siteDir)
293 shutil.copytree('./source', siteDir)
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')
301 # Read the template, and fix the stuff that's fixed for all pages
302 temp = open('page-template.txt')
303 template = temp.read()
306 template = template.replace('{{page.bootstrap_path}}', '/bootstrap-2.2.2')
307 template = template.replace('{{page.page_title}}', 'The Ardour Manual')
310 # Parse out the master docuemnt's structure into a dictionary list
311 fileStruct = GetFileStructure()
313 # Build a quasi-tree structure listing children at level + 1 for each node
314 nodeChildren = FindChildren(fileStruct)
316 # Create a dictionary for translation of internal links to real links
317 links = FindInternalLinks(fileStruct)
320 print('Found ' + str(len(links)) + ' internal link target', end='')
321 print('.') if len(links) == 1 else print('s.')
324 master = open('master-doc.txt')
325 firstLine = master.readline().rstrip('\r\n')
328 if firstLine == '<!-- exploded -->':
329 print('Parsing exploded file...')
330 elif firstLine == '<!-- imploded -->':
331 print('Parsing imploded file...')
333 print('Parsing unknown type...')
337 for header in fileStruct:
338 fileCount = fileCount + 1
343 level = header['level']
345 # Handle Part/Chapter/subchapter/section/subsection numbering
355 levelNums[level] = levelNums[level] + 1;
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 :-)
360 for i in range(level):
364 print('\nPart ' + roman[levelNums[0]] + ': ', end='')
366 print('\n\tChapter ' + str(levelNums[1]) + ': ', end='')
368 print(header['title'])
370 # Handle TOC scriblings...
372 toc = toc + '<h2>Part ' + roman[levelNums[level]] + ': ' + header['title'] + '</h2>\n';
374 toc = toc + ' <p id=chapter>Ch. ' + str(levelNums[level]) + ': <a href="/' + header['filename'] + '/">' + header['title'] + '</a></p>\n'
376 toc = toc + ' <a id=subchapter href="/' + header['filename'] + '/">' + header['title'] + '</a><br>\n'
378 toc = toc + ' <a id=subchapter href="/' + header['filename'] + '/">' + header['title'] + '</a><br>\n'
380 toc = toc + ' <a id=subchapter href="/' + header['filename'] + '/">' + header['title'] + '</a><br>\n'
382 # Make the 'this thing contains...' stuff
383 if HaveChildren(fileStruct, pageNumber):
384 pages = GetChildren(fileStruct, pageNumber)
387 more = more + '<li>' + '<a href="/' + fileStruct[pg]['filename'] + '/">' + fileStruct[pg]['title'] + '</a>' + '</li>\n'
389 more = '<div id=subtopics>\n' + '<h2>This section contains the following topics:</h2>\n' + '<ul>\n' + more + '</ul>\n' + '</div>\n'
391 # Make the 'Previous' & 'Next' content
396 pLink = '<li><a title="' + fileStruct[pageNumber - 1]['title'] + '" href="/' + fileStruct[pageNumber - 1]['filename'] + '" class="previous"> < Previous </a></li>'
398 if pageNumber < len(fileStruct) - 1:
399 nLink = '<li><a title="' + fileStruct[pageNumber + 1]['title'] + '" href="/' + fileStruct[pageNumber + 1]['filename'] + '" class="next"> Next > </a></li>'
401 prevnext = '<ul class=pager>' + pLink + nLink + '</ul>'
403 # Create the link sidebar
404 sidebar = CreateLinkSidebar(fileStruct, pageNumber, nodeChildren)
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
411 if 'include' in header:
412 srcFile = open('include/' + header['include'])
413 content = srcFile.read()
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 %}', '')
423 if 'content' in header:
424 content = header['content']
426 content = '[something went wrong]'
428 # Fix up any internal links
429 content = FixInternalLinks(links, content)
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)
435 page = template.replace('{{page.style}}', header['style'])
436 page = page.replace('{% if page.style %}', '')
437 page = page.replace('{% endif %}', '')
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)
444 # Create the directory for the index.html file to go into
445 os.mkdir(siteDir + header['filename'], 0o775)
447 # Finally, write the file!
448 destFile = open(siteDir + header['filename'] + '/index.html', 'w')
452 # Save filename for next header...
453 lastFile = header['filename']
454 pageNumber = pageNumber + 1
456 # Finally, create the TOC
457 sidebar = CreateLinkSidebar(fileStruct, -1, nodeChildren)
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 %}', '')
465 os.mkdir(siteDir + 'toc', 0o775)
466 tocFile = open(siteDir + 'toc/index.html', 'w')
471 print('Processed ' + str(fileCount) + ' files.')