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)
19 global_bootstrap_path = '/bootstrap-3.3.7'
20 global_page_title = 'The Ardour Manual'
21 global_site_dir = './website/'
22 global_githuburl = 'https://github.com/Ardour/manual/edit/master/include/'
23 global_screen_template = 'page-template.html'
24 global_onepage_template = 'onepage-template.html'
25 global_pdf_template = 'pdf-template.html'
26 global_master_doc = 'master-doc.txt'
28 # This matches all *non* letter/number, ' ', '.', '-', and '_' chars
29 cleanString = re.compile(r'[^a-zA-Z0-9 \._-]+')
30 # This matches new 'unbreakable' links, up to the closing quote or anchor
31 findLinks = re.compile(r'"@@[^#"]*[#"]')
34 # Create an all lowercase filename without special characters and with spaces
35 # replaced with dashes.
39 # Clean up the file name, removing all non letter/number or " .-_" chars.
40 # Also, convert to lower case and replace all spaces with dashes.
41 fn = cleanString.sub('', s).lower().replace(' ', '-')
42 # Double dashes can creep in from the above replacement, so we check for
44 fn = fn.replace('--', '-')
50 # Parse headers into a dictionary
52 def ParseHeader(fileObj):
56 hdrLine = fileObj.readline().rstrip('\r\n')
58 # Break out of the loop if we hit the end of header marker
59 if hdrLine.startswith('---'):
62 # Check to see that we have a well-formed header construct
63 match = re.findall(': ', hdrLine)
66 # Parse out foo: bar pairs & put into header dictionary
67 a = re.split(': ', hdrLine, 1)
74 # Turn a "part" name into an int
78 lvl = {'part': 0, 'chapter': 1, 'subchapter': 2}
86 # Converts a integer to a roman number
89 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')]
101 # Capture the master document's structure (and content, if any) in a list
103 def GetFileStructure():
108 mf = open(global_master_doc)
111 if ln.startswith('---'):
112 # First, stuff any content that we may have read into the current
113 # header's dictionary
115 fs[-1]['content'] = content
119 # Then, get the new header and do things to it
120 hdr = ParseHeader(mf)
121 level = PartToLevel(hdr['part'])
123 fnames[level] = MakeFilename(hdr['title'])
125 # Ickyness--user specified URIs
127 hdr['filename'] = hdr['uri']
131 for i in range(level + 1):
132 fullName = fullName + fnames[i] + '/'
134 # Strip trailing '/' on filename
135 hdr['filename'] = fullName[:-1]
139 if ('include' not in hdr) and (level > 0):
143 content = content + ln
145 # Catch the last file, since it would be missed above
147 fs[-1]['content'] = content
154 # Determine if a particular node has child nodes
156 def HaveChildren(fs, pos):
157 # If we're at the end of the list, there can be no children
158 if pos == len(fs) - 1:
161 # If the next node is at a lower level than the current node, we have
163 if fs[pos]['level'] < fs[pos + 1]['level']:
166 # Otherwise, no children at this node.
171 # Get the children at this level, and return them in a list
173 def GetChildren(fs, pos):
176 childLevel = fs[pos]['level']
178 while fs[pos]['level'] >= childLevel:
179 if fs[pos]['level'] == childLevel:
192 # Get the parent at this level
194 def GetParent(fs, pos):
195 thisLevel = fs[pos]['level']
198 while pos >= 0 and fs[pos]['level'] >= thisLevel:
204 # Change the hierarchy of titles : h1->hn, h2->hn+1, etc... n being delta-1
206 def reheader(txt, delta):
207 for i in range(6, 0, -1):
208 txt = txt.replace('<h' + str(i),'<h' + str(i+delta))
209 txt = txt.replace('</h' + str(i),'</h' + str(i+delta))
213 # Creates the BreadCrumbs
215 def GetBreadCrumbs(fs, pos):
216 breadcrumbs = '<li class="active">'+ fs[pos]['title'] + '</li>'
219 pos = GetParent(fs, pos)
222 breadcrumbs='<li><a href="/' + fs[pos]['filename'] + '/">'+ fs[pos]['title'] + '</a></li>'+ breadcrumbs
224 breadcrumbs = '<ul class="breadcrumb"><li><a href="/toc/index.html">Home</a></li>' + breadcrumbs + '</ul>'
229 # Make an array of children attached to each node in the file structure
230 # (It's a quasi-tree structure, and can be traversed as such.)
232 def FindChildren(fs):
235 for i in range(len(fs)):
236 if HaveChildren(fs, i):
237 childArray.append(GetChildren(fs, i))
239 childArray.append([])
245 # Make an array of the top level nodes in the file structure
247 def FindTopLevelNodes(fs):
250 for i in range(len(fs)):
251 if fs[i]['level'] == 0:
258 # Find all header links and create a dictionary out of them
260 def FindInternalLinks(fs):
265 linkDict['"@@' + hdr['link'] + '"'] = '"/' + hdr['filename'] + '/"'
266 linkDict['"@@' + hdr['link'] + '#'] = '"/' + hdr['filename'] + '/index.html#'
272 # Same as above, but create anchors (for the one-page version)
274 def FindInternalAnchors(fs):
279 linkDict['"@@' + hdr['link'] + '"'] = '"#' + hdr['link'] + '"'
280 linkDict['"@@' + hdr['link'] + '#'] = '"#' + hdr['link'] + '"'
287 # Internal links are of the form '@@link-name', which are references to the
288 # 'link:' field in the part header. We have to find all occurrences and replace
289 # them with the appropriate link.
291 def FixInternalLinks(links, content, title):
293 match = findLinks.findall(content)
299 content = content.replace(s, links[s])
303 # Report missing link targets to the user (if any)
305 print('\nMissing link target' + ('s' if len(missing) > 1 else '') + ' in "' + title + '":')
316 # Recursively build a list of links based on the location of the page we're
317 # looking at currently
319 def BuildList(lst, fs, pagePos, cList):
320 content = '\n\n<ul>\n'
322 for i in range(len(lst)):
324 nextPos = lst[i + 1] if i + 1 < len(lst) else len(fs)
326 active = ' class=active' if curPos == pagePos else ''
327 menuTitle = fs[curPos]['menu_title'] if 'menu_title' in fs[curPos] else fs[curPos]['title']
328 content = content + '<li' + active + '><a href="/' + fs[curPos]['filename'] + '/">' + menuTitle + '</a></li>'
330 # If the current page is our page, and it has children, enumerate them
331 if curPos == pagePos:
332 if len(cList[curPos]) > 0:
333 content = content + BuildList(cList[curPos], fs, -1, cList)
335 # Otherwise, if our page lies between the current one and the next,
336 # build a list of links from those nodes one level down.
337 elif (pagePos > curPos) and (pagePos < nextPos):
338 content = content + BuildList(cList[curPos], fs, pagePos, cList)
340 content = content + '\n</ul>\n'
346 # Builds the sidebar for the one-page version
348 def BuildOnePageSidebar(fs):
350 content = '\n\n<ul class="toc" style="white-space:nowrap;">\n'
354 for i in range(len(fs)):
355 # Handle Part/Chapter/subchapter/section/subsection numbering
356 level = fs[i]['level']
359 levelNums[level] = levelNums[level] + 1;
362 while j > 0: #level 0 is the part number which is not shown
363 txtlevel = str(levelNums[j]) + '.' + txtlevel
365 if len(txtlevel) > 0:
366 txtlevel = txtlevel[:-1] + ' - '
369 anchor = fs[i]['link']
371 anchor = fs[i]['filename']
374 content = content + '<ul style="white-space:nowrap;">\n'
377 content = content + '</ul>\n'
380 content = content + '<li><a href="#' + anchor + '">' + txtlevel + fs[i]['title'] + '</a></li>\n'
382 content = content + '</ul>\n'
388 # Create link sidebar given a position in the list.
390 def CreateLinkSidebar(fs, pos, childList):
392 # Build the list recursively from the top level nodes
393 content = BuildList(FindTopLevelNodes(fs), fs, pos, childList)
394 # Shove the TOC link and one file link at the top...
395 active = ' class=active' if pos<0 else ''
396 content = content.replace('<ul>','<ul><li' + active + '><a href="/toc/">Table of Contents</a></li>\n',1)
402 # We have command line arguments now, so deal with them
403 parser = argparse.ArgumentParser(description='A build script for the Ardour Manual')
404 parser.add_argument('-v', '--verbose', action='store_true', help='Display the high-level structure of the manual')
405 parser.add_argument('-q', '--quiet', action='store_true', help='Suppress all output (overrides -v)')
406 parser.add_argument('-d', '--devmode', action='store_true', help='Add content to pages to help developers debug them')
407 args = parser.parse_args()
408 verbose = args.verbose
410 devmode = args.devmode
427 if not quiet and devmode:
428 print('Devmode active: scribbling extra junk to the manual...')
430 if os.access(global_site_dir, os.F_OK):
432 print('Removing stale HTML data...')
434 shutil.rmtree(global_site_dir)
436 shutil.copytree('./source', global_site_dir)
439 # Read the template, and fix the stuff that's fixed for all pages
440 temp = open(global_screen_template)
441 template = temp.read()
443 template = template.replace('{{page.bootstrap_path}}', global_bootstrap_path)
444 template = template.replace('{{page.page_title}}', global_page_title)
446 # Same as above, but for the One-page version
447 temp = open(global_onepage_template)
448 onepage = temp.read()
450 onepage = onepage.replace('{{page.bootstrap_path}}', global_bootstrap_path)
451 onepage = onepage.replace('{{page.page_title}}', global_page_title)
453 # Same as above, but for the PDF version
454 temp = open(global_pdf_template)
455 pdfpage = temp.read()
457 pdfpage = pdfpage.replace('{{page.page_title}}', global_page_title)
459 # Parse out the master document's structure into a dictionary list
460 fileStruct = GetFileStructure()
462 # Build a quasi-tree structure listing children at level + 1 for each node
463 nodeChildren = FindChildren(fileStruct)
465 # Create a dictionary for translation of internal links to real links
466 links = FindInternalLinks(fileStruct)
467 oplinks = FindInternalAnchors(fileStruct)
470 print('Found ' + str(len(links)) + ' internal link target', end='')
471 print('.') if len(links) == 1 else print('s.')
474 master = open(global_master_doc)
475 firstLine = master.readline().rstrip('\r\n')
478 if firstLine == '<!-- exploded -->':
479 print('Parsing exploded file...')
480 elif firstLine == '<!-- imploded -->':
481 print('Parsing imploded file...')
483 print('Parsing unknown type...')
487 for header in fileStruct:
488 fileCount = fileCount + 1
493 level = header['level']
495 # Handle Part/Chapter/subchapter numbering
498 levelNums[level] = levelNums[level] + 1;
500 # This is totally unnecessary, but nice; besides which, you can capture
501 # the output to a file to look at later if you like :-)
503 for i in range(level):
507 print('\nPart ' + num2roman(levelNums[0]) + ': ', end='')
509 print('\n\tChapter ' + str(levelNums[1]) + ': ', end='')
511 print(header['title'])
513 # Handle TOC scriblings and one-page titles...
516 opl = ' id="' + header['link'] + '"'
518 opl = ' id="' + header['filename'] + '"'
521 toc = toc + '<h2>Part ' + num2roman(levelNums[level]) + ': ' + header['title'] + '</h2>\n';
522 oph = '<h1 class="clear"' + opl +'>Part ' + num2roman(levelNums[level]) + ' - ' + header['title'] + '</h1>\n';
524 toc = toc + '\t<p class="chapter">Ch. ' + str(levelNums[level]) + ': <a href="/' + header['filename'] + '/">' + header['title'] + '</a></p>\n'
525 oph = '<h2 class="clear"' + opl +'>' + str(levelNums[level]) + ' - ' + header['title'] + '</h3>\n';
527 toc = toc + '\t\t<p class="subchapter"><a href="/' + header['filename'] + '/">' + header['title'] + '</a></p>\n'
528 oph = '<h3 class="clear"' + opl +'>' + str(levelNums[level-1]) + '.' + str(levelNums[level]) + ' - ' + header['title'] + '</h3>\n';
530 # Make the 'this thing contains...' stuff
531 if HaveChildren(fileStruct, pageNumber):
532 pages = GetChildren(fileStruct, pageNumber)
535 more = more + '<li>' + '<a href="/' + fileStruct[pg]['filename'] + '/">' + fileStruct[pg]['title'] + '</a>' + '</li>\n'
537 more = '<div id=subtopics>\n' + '<h2>This section contains the following topics:</h2>\n' + '<ul>\n' + more + '</ul>\n' + '</div>\n'
539 parent = GetParent(fileStruct, pageNumber)
541 # Make the 'Previous', 'Up' & 'Next' content
547 pLink = '<li class="previous"><a title="' + fileStruct[pageNumber - 1]['title'] + '" href="/' + fileStruct[pageNumber - 1]['filename'] + '/" class="previous"> ← Previous </a></li>'
549 if pageNumber < len(fileStruct) - 1:
550 nLink = '<li class="next"><a title="' + fileStruct[pageNumber + 1]['title'] + '" href="/' + fileStruct[pageNumber + 1]['filename'] + '/" class="next"> Next → </a></li>'
553 uLink = '<li><a title="' + fileStruct[parent]['title'] + '" href="/' + fileStruct[parent]['filename'] + '/" class="active"> ↑ Up </a></li>'
555 uLink = '<li><a title="Ardour Table of Contents" href="/toc/index.html" class="active"> ↑ Up </a></li>'
557 prevnext = '<ul class="pager">' + pLink + uLink + nLink + '</ul>'
559 # Make the BreadCrumbs
560 breadcrumbs = GetBreadCrumbs(fileStruct, pageNumber)
562 # Create the link sidebar
563 sidebar = CreateLinkSidebar(fileStruct, pageNumber, nodeChildren)
565 # Parts DO NOT have any content, they are ONLY an organizing construct!
566 # Chapters, subchapters, sections & subsections can all have content,
567 # but the basic fundamental organizing unit WRT content is still the
571 if 'include' in header:
572 srcFile = open('include/' + header['include'])
573 githubedit = '<span style="float:right;"><a title="Edit in GitHub" href="' + global_githuburl + header['include'] + '"><img src="/images/github.png" alt="Edit in GitHub"/></a></span>'
574 content = srcFile.read()
577 # Get rid of any extant header in the include file
578 # (once this is accepted, we can nuke this bit, as content files
579 # will not have any headers or footers in them)
580 content = re.sub('---.*\n(.*\n)*---.*\n', '', content)
581 content = content.replace('{% children %}', '')
584 if 'content' in header:
585 content = header['content']
587 content = '[something went wrong]'
589 # Add header information to the page if in dev mode
591 devnote ='<aside style="background-color:indigo; color:white;">'
592 if 'filename' in header:
593 devnote = devnote + 'filename: ' + header['filename'] + '<br>'
594 if 'include' in header:
595 devnote = devnote + 'include: ' + header['include'] + '<br>'
597 devnote = devnote + 'link: ' + header['link'] + '<br>'
598 content = devnote + '</aside>' + content
600 # ----- One page and PDF version -----
602 # Fix up any internal links
603 opcontent = FixInternalLinks(oplinks, content, header['title'])
604 opcontent = reheader(opcontent, 2)
606 # Set up the actual page from the template
607 onepage = onepage.replace('{{ content }}', oph + '\n' + opcontent + '\n{{ content }}')
608 pdfpage = pdfpage.replace('{{ content }}', oph + '\n' + opcontent + '\n{{ content }}')
610 # ----- Normal version -----
612 # Fix up any internal links
613 content = FixInternalLinks(links, content, header['title'])
615 # Set up the actual page from the template
616 if 'style' not in header:
617 page = re.sub("{% if page.style %}.*\n.*\n{% endif %}.*\n", "", template)
619 page = template.replace('{{page.style}}', header['style'])
620 page = page.replace('{% if page.style %}', '')
621 page = page.replace('{% endif %}', '')
623 page = page.replace('{{ page.title }}', header['title'])
624 page = page.replace('{% tree %}', sidebar)
625 page = page.replace('{% prevnext %}', prevnext)
626 page = page.replace('{% githubedit %}', githubedit)
627 page = page.replace('{% breadcrumbs %}', breadcrumbs)
628 page = page.replace('{{ content }}', content + more)
630 # Create the directory for the index.html file to go into (we use makedirs,
631 # because we have to in order to accomodate the 'uri' keyword)
632 os.makedirs(global_site_dir + header['filename'], 0o775, exist_ok=True)
634 # Finally, write the file!
635 destFile = open(global_site_dir + header['filename'] + '/index.html', 'w')
639 # Save filename for next header...
640 lastFile = header['filename']
641 pageNumber = pageNumber + 1
643 # Finally, create the TOC
644 sidebar = CreateLinkSidebar(fileStruct, -1, nodeChildren)
646 page = re.sub("{% if page.style %}.*\n.*\n{% endif %}.*\n", "", template)
647 page = page.replace('{{ page.title }}', 'Ardour Table of Contents')
648 page = page.replace('{% tree %}', sidebar)
649 page = page.replace('{{ content }}', toc)
650 page = page.replace('{% prevnext %}', '')
651 page = page.replace('{% githubedit %}', '')
652 page = page.replace('{% breadcrumbs %}', '')
654 os.mkdir(global_site_dir + 'toc', 0o775)
655 tocFile = open(global_site_dir + 'toc/index.html', 'w')
659 # Create the one-page version of the documentation
660 onepageFile = open(global_site_dir + 'ardourmanual.html', 'w')
661 opsidebar = BuildOnePageSidebar(fileStruct) # create the link sidebar
662 onepage = onepage.replace('{% tree %}', opsidebar)
663 onepage = onepage.replace('{{ content }}', '') # cleans up the last spaceholder
664 onepageFile.write(onepage)
668 print('Generating the PDF...')
669 # Create the PDF version of the documentation
670 pdfpageFile = open(global_site_dir + 'pdf.html', 'w')
671 pdfpage = pdfpage.replace('{% tree %}', opsidebar) # create the TOC
672 pdfpage = pdfpage.replace('{{ content }}', '') # cleans up the last spaceholder
673 pdfpageFile.write(pdfpage)
676 from weasyprint import HTML
677 doc = HTML(filename = global_site_dir + 'pdf.html') #, base_url = os.path.dirname(os.path.realpath(__file__)))
678 doc.write_pdf(global_site_dir + 'manual.pdf')
681 print('Processed ' + str(fileCount) + ' files.')