3 # Script to take the master document and ancillary files and create the
4 # finished manual/website.
7 # (C) 2020 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_manual_url = 'http://manual.ardour.org'
25 global_githuburl = 'https://github.com/Ardour/manual/edit/master/include/'
26 global_screen_template = 'page-template.html'
27 global_onepage_template = 'onepage-template.html'
28 global_pdf_template = 'pdf-template.html'
29 global_master_doc = 'master-doc.txt'
30 global_pdflink = '<button class="btn btn-default" type="button" onclick="window.location.href=\'/manual.pdf\'"><span class="glyphicon glyphicon-book" aria-hidden="true"></span></button>'
31 from datetime import datetime
32 global_today_iso = datetime.today().strftime('%Y-%m-%dT%H%M%S')
33 global_today = datetime.today().strftime('%Y-%m-%d')
35 # This matches all *non* letter/number, ' ', '.', '-', and '_' chars
36 cleanString = re.compile(r'[^a-zA-Z0-9 \._-]+')
37 # This matches new 'unbreakable' links, up to the closing quote or anchor
38 findLinks = re.compile(r'"@@[^#"]*[#"]')
41 # Create an all lowercase filename without special characters and with spaces
42 # replaced with dashes.
46 # Clean up the file name, removing all non letter/number or " .-_" chars.
47 # Also, convert to lower case and replace all spaces with dashes.
48 fn = cleanString.sub('', s).lower().replace(' ', '-')
49 # Double dashes can creep in from the above replacement, so we check for
51 fn = fn.replace('--', '-')
57 # Parse headers into a dictionary
59 def ParseHeader(fileObj):
63 hdrLine = fileObj.readline().rstrip('\r\n')
65 # Break out of the loop if we hit the end of header marker
66 if hdrLine.startswith('---'):
69 # Check to see that we have a well-formed header construct
70 match = re.findall(': ', hdrLine)
73 # Parse out foo: bar pairs & put into header dictionary
74 a = re.split(': ', hdrLine, 1)
81 # Turn a "part" name into an int
84 lvl = {'part': 0, 'chapter': 1, 'subchapter': 2, 'section': 3, 'subsection': 4 }
93 # Converts a integer to a Roman numeral
96 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')]
108 # Capture the master document's structure (and content, if any) in a list
110 def GetFileStructure():
115 mf = open(global_master_doc)
118 if ln.startswith('---'):
119 # First, stuff any content that we may have read into the current
120 # header's dictionary
122 fs[-1]['content'] = content
126 # Then, get the new header and do things to it
127 hdr = ParseHeader(mf)
128 level = PartToLevel(hdr['part'])
130 fnames[level] = MakeFilename(hdr['title'])
132 # Ickyness--user specified URIs
134 hdr['filename'] = hdr['uri']
138 for i in range(level + 1):
139 fullName = fullName + fnames[i] + '/'
141 # Strip trailing '/' on filename
142 hdr['filename'] = fullName[:-1]
146 if ('include' not in hdr) and (level > 0):
150 content = content + ln
152 # Catch the last file, since it would be missed above
154 fs[-1]['content'] = content
161 # Determine if a particular node has child nodes
163 def HaveChildren(fs, pos):
164 # If we're at the end of the list, there can be no children
165 if pos == len(fs) - 1:
168 # If the next node is at a lower level than the current node, we have
170 if fs[pos]['level'] < fs[pos + 1]['level']:
173 # Otherwise, no children at this node.
178 # Get the children at this level, and return them in a list
180 def GetChildren(fs, pos):
183 childLevel = fs[pos]['level']
185 while fs[pos]['level'] >= childLevel:
186 if fs[pos]['level'] == childLevel:
199 # Get the parent at this level
201 def GetParent(fs, pos):
202 thisLevel = fs[pos]['level']
205 while pos >= 0 and fs[pos]['level'] >= thisLevel:
212 # Change the hierarchy of titles : h1->hn, h2->hn+1, etc... n being delta-1
214 def reheader(txt, delta):
215 for i in range(6, 0, -1):
216 txt = txt.replace('<h' + str(i), '<h' + str(i + delta))
217 txt = txt.replace('</h' + str(i), '</h' + str(i + delta))
223 # Creates the BreadCrumbs
225 def GetBreadCrumbs(fs, pos):
226 breadcrumbs = '<li class="active">'+ fs[pos]['title'] + '</li>'
229 pos = GetParent(fs, pos)
232 breadcrumbs='<li><a href="/' + fs[pos]['filename'] + '/">'+ fs[pos]['title'] + '</a></li>'+ breadcrumbs
234 breadcrumbs = '<ul class="breadcrumb"><li><a href="/toc/index.html">Home</a></li>' + breadcrumbs + '</ul>'
239 # Make an array of children attached to each node in the file structure
240 # (It's a quasi-tree structure, and can be traversed as such.)
242 def FindChildren(fs):
245 for i in range(len(fs)):
246 if HaveChildren(fs, i):
247 childArray.append(GetChildren(fs, i))
249 childArray.append([])
255 # Make an array of the top level nodes in the file structure
257 def FindTopLevelNodes(fs):
260 for i in range(len(fs)):
261 if fs[i]['level'] == 0:
268 # Find all header links and create a dictionary out of them
270 def FindInternalLinks(fs):
275 linkDict['"@@' + hdr['link'] + '"'] = '"/' + hdr['filename'] + '/"'
276 linkDict['"@@' + hdr['link'] + '#'] = '"/' + hdr['filename'] + '/index.html#'
282 # Same as above, but create anchors (for the one-page version)
284 def FindInternalAnchors(fs):
289 linkDict['"@@' + hdr['link'] + '"'] = '"#' + hdr['link'] + '"'
290 linkDict['"@@' + hdr['link'] + '#'] = '"#' + hdr['link'] + '"'
296 # Internal links are of the form '@@link-name', which are references to the
297 # 'link:' field in the part header. We have to find all occurrences and replace
298 # them with the appropriate link.
300 def FixInternalLinks(links, content, title):
302 match = findLinks.findall(content)
308 content = content.replace(s, links[s])
312 # Report missing link targets to the user (if any)
314 print('\nMissing link target' + ('s' if len(missing) > 1 else '') + ' in "' + title + '":')
325 # Recursively build a list of links based on the location of the page we're
326 # looking at currently
328 def BuildList(lst, fs, pagePos, cList):
331 for i in range(len(lst)):
333 nextPos = lst[i + 1] if i + 1 < len(lst) else len(fs)
335 active = ' class=active' if curPos == pagePos else ''
336 menuTitle = fs[curPos]['menu_title'] if 'menu_title' in fs[curPos] else fs[curPos]['title']
337 content = content + '\t<li' + active + '><a href="/' + fs[curPos]['filename'] + '/">' + menuTitle + '</a></li>\n'
339 # If the current page is our page, and it has children, enumerate them
340 if curPos == pagePos:
341 if len(cList[curPos]) > 0:
342 content = content + BuildList(cList[curPos], fs, -1, cList)
344 # Otherwise, if our page lies between the current one and the next,
345 # build a list of links from those nodes one level down.
346 elif (pagePos > curPos) and (pagePos < nextPos):
347 content = content + BuildList(cList[curPos], fs, pagePos, cList)
349 content = content + '</ul>\n'
355 # Builds the sidebar for the one-page version
357 def BuildOnePageSidebar(fs):
359 content = '\n\n<ul class="toc">\n'
363 for i in range(len(fs)):
364 # Handle Part/Chapter/subchapter/section/subsection numbering
365 level = fs[i]['level']
370 levelNums[level] = levelNums[level] + 1;
374 while j > 0: #level 0 is the part number which is not shown
375 txtlevel = str(levelNums[j]) + '.' + txtlevel
378 if len(txtlevel) > 0:
379 txtlevel = txtlevel[:-1] + ' - '
382 anchor = fs[i]['link']
384 anchor = fs[i]['filename']
387 content = content + '<ul class="toc">\n'
391 content = content + '</ul>\n'
394 content = content + '<li><a href="#' + anchor + '">' + txtlevel + fs[i]['title'] + '</a></li>\n'
396 content = content + '</ul>\n'
402 # Create link sidebar given a position in the list.
404 def CreateLinkSidebar(fs, pos, childList):
406 # Build the list recursively from the top level nodes
407 content = BuildList(FindTopLevelNodes(fs), fs, pos, childList)
408 # Shove the TOC link and one file link at the top...
409 active = ' class=active' if pos < 0 else ''
410 content = content.replace('<ul>', '<ul><li' + active + '><a href="/toc/">Table of Contents</a></li>\n', 1)
417 # We have command line arguments now, so deal with them
418 parser = argparse.ArgumentParser(description='A build script for the Ardour Manual')
419 parser.add_argument('-v', '--verbose', action='store_true', help='Display the high-level structure of the manual')
420 parser.add_argument('-q', '--quiet', action='store_true', help='Suppress all output (overrides -v)')
421 parser.add_argument('-d', '--devmode', action='store_true', help='Add content to pages to help developers debug them')
422 parser.add_argument('-p', '--pdf', action='store_true', help='Automatically generate PDF from content')
423 args = parser.parse_args()
424 verbose = args.verbose
425 noisy = not args.quiet
426 devmode = args.devmode
429 # --quiet overrides --verbose, so tell it to shut up if user did both
443 if noisy and devmode:
444 print('Devmode active: scribbling extra junk to the manual...')
446 if os.access(global_site_dir, os.F_OK):
448 print('Removing stale HTML data...')
450 shutil.rmtree(global_site_dir)
452 shutil.copytree('./source', global_site_dir)
454 # Read the template, and fix the stuff that's fixed for all pages
455 temp = open(global_screen_template)
456 template = temp.read()
458 template = template.replace('{{page.bootstrap_path}}', global_bootstrap_path)
459 template = template.replace('{{page.page_title}}', global_page_title)
461 template = template.replace('{{page.page_pdflink}}', global_pdflink)
463 template = template.replace('{{page.page_pdflink}}', '')
466 # Same as above, but for the "One-Page" version
467 temp = open(global_onepage_template)
468 onepage = temp.read()
470 onepage = onepage.replace('{{page.bootstrap_path}}', global_bootstrap_path)
471 onepage = onepage.replace('{{page.page_title}}', global_page_title)
474 # Same as above, but for the PDF version
475 temp = open(global_pdf_template)
476 pdfpage = temp.read()
478 pdfpage = pdfpage.replace('{{page.page_title}}', global_page_title)
480 # Parse out the master document's structure into a dictionary list
481 fileStruct = GetFileStructure()
483 # Build a quasi-tree structure listing children at level + 1 for each node
484 nodeChildren = FindChildren(fileStruct)
486 # Create a dictionary for translation of internal links to real links
487 links = FindInternalLinks(fileStruct)
488 oplinks = FindInternalAnchors(fileStruct)
491 print('Found ' + str(len(links)) + ' internal link target', end='')
492 print('.') if len(links) == 1 else print('s.')
495 master = open(global_master_doc)
496 firstLine = master.readline().rstrip('\r\n')
499 if firstLine == '<!-- exploded -->':
500 print('Parsing exploded file...')
501 elif firstLine == '<!-- imploded -->':
502 print('Parsing imploded file...')
504 print('Parsing unknown type...')
508 for header in fileStruct:
509 fileCount = fileCount + 1
514 level = header['level']
516 # Handle Part/Chapter/subchapter/section/subsection numbering
520 levelNums[level] = levelNums[level] + 1;
522 # This is totally unnecessary, but nice; besides which, you can capture
523 # the output to a file to look at later if you like :-)
525 for i in range(level):
529 print('\nPart ' + num2roman(levelNums[0]) + ': ', end='')
531 print('\n\tChapter ' + str(levelNums[1]) + ': ', end='')
533 print(header['title'])
535 # Handle TOC scriblings...
537 toc = toc + '<h2>Part ' + num2roman(levelNums[level]) + ': ' + header['title'] + '</h2>\n';
539 toc = toc + '\t<p class="chapter">Ch. ' + str(levelNums[level]) + ': <a href="/' + header['filename'] + '/">' + header['title'] + '</a></p>\n'
541 toc = toc + '\t\t<p class="subchapter"><a href="/' + header['filename'] + '/">' + header['title'] + '</a></p>\n'
543 toc = toc + '<p class="section"><a href="/' + header['filename'] + '/">' + header['title'] + '</a></p>\n'
545 toc = toc + '<p class="subsection"><a href="/' + header['filename'] + '/">' + header['title'] + '</a></p>\n'
547 # Make the 'this thing contains...' stuff
548 if HaveChildren(fileStruct, pageNumber):
549 pages = GetChildren(fileStruct, pageNumber)
552 more = more + '<li>' + '<a href="/' + fileStruct[pg]['filename'] + '/">' + fileStruct[pg]['title'] + '</a>' + '</li>\n'
554 more = '<div id=subtopics>\n' + '<h2>This section contains the following topics:</h2>\n' + '<ul>\n' + more + '</ul>\n' + '</div>\n'
556 parent = GetParent(fileStruct, pageNumber)
558 # Make the 'Previous', 'Up' & 'Next' content
564 pLink = '<li class="previous"><a title="' + fileStruct[pageNumber - 1]['title'] + '" href="/' + fileStruct[pageNumber - 1]['filename'] + '/" class="previous"> ← Previous </a></li>'
566 if pageNumber < len(fileStruct) - 1:
567 nLink = '<li class="next"><a title="' + fileStruct[pageNumber + 1]['title'] + '" href="/' + fileStruct[pageNumber + 1]['filename'] + '/" class="next"> Next → </a></li>'
570 uLink = '<li><a title="' + fileStruct[parent]['title'] + '" href="/' + fileStruct[parent]['filename'] + '/" class="active"> ↑ Up </a></li>'
572 uLink = '<li><a title="Ardour Table of Contents" href="/toc/index.html" class="active"> ↑ Up </a></li>'
574 prevnext = '<ul class="pager">' + pLink + uLink + nLink + '</ul>'
576 # Make the BreadCrumbs
577 breadcrumbs = GetBreadCrumbs(fileStruct, pageNumber)
579 # Create the link sidebar
580 sidebar = CreateLinkSidebar(fileStruct, pageNumber, nodeChildren)
582 # Parts DO NOT have any content, they are ONLY an organizing construct!
583 # Chapters, subchapters, sections & subsections can all have content,
584 # but the basic fundamental organizing unit WRT content is still the
589 if 'include' in header:
590 srcFile = open('include/' + header['include'])
591 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>'
592 content = srcFile.read()
595 # Get rid of any extant header in the include file
596 # (once this is accepted, we can nuke this bit, as content files
597 # will not have any headers or footers in them)
598 content = re.sub('---.*\n(.*\n)*---.*\n', '', content)
599 content = content.replace('{% children %}', '')
602 if 'content' in header:
603 content = header['content']
605 content = '[something went wrong]'
607 # Add header information to the page if in dev mode
609 devnote ='<aside style="background-color:indigo; color:white;">'
611 if 'filename' in header:
612 devnote = devnote + 'filename: ' + header['filename'] + '<br>'
614 if 'include' in header:
615 devnote = devnote + 'include: ' + header['include'] + '<br>'
618 devnote = devnote + 'link: ' + header['link'] + '<br>'
620 content = devnote + '</aside>' + content
622 # ----- One page and PDF version -----
624 # Fix up any internal links
625 opcontent = FixInternalLinks(oplinks, content, header['title'])
626 opcontent = reheader(opcontent, 2)
628 # Create "one page" header
629 oph = '<h' + str(level+1) + ' class="clear" id="' + header[('link' if 'link' in header else 'filename')] +'">' + header['title'] + '</h' + str(level+1) + '>\n';
631 # Set up the actual page from the template
632 onepage = onepage.replace('{{ content }}', oph + '\n' + opcontent + '\n{{ content }}')
635 if not 'pdf-exclude' in header:
636 pdfpage = pdfpage.replace('{{ content }}', oph + '\n' + opcontent + '\n{{ content }}')
638 pdfpage = pdfpage.replace('{{ content }}', oph + '\n' + 'Please refer to the <a href="' + global_manual_url + '/' + header['filename'] + '/">online manual</a>.\n{{ content }}')
640 # ----- Normal version -----
642 # Fix up any internal links
643 content = FixInternalLinks(links, content, header['title'])
645 # Set up the actual page from the template
646 if 'style' not in header:
647 page = re.sub("{% if page.style %}.*\n.*\n{% endif %}.*\n", "", template)
649 page = template.replace('{{page.style}}', header['style'])
650 page = page.replace('{% if page.style %}', '')
651 page = page.replace('{% endif %}', '')
653 page = page.replace('{{ page.title }}', header['title'])
654 page = page.replace('{% tree %}', sidebar)
655 page = page.replace('{% prevnext %}', prevnext)
656 page = page.replace('{% githubedit %}', githubedit)
657 page = page.replace('{% breadcrumbs %}', breadcrumbs)
658 page = page.replace('{{ content }}', content + more)
660 # Create the directory for the index.html file to go into (we use makedirs,
661 # because we have to in order to accomodate the 'uri' keyword)
662 os.makedirs(global_site_dir + header['filename'], 0o775, exist_ok=True)
664 # Finally, write the file!
665 destFile = open(global_site_dir + header['filename'] + '/index.html', 'w')
669 # Save filename for next header...
670 lastFile = header['filename']
671 pageNumber = pageNumber + 1
673 # Finally, create the TOC
674 sidebar = CreateLinkSidebar(fileStruct, -1, nodeChildren)
676 page = re.sub("{% if page.style %}.*\n.*\n{% endif %}.*\n", "", template)
677 page = page.replace('{{ page.title }}', 'Ardour Table of Contents')
678 page = page.replace('{% tree %}', sidebar)
679 page = page.replace('{{ content }}', toc)
680 page = page.replace('{% prevnext %}', '')
681 page = page.replace('{% githubedit %}', '')
682 page = page.replace('{% breadcrumbs %}', '')
684 os.mkdir(global_site_dir + 'toc', 0o775)
685 tocFile = open(global_site_dir + 'toc/index.html', 'w')
689 # Create the one-page version of the documentation
690 onepageFile = open(global_site_dir + 'ardourmanual.html', 'w')
691 opsidebar = BuildOnePageSidebar(fileStruct) # create the link sidebar
692 onepage = onepage.replace('{% tree %}', opsidebar)
693 onepage = onepage.replace('{{ content }}', '') # cleans up the last spaceholder
694 onepageFile.write(onepage)
699 print('Generating the PDF...')
701 # Create the PDF version of the documentation
702 pdfpage = pdfpage.replace('{% tree %}', opsidebar) # create the TOC
703 pdfpage = pdfpage.replace('{{ content }}', '') # cleans up the last spaceholder
704 pdfpage = pdfpage.replace('{{ today }}', global_today)
705 pdfpage = pdfpage.replace('{{ today_iso }}', global_today_iso)
706 pdfpage = pdfpage.replace('src="/images/', 'src="images/') # makes images links relative
707 pdfpage = pdfpage.replace('url(\'/images/', 'url(\'images/') # CSS images links relative
708 # Write it to disk (optional, can be removed)
709 pdfpageFile = open(global_site_dir + 'pdf.html', 'w')
710 pdfpageFile.write(pdfpage)
713 # Generating the actual PDF with weasyprint (https://weasyprint.org/)
714 from weasyprint import HTML
715 from weasyprint.fonts import FontConfiguration
716 html_font_config = FontConfiguration()
717 doc = HTML(string = pdfpage, base_url = global_site_dir)
718 doc.write_pdf(global_site_dir + 'manual.pdf', font_config = html_font_config)
721 print('Processed ' + str(fileCount) + ' files.')