3 # Script to take the master document and ancillary files and create the
4 # finished manual/website.
7 # (C) 2017 Underground Software
9 # Contributors: Ed Ward
12 # Remnants (could go into the master document as the first header)
21 global_bootstrap_path = '/bootstrap-3.3.7'
22 global_page_title = 'The Ardour Manual'
23 global_site_dir = './website/'
24 global_githuburl = 'https://github.com/Ardour/manual/edit/master/include/'
25 global_screen_template = 'page-template.html'
26 global_onepage_template = 'onepage-template.html'
27 global_pdf_template = 'pdf-template.html'
28 global_master_doc = 'master-doc.txt'
29 from datetime import datetime
30 global_today_iso = datetime.today().strftime('%Y-%m-%dT%H%M%S')
31 global_today = datetime.today().strftime('%Y-%m-%d')
33 # This matches all *non* letter/number, ' ', '.', '-', and '_' chars
34 cleanString = re.compile(r'[^a-zA-Z0-9 \._-]+')
35 # This matches new 'unbreakable' links, up to the closing quote or anchor
36 findLinks = re.compile(r'"@@[^#"]*[#"]')
39 # Create an all lowercase filename without special characters and with spaces
40 # replaced with dashes.
44 # Clean up the file name, removing all non letter/number or " .-_" chars.
45 # Also, convert to lower case and replace all spaces with dashes.
46 fn = cleanString.sub('', s).lower().replace(' ', '-')
47 # Double dashes can creep in from the above replacement, so we check for
49 fn = fn.replace('--', '-')
55 # Parse headers into a dictionary
57 def ParseHeader(fileObj):
61 hdrLine = fileObj.readline().rstrip('\r\n')
63 # Break out of the loop if we hit the end of header marker
64 if hdrLine.startswith('---'):
67 # Check to see that we have a well-formed header construct
68 match = re.findall(': ', hdrLine)
71 # Parse out foo: bar pairs & put into header dictionary
72 a = re.split(': ', hdrLine, 1)
79 # Turn a "part" name into an int
83 lvl = {'part': 0, 'chapter': 1, 'subchapter': 2}
91 # Converts a integer to a Roman numeral
94 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')]
106 # Capture the master document's structure (and content, if any) in a list
108 def GetFileStructure():
113 mf = open(global_master_doc)
116 if ln.startswith('---'):
117 # First, stuff any content that we may have read into the current
118 # header's dictionary
120 fs[-1]['content'] = content
124 # Then, get the new header and do things to it
125 hdr = ParseHeader(mf)
126 level = PartToLevel(hdr['part'])
128 fnames[level] = MakeFilename(hdr['title'])
130 # Ickyness--user specified URIs
132 hdr['filename'] = hdr['uri']
136 for i in range(level + 1):
137 fullName = fullName + fnames[i] + '/'
139 # Strip trailing '/' on filename
140 hdr['filename'] = fullName[:-1]
144 if ('include' not in hdr) and (level > 0):
148 content = content + ln
150 # Catch the last file, since it would be missed above
152 fs[-1]['content'] = content
159 # Determine if a particular node has child nodes
161 def HaveChildren(fs, pos):
162 # If we're at the end of the list, there can be no children
163 if pos == len(fs) - 1:
166 # If the next node is at a lower level than the current node, we have
168 if fs[pos]['level'] < fs[pos + 1]['level']:
171 # Otherwise, no children at this node.
176 # Get the children at this level, and return them in a list
178 def GetChildren(fs, pos):
181 childLevel = fs[pos]['level']
183 while fs[pos]['level'] >= childLevel:
184 if fs[pos]['level'] == childLevel:
197 # Get the parent at this level
199 def GetParent(fs, pos):
200 thisLevel = fs[pos]['level']
203 while pos >= 0 and fs[pos]['level'] >= thisLevel:
210 #Â Change the hierarchy of titles : h1->hn, h2->hn+1, etc... n being delta-1
212 def reheader(txt, delta):
213 for i in range(6, 0, -1):
214 txt = txt.replace('<h' + str(i),'<h' + str(i+delta))
215 txt = txt.replace('</h' + str(i),'</h' + str(i+delta))
220 # Creates the BreadCrumbs
222 def GetBreadCrumbs(fs, pos):
223 breadcrumbs = '<li class="active">'+ fs[pos]['title'] + '</li>'
226 pos = GetParent(fs, pos)
229 breadcrumbs='<li><a href="/' + fs[pos]['filename'] + '/">'+ fs[pos]['title'] + '</a></li>'+ breadcrumbs
231 breadcrumbs = '<ul class="breadcrumb"><li><a href="/toc/index.html">Home</a></li>' + breadcrumbs + '</ul>'
236 # Make an array of children attached to each node in the file structure
237 # (It's a quasi-tree structure, and can be traversed as such.)
239 def FindChildren(fs):
242 for i in range(len(fs)):
243 if HaveChildren(fs, i):
244 childArray.append(GetChildren(fs, i))
246 childArray.append([])
252 # Make an array of the top level nodes in the file structure
254 def FindTopLevelNodes(fs):
257 for i in range(len(fs)):
258 if fs[i]['level'] == 0:
265 # Find all header links and create a dictionary out of them
267 def FindInternalLinks(fs):
272 linkDict['"@@' + hdr['link'] + '"'] = '"/' + hdr['filename'] + '/"'
273 linkDict['"@@' + hdr['link'] + '#'] = '"/' + hdr['filename'] + '/index.html#'
278 # Same as above, but create anchors (for the one-page version)
280 def FindInternalAnchors(fs):
285 linkDict['"@@' + hdr['link'] + '"'] = '"#' + hdr['link'] + '"'
286 linkDict['"@@' + hdr['link'] + '#'] = '"#' + hdr['link'] + '"'
292 # Internal links are of the form '@@link-name', which are references to the
293 # 'link:' field in the part header. We have to find all occurrences and replace
294 # them with the appropriate link.
296 def FixInternalLinks(links, content, title):
298 match = findLinks.findall(content)
304 content = content.replace(s, links[s])
308 # Report missing link targets to the user (if any)
310 print('\nMissing link target' + ('s' if len(missing) > 1 else '') + ' in "' + title + '":')
321 # Recursively build a list of links based on the location of the page we're
322 # looking at currently
324 def BuildList(lst, fs, pagePos, cList):
327 for i in range(len(lst)):
329 nextPos = lst[i + 1] if i + 1 < len(lst) else len(fs)
331 active = ' class=active' if curPos == pagePos else ''
332 menuTitle = fs[curPos]['menu_title'] if 'menu_title' in fs[curPos] else fs[curPos]['title']
333 content = content + '\t<li' + active + '><a href="/' + fs[curPos]['filename'] + '/">' + menuTitle + '</a></li>\n'
335 # If the current page is our page, and it has children, enumerate them
336 if curPos == pagePos:
337 if len(cList[curPos]) > 0:
338 content = content + BuildList(cList[curPos], fs, -1, cList)
340 # Otherwise, if our page lies between the current one and the next,
341 # build a list of links from those nodes one level down.
342 elif (pagePos > curPos) and (pagePos < nextPos):
343 content = content + BuildList(cList[curPos], fs, pagePos, cList)
345 content = content + '</ul>\n'
351 # Builds the sidebar for the one-page version
353 def BuildOnePageSidebar(fs):
355 content = '\n\n<ul class="toc" style="white-space:nowrap;">\n'
359 for i in range(len(fs)):
360 # Handle Part/Chapter/subchapter numbering
361 level = fs[i]['level']
364 levelNums[level] = levelNums[level] + 1;
367 while j > 0: #level 0 is the part number which is not shown
368 txtlevel = str(levelNums[j]) + '.' + txtlevel
370 if len(txtlevel) > 0:
371 txtlevel = txtlevel[:-1] + ' - '
374 anchor = fs[i]['link']
376 anchor = fs[i]['filename']
379 content = content + '<ul style="white-space:nowrap;">\n'
382 content = content + '</ul>\n'
385 content = content + '<li><a href="#' + anchor + '">' + txtlevel + fs[i]['title'] + '</a></li>\n'
387 content = content + '</ul>\n'
393 # Create link sidebar given a position in the list.
395 def CreateLinkSidebar(fs, pos, childList):
397 # Build the list recursively from the top level nodes
398 content = BuildList(FindTopLevelNodes(fs), fs, pos, childList)
399 # Shove the TOC link and one file link at the top...
400 active = ' class=active' if pos<0 else ''
401 content = content.replace('<ul>','<ul><li' + active + '><a href="/toc/">Table of Contents</a></li>',1)
407 # We have command line arguments now, so deal with them
408 parser = argparse.ArgumentParser(description='A build script for the Ardour Manual')
409 parser.add_argument('-v', '--verbose', action='store_true', help='Display the high-level structure of the manual')
410 parser.add_argument('-q', '--quiet', action='store_true', help='Suppress all output (overrides -v)')
411 parser.add_argument('-d', '--devmode', action='store_true', help='Add content to pages to help developers debug them')
412 parser.add_argument('-n', '--nopdf', action='store_true', help='Do not automatically generate PDF from content')
413 args = parser.parse_args()
414 verbose = args.verbose
416 devmode = args.devmode
434 if not quiet and devmode:
435 print('Devmode active: scribbling extra junk to the manual...')
437 if os.access(global_site_dir, os.F_OK):
439 print('Removing stale HTML data...')
441 shutil.rmtree(global_site_dir)
443 shutil.copytree('./source', global_site_dir)
446 # Read the template, and fix the stuff that's fixed for all pages
447 temp = open(global_screen_template)
448 template = temp.read()
450 template = template.replace('{{page.bootstrap_path}}', global_bootstrap_path)
451 template = template.replace('{{page.page_title}}', global_page_title)
453 # Same as above, but for the One-page version
454 temp = open(global_onepage_template)
455 onepage = temp.read()
457 onepage = onepage.replace('{{page.bootstrap_path}}', global_bootstrap_path)
458 onepage = onepage.replace('{{page.page_title}}', global_page_title)
461 # Same as above, but for the PDF version
462 temp = open(global_pdf_template)
463 pdfpage = temp.read()
465 pdfpage = pdfpage.replace('{{page.page_title}}', global_page_title)
467 # Parse out the master document's structure into a dictionary list
468 fileStruct = GetFileStructure()
470 # Build a quasi-tree structure listing children at level + 1 for each node
471 nodeChildren = FindChildren(fileStruct)
473 # Create a dictionary for translation of internal links to real links
474 links = FindInternalLinks(fileStruct)
475 oplinks = FindInternalAnchors(fileStruct)
478 print('Found ' + str(len(links)) + ' internal link target', end='')
479 print('.') if len(links) == 1 else print('s.')
482 master = open(global_master_doc)
483 firstLine = master.readline().rstrip('\r\n')
486 if firstLine == '<!-- exploded -->':
487 print('Parsing exploded file...')
488 elif firstLine == '<!-- imploded -->':
489 print('Parsing imploded file...')
491 print('Parsing unknown type...')
495 for header in fileStruct:
496 fileCount = fileCount + 1
501 level = header['level']
503 # Handle Part/Chapter/subchapter numbering
506 levelNums[level] = levelNums[level] + 1;
508 # This is totally unnecessary, but nice; besides which, you can capture
509 # the output to a file to look at later if you like :-)
511 for i in range(level):
515 print('\nPart ' + num2roman(levelNums[0]) + ': ', end='')
517 print('\n\tChapter ' + str(levelNums[1]) + ': ', end='')
519 print(header['title'])
521 # Handle TOC scriblings...
523 toc = toc + '<h2>Part ' + num2roman(levelNums[level]) + ': ' + header['title'] + '</h2>\n';
525 toc = toc + '\t<p class="chapter">Ch. ' + str(levelNums[level]) + ': <a href="/' + header['filename'] + '/">' + header['title'] + '</a></p>\n'
527 toc = toc + '\t\t<p class="subchapter"><a href="/' + header['filename'] + '/">' + header['title'] + '</a></p>\n'
529 # Handle one-page and PDF titles...
532 opl = ' id="' + header['link'] + '"'
534 opl = ' id="' + header['filename'] + '"'
535 oph = '<h' + str(level+1) + ' class="clear"' + opl +'>' + header['title'] + '</h' + str(level+1) + '>\n';
538 # Make the 'this thing contains...' stuff
539 if HaveChildren(fileStruct, pageNumber):
540 pages = GetChildren(fileStruct, pageNumber)
543 more = more + '<li>' + '<a href="/' + fileStruct[pg]['filename'] + '/">' + fileStruct[pg]['title'] + '</a>' + '</li>\n'
545 more = '<div id=subtopics>\n' + '<h2>This section contains the following topics:</h2>\n' + '<ul>\n' + more + '</ul>\n' + '</div>\n'
547 parent = GetParent(fileStruct, pageNumber)
549 # Make the 'Previous', 'Up' & 'Next' content
555 pLink = '<li class="previous"><a title="' + fileStruct[pageNumber - 1]['title'] + '" href="/' + fileStruct[pageNumber - 1]['filename'] + '/" class="previous"> ← Previous </a></li>'
557 if pageNumber < len(fileStruct) - 1:
558 nLink = '<li class="next"><a title="' + fileStruct[pageNumber + 1]['title'] + '" href="/' + fileStruct[pageNumber + 1]['filename'] + '/" class="next"> Next → </a></li>'
561 uLink = '<li><a title="' + fileStruct[parent]['title'] + '" href="/' + fileStruct[parent]['filename'] + '/" class="active"> ↑ Up </a></li>'
563 uLink = '<li><a title="Ardour Table of Contents" href="/toc/index.html" class="active"> ↑ Up </a></li>'
565 prevnext = '<ul class="pager">' + pLink + uLink + nLink + '</ul>'
567 # Make the BreadCrumbs
568 breadcrumbs = GetBreadCrumbs(fileStruct, pageNumber)
570 # Create the link sidebar
571 sidebar = CreateLinkSidebar(fileStruct, pageNumber, nodeChildren)
573 # Parts DO NOT have any content, they are ONLY an organizing construct!
574 # Chapters, subchapters, sections & subsections can all have content,
575 # but the basic fundamental organizing unit WRT content is still the
580 if 'include' in header:
581 srcFile = open('include/' + header['include'])
582 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>'
583 content = srcFile.read()
586 # Get rid of any extant header in the include file
587 # (once this is accepted, we can nuke this bit, as content files
588 # will not have any headers or footers in them)
589 content = re.sub('---.*\n(.*\n)*---.*\n', '', content)
590 content = content.replace('{% children %}', '')
593 if 'content' in header:
594 content = header['content']
596 content = '[something went wrong]'
598 # Add header information to the page if in dev mode
600 devnote ='<aside style="background-color:indigo; color:white;">'
602 if 'filename' in header:
603 devnote = devnote + 'filename: ' + header['filename'] + '<br>'
605 if 'include' in header:
606 devnote = devnote + 'include: ' + header['include'] + '<br>'
609 devnote = devnote + 'link: ' + header['link'] + '<br>'
611 content = devnote + '</aside>' + content
613 # ----- One page and PDF version -----
615 # Fix up any internal links
616 opcontent = FixInternalLinks(oplinks, content, header['title'])
617 opcontent = reheader(opcontent, 2)
619 # Set up the actual page from the template
620 onepage = onepage.replace('{{ content }}', oph + '\n' + opcontent + '\n{{ content }}')
622 pdfpage = pdfpage.replace('{{ content }}', oph + '\n' + opcontent + '\n{{ content }}')
624 # ----- Normal version -----
626 # Fix up any internal links
627 content = FixInternalLinks(links, content, header['title'])
629 # Set up the actual page from the template
630 if 'style' not in header:
631 page = re.sub("{% if page.style %}.*\n.*\n{% endif %}.*\n", "", template)
633 page = template.replace('{{page.style}}', header['style'])
634 page = page.replace('{% if page.style %}', '')
635 page = page.replace('{% endif %}', '')
637 page = page.replace('{{ page.title }}', header['title'])
638 page = page.replace('{% tree %}', sidebar)
639 page = page.replace('{% prevnext %}', prevnext)
640 page = page.replace('{% githubedit %}', githubedit)
641 page = page.replace('{% breadcrumbs %}', breadcrumbs)
642 page = page.replace('{{ content }}', content + more)
644 # Create the directory for the index.html file to go into (we use makedirs,
645 # because we have to in order to accomodate the 'uri' keyword)
646 os.makedirs(global_site_dir + header['filename'], 0o775, exist_ok=True)
648 # Finally, write the file!
649 destFile = open(global_site_dir + header['filename'] + '/index.html', 'w')
653 # Save filename for next header...
654 lastFile = header['filename']
655 pageNumber = pageNumber + 1
657 # Finally, create the TOC
658 sidebar = CreateLinkSidebar(fileStruct, -1, nodeChildren)
660 page = re.sub("{% if page.style %}.*\n.*\n{% endif %}.*\n", "", template)
661 page = page.replace('{{ page.title }}', 'Ardour Table of Contents')
662 page = page.replace('{% tree %}', sidebar)
663 page = page.replace('{{ content }}', toc)
664 page = page.replace('{% prevnext %}', '')
665 page = page.replace('{% githubedit %}', '')
666 page = page.replace('{% breadcrumbs %}', '')
668 os.mkdir(global_site_dir + 'toc', 0o775)
669 tocFile = open(global_site_dir + 'toc/index.html', 'w')
673 # Create the one-page version of the documentation
674 onepageFile = open(global_site_dir + 'ardourmanual.html', 'w')
675 opsidebar = BuildOnePageSidebar(fileStruct) # create the link sidebar
676 onepage = onepage.replace('{% tree %}', opsidebar)
677 onepage = onepage.replace('{{ content }}', '') # cleans up the last spaceholder
678 onepageFile.write(onepage)
683 print('Generating the PDF...')
685 # Create the PDF version of the documentation
686 pdfpage = pdfpage.replace('{% tree %}', opsidebar) # create the TOC
687 pdfpage = pdfpage.replace('{{ content }}', '') # cleans up the last spaceholder
688 pdfpage = pdfpage.replace('{{ today }}', global_today)
689 pdfpage = pdfpage.replace('{{ today_iso }}', global_today_iso)
690 pdfpage = pdfpage.replace('src="/images/', 'src="images/') # makes images links relative
691 pdfpage = pdfpage.replace('url(\'/images/', 'url(\'images/') # CSS images links relative
692 # Write it to disk (optional, can be removed)
693 pdfpageFile = open(global_site_dir + 'pdf.html', 'w')
694 pdfpageFile.write(pdfpage)
697 # Generating the actual PDF with weasyprint (https://weasyprint.org/)
698 from weasyprint import HTML
699 from weasyprint.fonts import FontConfiguration
700 html_font_config = FontConfiguration()
701 doc = HTML(string = pdfpage, base_url = global_site_dir)
702 doc.write_pdf(global_site_dir + 'manual.pdf', font_config = html_font_config)
705 print('Processed ' + str(fileCount) + ' files.')