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 = datetime.today().strftime('%Y-%m-%d')
34 # This matches all *non* letter/number, ' ', '.', '-', and '_' chars
35 cleanString = re.compile(r'[^a-zA-Z0-9 \._-]+')
36 # This matches new 'unbreakable' links, up to the closing quote or anchor
37 findLinks = re.compile(r'"@@[^#"]*[#"]')
40 # Create an all lowercase filename without special characters and with spaces
41 # replaced with dashes.
45 # Clean up the file name, removing all non letter/number or " .-_" chars.
46 # Also, convert to lower case and replace all spaces with dashes.
47 fn = cleanString.sub('', s).lower().replace(' ', '-')
48 # Double dashes can creep in from the above replacement, so we check for
50 fn = fn.replace('--', '-')
56 # Parse headers into a dictionary
58 def ParseHeader(fileObj):
62 hdrLine = fileObj.readline().rstrip('\r\n')
64 # Break out of the loop if we hit the end of header marker
65 if hdrLine.startswith('---'):
68 # Check to see that we have a well-formed header construct
69 match = re.findall(': ', hdrLine)
72 # Parse out foo: bar pairs & put into header dictionary
73 a = re.split(': ', hdrLine, 1)
80 # Turn a "part" name into an int
83 lvl = {'part': 0, 'chapter': 1, 'subchapter': 2, 'section': 3, 'subsection': 4 }
92 # Converts a integer to a Roman numeral
95 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')]
107 # Capture the master document's structure (and content, if any) in a list
109 def GetFileStructure():
114 mf = open(global_master_doc)
117 if ln.startswith('---'):
118 # First, stuff any content that we may have read into the current
119 # header's dictionary
121 fs[-1]['content'] = content
125 # Then, get the new header and do things to it
126 hdr = ParseHeader(mf)
127 level = PartToLevel(hdr['part'])
129 fnames[level] = MakeFilename(hdr['title'])
131 # Ickyness--user specified URIs
133 hdr['filename'] = hdr['uri']
137 for i in range(level + 1):
138 fullName = fullName + fnames[i] + '/'
140 # Strip trailing '/' on filename
141 hdr['filename'] = fullName[:-1]
145 if ('include' not in hdr) and (level > 0):
149 content = content + ln
151 # Catch the last file, since it would be missed above
153 fs[-1]['content'] = content
160 # Determine if a particular node has child nodes
162 def HaveChildren(fs, pos):
163 # If we're at the end of the list, there can be no children
164 if pos == len(fs) - 1:
167 # If the next node is at a lower level than the current node, we have
169 if fs[pos]['level'] < fs[pos + 1]['level']:
172 # Otherwise, no children at this node.
177 # Get the children at this level, and return them in a list
179 def GetChildren(fs, pos):
182 childLevel = fs[pos]['level']
184 while fs[pos]['level'] >= childLevel:
185 if fs[pos]['level'] == childLevel:
198 # Get the parent at this level
200 def GetParent(fs, pos):
201 thisLevel = fs[pos]['level']
204 while pos >= 0 and fs[pos]['level'] >= thisLevel:
211 # Change the hierarchy of titles : h1->hn, h2->hn+1, etc... n being delta-1
213 def reheader(txt, delta):
214 for i in range(6, 0, -1):
215 txt = txt.replace('<h' + str(i), '<h' + str(i + delta))
216 txt = txt.replace('</h' + str(i), '</h' + str(i + delta))
222 # Creates the BreadCrumbs
224 def GetBreadCrumbs(fs, pos):
225 breadcrumbs = '<li class="active">'+ fs[pos]['title'] + '</li>'
228 pos = GetParent(fs, pos)
231 breadcrumbs='<li><a href="/' + fs[pos]['filename'] + '/">'+ fs[pos]['title'] + '</a></li>'+ breadcrumbs
233 breadcrumbs = '<ul class="breadcrumb"><li><a href="/toc/index.html">Home</a></li>' + breadcrumbs + '</ul>'
238 # Make an array of children attached to each node in the file structure
239 # (It's a quasi-tree structure, and can be traversed as such.)
241 def FindChildren(fs):
244 for i in range(len(fs)):
245 if HaveChildren(fs, i):
246 childArray.append(GetChildren(fs, i))
248 childArray.append([])
254 # Make an array of the top level nodes in the file structure
256 def FindTopLevelNodes(fs):
259 for i in range(len(fs)):
260 if fs[i]['level'] == 0:
267 # Find all header links and create a dictionary out of them
269 def FindInternalLinks(fs):
274 linkDict['"@@' + hdr['link'] + '"'] = '"/' + hdr['filename'] + '/"'
275 linkDict['"@@' + hdr['link'] + '#'] = '"/' + hdr['filename'] + '/index.html#'
281 # Same as above, but create anchors (for the one-page version)
283 def FindInternalAnchors(fs):
288 linkDict['"@@' + hdr['link'] + '"'] = '"#' + hdr['link'] + '"'
289 linkDict['"@@' + hdr['link'] + '#'] = '"#' + hdr['link'] + '"'
295 # Internal links are of the form '@@link-name', which are references to the
296 # 'link:' field in the part header. We have to find all occurrences and replace
297 # them with the appropriate link.
299 def FixInternalLinks(links, content, title):
301 match = findLinks.findall(content)
307 content = content.replace(s, links[s])
311 # Report missing link targets to the user (if any)
313 print('\nMissing link target' + ('s' if len(missing) > 1 else '') + ' in "' + title + '":')
324 # Recursively build a list of links based on the location of the page we're
325 # looking at currently
327 def BuildList(lst, fs, pagePos, cList):
330 for i in range(len(lst)):
332 nextPos = lst[i + 1] if i + 1 < len(lst) else len(fs)
334 active = ' class=active' if curPos == pagePos else ''
335 menuTitle = fs[curPos]['menu_title'] if 'menu_title' in fs[curPos] else fs[curPos]['title']
336 content = content + '\t<li' + active + '><a href="/' + fs[curPos]['filename'] + '/">' + menuTitle + '</a></li>\n'
338 # If the current page is our page, and it has children, enumerate them
339 if curPos == pagePos:
340 if len(cList[curPos]) > 0:
341 content = content + BuildList(cList[curPos], fs, -1, cList)
343 # Otherwise, if our page lies between the current one and the next,
344 # build a list of links from those nodes one level down.
345 elif (pagePos > curPos) and (pagePos < nextPos):
346 content = content + BuildList(cList[curPos], fs, pagePos, cList)
348 content = content + '</ul>\n'
354 # Builds the sidebar for the one-page version
356 def BuildOnePageSidebar(fs):
358 content = '\n\n<ul class="toc">\n'
362 for i in range(len(fs)):
363 # Handle Part/Chapter/subchapter/section/subsection numbering
364 level = fs[i]['level']
369 levelNums[level] = levelNums[level] + 1;
373 while j > 0: #level 0 is the part number which is not shown
374 txtlevel = str(levelNums[j]) + '.' + txtlevel
377 if len(txtlevel) > 0:
378 txtlevel = txtlevel[:-1] + ' - '
381 anchor = fs[i]['link']
383 anchor = fs[i]['filename']
386 content = content + '<ul class="toc">\n'
390 content = content + '</ul>\n'
393 content = content + '<li><a href="#' + anchor + '">' + txtlevel + fs[i]['title'] + '</a></li>\n'
395 content = content + '</ul>\n'
401 # Create link sidebar given a position in the list.
403 def CreateLinkSidebar(fs, pos, childList):
405 # Build the list recursively from the top level nodes
406 content = BuildList(FindTopLevelNodes(fs), fs, pos, childList)
407 # Shove the TOC link and one file link at the top...
408 active = ' class=active' if pos < 0 else ''
409 content = content.replace('<ul>', '<ul><li' + active + '><a href="/toc/">Table of Contents</a></li>\n', 1)
416 # We have command line arguments now, so deal with them
417 parser = argparse.ArgumentParser(description='A build script for the Ardour Manual')
418 parser.add_argument('-v', '--verbose', action='store_true', help='Display the high-level structure of the manual')
419 parser.add_argument('-q', '--quiet', action='store_true', help='Suppress all output (overrides -v)')
420 parser.add_argument('-d', '--devmode', action='store_true', help='Add content to pages to help developers debug them')
421 parser.add_argument('-p', '--pdf', action='store_true', help='Automatically generate PDF from content')
422 args = parser.parse_args()
423 verbose = args.verbose
424 noisy = not args.quiet
425 devmode = args.devmode
428 # --quiet overrides --verbose, so tell it to shut up if user did both
442 if noisy and devmode:
443 print('Devmode active: scribbling extra junk to the manual...')
445 if os.access(global_site_dir, os.F_OK):
447 print('Removing stale HTML data...')
449 shutil.rmtree(global_site_dir)
451 shutil.copytree('./source', global_site_dir)
453 # Read the template, and fix the stuff that's fixed for all pages
454 temp = open(global_screen_template)
455 template = temp.read()
457 template = template.replace('{{page.bootstrap_path}}', global_bootstrap_path)
458 template = template.replace('{{page.page_title}}', global_page_title)
460 template = template.replace('{{page.page_pdflink}}', global_pdflink)
462 template = template.replace('{{page.page_pdflink}}', '')
465 # Same as above, but for the "One-Page" version
466 temp = open(global_onepage_template)
467 onepage = temp.read()
469 onepage = onepage.replace('{{page.bootstrap_path}}', global_bootstrap_path)
470 onepage = onepage.replace('{{page.page_title}}', global_page_title)
473 # Same as above, but for the PDF version
474 temp = open(global_pdf_template)
475 pdfpage = temp.read()
477 pdfpage = pdfpage.replace('{{page.page_title}}', global_page_title)
479 # Parse out the master document's structure into a dictionary list
480 fileStruct = GetFileStructure()
482 # Build a quasi-tree structure listing children at level + 1 for each node
483 nodeChildren = FindChildren(fileStruct)
485 # Create a dictionary for translation of internal links to real links
486 links = FindInternalLinks(fileStruct)
487 oplinks = FindInternalAnchors(fileStruct)
490 print('Found ' + str(len(links)) + ' internal link target', end='')
491 print('.') if len(links) == 1 else print('s.')
494 master = open(global_master_doc)
495 firstLine = master.readline().rstrip('\r\n')
498 if firstLine == '<!-- exploded -->':
499 print('Parsing exploded file...')
500 elif firstLine == '<!-- imploded -->':
501 print('Parsing imploded file...')
503 print('Parsing unknown type...')
507 for header in fileStruct:
508 fileCount = fileCount + 1
513 level = header['level']
515 # Handle Part/Chapter/subchapter/section/subsection numbering
519 levelNums[level] = levelNums[level] + 1;
521 # This is totally unnecessary, but nice; besides which, you can capture
522 # the output to a file to look at later if you like :-)
524 for i in range(level):
528 print('\nPart ' + num2roman(levelNums[0]) + ': ', end='')
530 print('\n\tChapter ' + str(levelNums[1]) + ': ', end='')
532 print(header['title'])
534 # Handle TOC scriblings...
536 toc = toc + '<h2>Part ' + num2roman(levelNums[level]) + ': ' + header['title'] + '</h2>\n';
538 toc = toc + '\t<p class="chapter">Ch. ' + str(levelNums[level]) + ': <a href="/' + header['filename'] + '/">' + header['title'] + '</a></p>\n'
540 toc = toc + '\t\t<p class="subchapter"><a href="/' + header['filename'] + '/">' + header['title'] + '</a></p>\n'
542 toc = toc + '<p class="section"><a href="/' + header['filename'] + '/">' + header['title'] + '</a></p>\n'
544 toc = toc + '<p class="subsection"><a href="/' + header['filename'] + '/">' + header['title'] + '</a></p>\n'
546 # Make the 'this thing contains...' stuff
547 if HaveChildren(fileStruct, pageNumber):
548 pages = GetChildren(fileStruct, pageNumber)
551 more = more + '<li>' + '<a href="/' + fileStruct[pg]['filename'] + '/">' + fileStruct[pg]['title'] + '</a>' + '</li>\n'
553 more = '<div id=subtopics>\n' + '<h2>This section contains the following topics:</h2>\n' + '<ul>\n' + more + '</ul>\n' + '</div>\n'
555 parent = GetParent(fileStruct, pageNumber)
557 # Make the 'Previous', 'Up' & 'Next' content
563 pLink = '<li class="previous"><a title="' + fileStruct[pageNumber - 1]['title'] + '" href="/' + fileStruct[pageNumber - 1]['filename'] + '/" class="previous"> ← Previous </a></li>'
565 if pageNumber < len(fileStruct) - 1:
566 nLink = '<li class="next"><a title="' + fileStruct[pageNumber + 1]['title'] + '" href="/' + fileStruct[pageNumber + 1]['filename'] + '/" class="next"> Next → </a></li>'
569 uLink = '<li><a title="' + fileStruct[parent]['title'] + '" href="/' + fileStruct[parent]['filename'] + '/" class="active"> ↑ Up </a></li>'
571 uLink = '<li><a title="Ardour Table of Contents" href="/toc/index.html" class="active"> ↑ Up </a></li>'
573 prevnext = '<ul class="pager">' + pLink + uLink + nLink + '</ul>'
575 # Make the BreadCrumbs
576 breadcrumbs = GetBreadCrumbs(fileStruct, pageNumber)
578 # Create the link sidebar
579 sidebar = CreateLinkSidebar(fileStruct, pageNumber, nodeChildren)
581 # Parts DO NOT have any content, they are ONLY an organizing construct!
582 # Chapters, subchapters, sections & subsections can all have content,
583 # but the basic fundamental organizing unit WRT content is still the
588 if 'include' in header:
589 srcFile = open('include/' + header['include'])
590 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>'
591 content = srcFile.read()
594 # Get rid of any extant header in the include file
595 # (once this is accepted, we can nuke this bit, as content files
596 # will not have any headers or footers in them)
597 content = re.sub('---.*\n(.*\n)*---.*\n', '', content)
598 content = content.replace('{% children %}', '')
601 if 'content' in header:
602 content = header['content']
604 content = '[something went wrong]'
606 # Add header information to the page if in dev mode
608 devnote ='<aside style="background-color:indigo; color:white;">'
610 if 'filename' in header:
611 devnote = devnote + 'filename: ' + header['filename'] + '<br>'
613 if 'include' in header:
614 devnote = devnote + 'include: ' + header['include'] + '<br>'
617 devnote = devnote + 'link: ' + header['link'] + '<br>'
619 content = devnote + '</aside>' + content
621 # ----- One page and PDF version -----
623 # Fix up any internal links
624 opcontent = FixInternalLinks(oplinks, content, header['title'])
625 opcontent = reheader(opcontent, 2)
627 # Create "one page" header
628 oph = '<h' + str(level+1) + ' class="clear" id="' + header[('link' if 'link' in header else 'filename')] +'">' + header['title'] + '</h' + str(level+1) + '>\n';
630 # Set up the actual page from the template
631 onepage = onepage.replace('{{ content }}', oph + '\n' + opcontent + '\n{{ content }}')
634 if not 'pdf-exclude' in header:
635 pdfpage = pdfpage.replace('{{ content }}', oph + '\n' + opcontent + '\n{{ content }}')
637 pdfpage = pdfpage.replace('{{ content }}', oph + '\n' + 'Please refer to the <a href="' + global_manual_url + '/' + header['filename'] + '/">online manual</a>.\n{{ content }}')
639 # ----- Normal version -----
641 # Fix up any internal links
642 content = FixInternalLinks(links, content, header['title'])
644 # Set up the actual page from the template
645 if 'style' not in header:
646 page = re.sub("{% if page.style %}.*\n.*\n{% endif %}.*\n", "", template)
648 page = template.replace('{{page.style}}', header['style'])
649 page = page.replace('{% if page.style %}', '')
650 page = page.replace('{% endif %}', '')
652 page = page.replace('{{ page.title }}', header['title'])
653 page = page.replace('{% tree %}', sidebar)
654 page = page.replace('{% prevnext %}', prevnext)
655 page = page.replace('{% githubedit %}', githubedit)
656 page = page.replace('{% breadcrumbs %}', breadcrumbs)
657 page = page.replace('{{ content }}', content + more)
659 # Create the directory for the index.html file to go into (we use makedirs,
660 # because we have to in order to accomodate the 'uri' keyword)
661 os.makedirs(global_site_dir + header['filename'], 0o775, exist_ok=True)
663 # Finally, write the file!
664 destFile = open(global_site_dir + header['filename'] + '/index.html', 'w')
668 # Save filename for next header...
669 lastFile = header['filename']
670 pageNumber = pageNumber + 1
672 # Finally, create the TOC
673 sidebar = CreateLinkSidebar(fileStruct, -1, nodeChildren)
675 page = re.sub("{% if page.style %}.*\n.*\n{% endif %}.*\n", "", template)
676 page = page.replace('{{ page.title }}', 'Ardour Table of Contents')
677 page = page.replace('{% tree %}', sidebar)
678 page = page.replace('{{ content }}', toc)
679 page = page.replace('{% prevnext %}', '')
680 page = page.replace('{% githubedit %}', '')
681 page = page.replace('{% breadcrumbs %}', '')
683 os.mkdir(global_site_dir + 'toc', 0o775)
684 tocFile = open(global_site_dir + 'toc/index.html', 'w')
688 # Create the one-page version of the documentation
689 onepageFile = open(global_site_dir + 'ardourmanual.html', 'w')
690 opsidebar = BuildOnePageSidebar(fileStruct) # create the link sidebar
691 onepage = onepage.replace('{% tree %}', opsidebar)
692 onepage = onepage.replace('{{ content }}', '') # cleans up the last spaceholder
693 onepageFile.write(onepage)
698 print('Generating the PDF...')
700 logger = logging.getLogger('weasyprint')
701 logger.addHandler(logging.StreamHandler())
703 # Create the PDF version of the documentation
704 pdfpage = pdfpage.replace('{% tree %}', opsidebar) # create the TOC
705 pdfpage = pdfpage.replace('{{ content }}', '') # cleans up the last spaceholder
706 pdfpage = pdfpage.replace('{{ today }}', global_today)
707 pdfpage = pdfpage.replace('src="/images/', 'src="images/') # makes images links relative
708 pdfpage = pdfpage.replace('url(\'/images/', 'url(\'images/') # CSS images links relative
709 # Write it to disk (optional, can be removed)
710 pdfpageFile = open(global_site_dir + 'pdf.html', 'w')
711 pdfpageFile.write(pdfpage)
714 # Generating the actual PDF with weasyprint (https://weasyprint.org/)
715 from weasyprint import HTML
716 from weasyprint.fonts import FontConfiguration
718 html_font_config = FontConfiguration()
719 doc = HTML(string = pdfpage, base_url = global_site_dir)
720 doc.write_pdf(global_site_dir + 'manual.pdf', font_config = html_font_config)
723 print('Processed ' + str(fileCount) + ' files.')