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 # This matches all *non* letter/number, ' ', '.', '-', and '_' chars
23 cleanString = re.compile(r'[^a-zA-Z0-9 \._-]+')
24 # This matches new 'unbreakable' links, up to the closing quote or anchor
25 findLinks = re.compile(r'@@[^#"]*')
28 # Create an all lowercase filename without special characters and with spaces
29 # replaced with dashes.
33 # Clean up the file name, removing all non letter/number or " .-_" chars.
34 # Also, convert to lower case and replace all spaces with dashes.
35 fn = cleanString.sub('', s).lower().replace(' ', '-')
36 # Double dashes can creep in from the above replacement, so we check for
38 fn = fn.replace('--', '-')
44 # Parse headers into a dictionary
46 def ParseHeader(fileObj):
50 hdrLine = fileObj.readline().rstrip('\r\n')
52 # Break out of the loop if we hit the end of header marker
53 if hdrLine.startswith('---'):
56 # Check to see that we have a well-formed header construct
57 match = re.findall(': ', hdrLine)
60 # Parse out foo: bar pairs & put into header dictionary
61 a = re.split(': ', hdrLine, 1)
68 # Turn a "part" name into an int
77 elif s == 'subchapter':
81 elif s == 'subsection':
87 # Converts a integer to a roman number
90 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')]
102 # Capture the master document's structure (and content, if any) in a list
104 def GetFileStructure():
109 mf = open('master-doc.txt')
112 if ln.startswith('---'):
113 # First, stuff any content that we may have read into the current
114 # header's dictionary
116 fs[-1]['content'] = content
120 # Then, get the new header and do things to it
121 hdr = ParseHeader(mf)
122 level = PartToLevel(hdr['part'])
124 fnames[level] = MakeFilename(hdr['title'])
126 # Ickyness--user specified URIs
128 hdr['filename'] = hdr['uri']
132 for i in range(level + 1):
133 fullName = fullName + fnames[i] + '/'
135 # Strip trailing '/' on filename
136 hdr['filename'] = fullName[:-1]
140 if ('include' not in hdr) and (level > 0):
144 content = content + ln
146 # Catch the last file, since it would be missed above
148 fs[-1]['content'] = content
155 # Determine if a particular node has child nodes
157 def HaveChildren(fs, pos):
158 # If we're at the end of the list, there can be no children
159 if pos == len(fs) - 1:
162 # If the next node is at a lower level than the current node, we have
164 if fs[pos]['level'] < fs[pos + 1]['level']:
167 # Otherwise, no children at this node.
172 # Get the children at this level, and return them in a list
174 def GetChildren(fs, pos):
177 childLevel = fs[pos]['level']
179 while fs[pos]['level'] >= childLevel:
180 if fs[pos]['level'] == childLevel:
193 # Get the parent at this level
195 def GetParent(fs, pos):
196 thisLevel = fs[pos]['level']
199 while pos >= 0 and fs[pos]['level'] >= thisLevel:
206 # Creates the BreadCrumbs
208 def GetBreadCrumbs(fs, pos):
209 # The <span class="divider">></span> is for Bootstrap pre-3.0
210 breadcrumbs = ' <span class="divider">></span> <li class="active">'+ fs[pos]['title'] + '</li>'
213 pos = GetParent(fs, pos)
216 breadcrumbs=' <span class="divider">></span> <li><a href="/' + fs[pos]['filename'] + '/">'+ fs[pos]['title'] + '</a></li>'+ breadcrumbs
218 breadcrumbs = '<ol class="breadcrumb"><li><a href="/toc/index.html">Home</a></li>' + breadcrumbs + '</ol>'
223 # Make an array of children attached to each node in the file structure
224 # (It's a quasi-tree structure, and can be traversed as such.)
226 def FindChildren(fs):
229 for i in range(len(fs)):
230 if HaveChildren(fs, i):
231 childArray.append(GetChildren(fs, i))
233 childArray.append([])
239 # Make an array of the top level nodes in the file structure
241 def FindTopLevelNodes(fs):
244 for i in range(len(fs)):
245 if fs[i]['level'] == 0:
252 # Find all header links and create a dictionary out of them
254 def FindInternalLinks(fs):
259 linkDict['@@' + hdr['link']] = '/' + hdr['filename'] + '/'
265 # Internal links are of the form '@@link-name', which are references to the
266 # 'link:' field in the part header. We have to find all occurances and replace
267 # them with the appropriate link.
269 def FixInternalLinks(links, content, title):
271 match = findLinks.findall(content)
277 content = content.replace(s, links[s])
281 # Report missing link targets to the user (if any)
283 print('\nMissing link target' + ('s' if len(missing) > 1 else '') + ' in "' + title + '":')
294 # Recursively build a list of links based on the location of the page we're
295 # looking at currently
297 def BuildList(lst, fs, pagePos, cList):
298 content = '\n\n<dl>\n'
300 for i in range(len(lst)):
302 nextPos = lst[i + 1] if i + 1 < len(lst) else len(fs)
304 active = ' class=active' if curPos == pagePos else ''
305 menuTitle = fs[curPos]['menu_title'] if 'menu_title' in fs[curPos] else fs[curPos]['title']
306 content = content + '<dt' + active + '><a href="/' + fs[curPos]['filename'] + '/">' + menuTitle + '</a></dt><dd' + active + '>'
308 # If the current page is our page, and it has children, enumerate them
309 if curPos == pagePos:
310 if len(cList[curPos]) > 0:
311 content = content + BuildList(cList[curPos], fs, -1, cList)
313 # Otherwise, if our page lies between the current one and the next,
314 # build a list of links from those nodes one level down.
315 elif (pagePos > curPos) and (pagePos < nextPos):
316 content = content + BuildList(cList[curPos], fs, pagePos, cList)
318 content = content + '</dd>\n'
320 content = content + '</dl>\n'
325 # Create link sidebar given a position in the list.
327 def CreateLinkSidebar(fs, pos, childList):
329 # Build the list recursively from the top level nodes
330 content = BuildList(FindTopLevelNodes(fs), fs, pos, childList)
331 # Shove the TOC link in the top...
332 content = content[:7] + '<dt><a href="/toc/">Table of Contents</a></dt><dd></dd>\n' + content[7:]
339 # We have command line arguments now, so deal with them
340 parser = argparse.ArgumentParser(description='A build script for the Ardour Manual')
341 parser.add_argument('-v', '--verbose', action='store_true', help='Display the high-level structure of the manual')
342 parser.add_argument('-q', '--quiet', action='store_true', help='Suppress all output (overrides -v)')
343 parser.add_argument('-d', '--devmode', action='store_true', help='Add content to pages to help developers debug them')
344 args = parser.parse_args()
345 verbose = args.verbose
347 devmode = args.devmode
360 siteDir = './website/'
362 if not quiet and devmode:
363 print('Devmode active: scribbling extra junk to the manual...')
365 if os.access(siteDir, os.F_OK):
367 print('Removing stale HTML data...')
369 shutil.rmtree(siteDir)
371 shutil.copytree('./source', siteDir)
374 # Read the template, and fix the stuff that's fixed for all pages
375 temp = open('page-template.txt')
376 template = temp.read()
379 template = template.replace('{{page.bootstrap_path}}', '/bootstrap-2.2.2')
380 template = template.replace('{{page.page_title}}', 'The Ardour Manual')
383 # Parse out the master docuemnt's structure into a dictionary list
384 fileStruct = GetFileStructure()
386 # Build a quasi-tree structure listing children at level + 1 for each node
387 nodeChildren = FindChildren(fileStruct)
389 # Create a dictionary for translation of internal links to real links
390 links = FindInternalLinks(fileStruct)
393 print('Found ' + str(len(links)) + ' internal link target', end='')
394 print('.') if len(links) == 1 else print('s.')
397 master = open('master-doc.txt')
398 firstLine = master.readline().rstrip('\r\n')
401 if firstLine == '<!-- exploded -->':
402 print('Parsing exploded file...')
403 elif firstLine == '<!-- imploded -->':
404 print('Parsing imploded file...')
406 print('Parsing unknown type...')
410 for header in fileStruct:
411 fileCount = fileCount + 1
416 level = header['level']
418 # Handle Part/Chapter/subchapter/section/subsection numbering
428 levelNums[level] = levelNums[level] + 1;
430 # This is totally unnecessary, but nice; besides which, you can capture
431 # the output to a file to look at later if you like :-)
433 for i in range(level):
437 print('\nPart ' + num2roman(levelNums[0]) + ': ', end='')
439 print('\n\tChapter ' + str(levelNums[1]) + ': ', end='')
441 print(header['title'])
443 # Handle TOC scriblings...
445 toc = toc + '<h2>Part ' + num2roman(levelNums[level]) + ': ' + header['title'] + '</h2>\n';
447 toc = toc + ' <p id=chapter>Ch. ' + str(levelNums[level]) + ': <a href="/' + header['filename'] + '/">' + header['title'] + '</a></p>\n'
449 toc = toc + ' <a id=subchapter href="/' + header['filename'] + '/">' + header['title'] + '</a><br>\n'
451 toc = toc + ' <a id=section href="/' + header['filename'] + '/">' + header['title'] + '</a><br>\n'
453 toc = toc + ' <a id=subsection href="/' + header['filename'] + '/">' + header['title'] + '</a><br>\n'
455 # Make the 'this thing contains...' stuff
456 if HaveChildren(fileStruct, pageNumber):
457 pages = GetChildren(fileStruct, pageNumber)
460 more = more + '<li>' + '<a href="/' + fileStruct[pg]['filename'] + '/">' + fileStruct[pg]['title'] + '</a>' + '</li>\n'
462 more = '<div id=subtopics>\n' + '<h2>This section contains the following topics:</h2>\n' + '<ul>\n' + more + '</ul>\n' + '</div>\n'
464 parent = GetParent(fileStruct, pageNumber)
466 # Make the 'Previous' & 'Next' content
472 pLink = '<li><a title="' + fileStruct[pageNumber - 1]['title'] + '" href="/' + fileStruct[pageNumber - 1]['filename'] + '/" class="previous"> ← Previous </a></li>'
474 if pageNumber < len(fileStruct) - 1:
475 nLink = '<li><a title="' + fileStruct[pageNumber + 1]['title'] + '" href="/' + fileStruct[pageNumber + 1]['filename'] + '/" class="next"> Next → </a></li>'
478 uLink = '<li><a title="' + fileStruct[parent]['title'] + '" href="/' + fileStruct[parent]['filename'] + '/" class="active"> ↑ Up </a></li>'
480 uLink = '<li><a title="Ardour Table of Contents" href="/toc/index.html" class="active"> ↑ Up </a></li>'
482 prevnext = '<ul class=pager>' + pLink + uLink + nLink + '</ul>'
484 # Make the BreadCrumbs
485 breadcrumbs = GetBreadCrumbs(fileStruct, pageNumber)
487 # Create the link sidebar
488 sidebar = CreateLinkSidebar(fileStruct, pageNumber, nodeChildren)
490 # Parts DO NOT have any content, they are ONLY an organizing construct!
491 # Chapters, subchapters, sections & subsections can all have content,
492 # but the basic fundamental organizing unit WRT content is still the
495 if 'include' in header:
496 srcFile = open('include/' + header['include'])
497 content = srcFile.read()
500 # Get rid of any extant header in the include file
501 # (once this is accepted, we can nuke this bit, as content files
502 # will not have any headers or footers in them)
503 content = re.sub('---.*\n(.*\n)*---.*\n', '', content)
504 content = content.replace('{% children %}', '')
507 if 'content' in header:
508 content = header['content']
510 content = '[something went wrong]'
512 # Fix up any internal links
513 content = FixInternalLinks(links, content, header['title'])
515 # Add header information to the page if in dev mode
517 devnote ='<aside style="background-color:indigo; color:white;">'
518 if 'filename' in header:
519 devnote = devnote + 'filename: ' + header['filename'] + '<br>'
520 if 'include' in header:
521 devnote = devnote + 'include: ' + header['include'] + '<br>'
523 devnote = devnote + 'link: ' + header['link'] + '<br>'
524 content = devnote + '</aside>' + content
526 # Set up the actual page from the template
527 if 'style' not in header:
528 page = re.sub("{% if page.style %}.*\n.*\n{% endif %}.*\n", "", template)
530 page = template.replace('{{page.style}}', header['style'])
531 page = page.replace('{% if page.style %}', '')
532 page = page.replace('{% endif %}', '')
534 page = page.replace('{{ page.title }}', header['title'])
535 page = page.replace('{% tree %}', sidebar)
536 page = page.replace('{% prevnext %}', prevnext)
537 page = page.replace('{% breadcrumbs %}', breadcrumbs)
538 page = page.replace('{{ content }}', content + more)
540 # Create the directory for the index.html file to go into (we use makedirs,
541 # because we have to in order to accomodate the 'uri' keyword)
542 os.makedirs(siteDir + header['filename'], 0o775, exist_ok=True)
544 # Finally, write the file!
545 destFile = open(siteDir + header['filename'] + '/index.html', 'w')
549 # Save filename for next header...
550 lastFile = header['filename']
551 pageNumber = pageNumber + 1
553 # Finally, create the TOC
554 sidebar = CreateLinkSidebar(fileStruct, -1, nodeChildren)
556 page = re.sub("{% if page.style %}.*\n.*\n{% endif %}.*\n", "", template)
557 page = page.replace('{{ page.title }}', 'Ardour Table of Contents')
558 page = page.replace('{% tree %}', sidebar)
559 page = page.replace('{{ content }}', toc)
560 page = page.replace('{% prevnext %}', '')
561 page = page.replace('{% breadcrumbs %}', '')
563 os.mkdir(siteDir + 'toc', 0o775)
564 tocFile = open(siteDir + 'toc/index.html', 'w')
569 print('Processed ' + str(fileCount) + ' files.')