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 from datetime import datetime
31 global_today_iso = datetime.today().strftime('%Y-%m-%dT%H%M%S')
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 # Same as above, but for the "One-Page" version
461 temp = open(global_onepage_template)
462 onepage = temp.read()
464 onepage = onepage.replace('{{page.bootstrap_path}}', global_bootstrap_path)
465 onepage = onepage.replace('{{page.page_title}}', global_page_title)
468 # Same as above, but for the PDF version
469 temp = open(global_pdf_template)
470 pdfpage = temp.read()
472 pdfpage = pdfpage.replace('{{page.page_title}}', global_page_title)
474 # Parse out the master document's structure into a dictionary list
475 fileStruct = GetFileStructure()
477 # Build a quasi-tree structure listing children at level + 1 for each node
478 nodeChildren = FindChildren(fileStruct)
480 # Create a dictionary for translation of internal links to real links
481 links = FindInternalLinks(fileStruct)
482 oplinks = FindInternalAnchors(fileStruct)
485 print('Found ' + str(len(links)) + ' internal link target', end='')
486 print('.') if len(links) == 1 else print('s.')
489 master = open(global_master_doc)
490 firstLine = master.readline().rstrip('\r\n')
493 if firstLine == '<!-- exploded -->':
494 print('Parsing exploded file...')
495 elif firstLine == '<!-- imploded -->':
496 print('Parsing imploded file...')
498 print('Parsing unknown type...')
502 for header in fileStruct:
503 fileCount = fileCount + 1
508 level = header['level']
510 # Handle Part/Chapter/subchapter/section/subsection numbering
514 levelNums[level] = levelNums[level] + 1;
516 # This is totally unnecessary, but nice; besides which, you can capture
517 # the output to a file to look at later if you like :-)
519 for i in range(level):
523 print('\nPart ' + num2roman(levelNums[0]) + ': ', end='')
525 print('\n\tChapter ' + str(levelNums[1]) + ': ', end='')
527 print(header['title'])
529 # Handle TOC scriblings...
531 toc = toc + '<h2>Part ' + num2roman(levelNums[level]) + ': ' + header['title'] + '</h2>\n';
533 toc = toc + '\t<p class="chapter">Ch. ' + str(levelNums[level]) + ': <a href="/' + header['filename'] + '/">' + header['title'] + '</a></p>\n'
535 toc = toc + '\t\t<p class="subchapter"><a href="/' + header['filename'] + '/">' + header['title'] + '</a></p>\n'
537 toc = toc + '<p class="section"><a href="/' + header['filename'] + '/">' + header['title'] + '</a></p>\n'
539 toc = toc + '<p class="subsection"><a href="/' + header['filename'] + '/">' + header['title'] + '</a></p>\n'
541 # Make the 'this thing contains...' stuff
542 if HaveChildren(fileStruct, pageNumber):
543 pages = GetChildren(fileStruct, pageNumber)
546 more = more + '<li>' + '<a href="/' + fileStruct[pg]['filename'] + '/">' + fileStruct[pg]['title'] + '</a>' + '</li>\n'
548 more = '<div id=subtopics>\n' + '<h2>This section contains the following topics:</h2>\n' + '<ul>\n' + more + '</ul>\n' + '</div>\n'
550 parent = GetParent(fileStruct, pageNumber)
552 # Make the 'Previous', 'Up' & 'Next' content
558 pLink = '<li class="previous"><a title="' + fileStruct[pageNumber - 1]['title'] + '" href="/' + fileStruct[pageNumber - 1]['filename'] + '/" class="previous"> ← Previous </a></li>'
560 if pageNumber < len(fileStruct) - 1:
561 nLink = '<li class="next"><a title="' + fileStruct[pageNumber + 1]['title'] + '" href="/' + fileStruct[pageNumber + 1]['filename'] + '/" class="next"> Next → </a></li>'
564 uLink = '<li><a title="' + fileStruct[parent]['title'] + '" href="/' + fileStruct[parent]['filename'] + '/" class="active"> ↑ Up </a></li>'
566 uLink = '<li><a title="Ardour Table of Contents" href="/toc/index.html" class="active"> ↑ Up </a></li>'
568 prevnext = '<ul class="pager">' + pLink + uLink + nLink + '</ul>'
570 # Make the BreadCrumbs
571 breadcrumbs = GetBreadCrumbs(fileStruct, pageNumber)
573 # Create the link sidebar
574 sidebar = CreateLinkSidebar(fileStruct, pageNumber, nodeChildren)
576 # Parts DO NOT have any content, they are ONLY an organizing construct!
577 # Chapters, subchapters, sections & subsections can all have content,
578 # but the basic fundamental organizing unit WRT content is still the
583 if 'include' in header:
584 srcFile = open('include/' + header['include'])
585 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>'
586 content = srcFile.read()
589 # Get rid of any extant header in the include file
590 # (once this is accepted, we can nuke this bit, as content files
591 # will not have any headers or footers in them)
592 content = re.sub('---.*\n(.*\n)*---.*\n', '', content)
593 content = content.replace('{% children %}', '')
596 if 'content' in header:
597 content = header['content']
599 content = '[something went wrong]'
601 # Add header information to the page if in dev mode
603 devnote ='<aside style="background-color:indigo; color:white;">'
605 if 'filename' in header:
606 devnote = devnote + 'filename: ' + header['filename'] + '<br>'
608 if 'include' in header:
609 devnote = devnote + 'include: ' + header['include'] + '<br>'
612 devnote = devnote + 'link: ' + header['link'] + '<br>'
614 content = devnote + '</aside>' + content
616 # ----- One page and PDF version -----
618 # Fix up any internal links
619 opcontent = FixInternalLinks(oplinks, content, header['title'])
620 opcontent = reheader(opcontent, 2)
622 # Create "one page" header
623 oph = '<h' + str(level+1) + ' class="clear" id="' + header[('link' if 'link' in header else 'filename')] +'">' + header['title'] + '</h' + str(level+1) + '>\n';
625 # Set up the actual page from the template
626 onepage = onepage.replace('{{ content }}', oph + '\n' + opcontent + '\n{{ content }}')
629 if not 'pdf-exclude' in header:
630 pdfpage = pdfpage.replace('{{ content }}', oph + '\n' + opcontent + '\n{{ content }}')
632 pdfpage = pdfpage.replace('{{ content }}', oph + '\n' + 'Please refer to the <a href="' + global_manual_url + '/' + header['filename'] + '/">online manual</a>.\n{{ content }}')
634 # ----- Normal version -----
636 # Fix up any internal links
637 content = FixInternalLinks(links, content, header['title'])
639 # Set up the actual page from the template
640 if 'style' not in header:
641 page = re.sub("{% if page.style %}.*\n.*\n{% endif %}.*\n", "", template)
643 page = template.replace('{{page.style}}', header['style'])
644 page = page.replace('{% if page.style %}', '')
645 page = page.replace('{% endif %}', '')
647 page = page.replace('{{ page.title }}', header['title'])
648 page = page.replace('{% tree %}', sidebar)
649 page = page.replace('{% prevnext %}', prevnext)
650 page = page.replace('{% githubedit %}', githubedit)
651 page = page.replace('{% breadcrumbs %}', breadcrumbs)
652 page = page.replace('{{ content }}', content + more)
654 # Create the directory for the index.html file to go into (we use makedirs,
655 # because we have to in order to accomodate the 'uri' keyword)
656 os.makedirs(global_site_dir + header['filename'], 0o775, exist_ok=True)
658 # Finally, write the file!
659 destFile = open(global_site_dir + header['filename'] + '/index.html', 'w')
663 # Save filename for next header...
664 lastFile = header['filename']
665 pageNumber = pageNumber + 1
667 # Finally, create the TOC
668 sidebar = CreateLinkSidebar(fileStruct, -1, nodeChildren)
670 page = re.sub("{% if page.style %}.*\n.*\n{% endif %}.*\n", "", template)
671 page = page.replace('{{ page.title }}', 'Ardour Table of Contents')
672 page = page.replace('{% tree %}', sidebar)
673 page = page.replace('{{ content }}', toc)
674 page = page.replace('{% prevnext %}', '')
675 page = page.replace('{% githubedit %}', '')
676 page = page.replace('{% breadcrumbs %}', '')
678 os.mkdir(global_site_dir + 'toc', 0o775)
679 tocFile = open(global_site_dir + 'toc/index.html', 'w')
683 # Create the one-page version of the documentation
684 onepageFile = open(global_site_dir + 'ardourmanual.html', 'w')
685 opsidebar = BuildOnePageSidebar(fileStruct) # create the link sidebar
686 onepage = onepage.replace('{% tree %}', opsidebar)
687 onepage = onepage.replace('{{ content }}', '') # cleans up the last spaceholder
688 onepageFile.write(onepage)
693 print('Generating the PDF...')
695 # Create the PDF version of the documentation
696 pdfpage = pdfpage.replace('{% tree %}', opsidebar) # create the TOC
697 pdfpage = pdfpage.replace('{{ content }}', '') # cleans up the last spaceholder
698 pdfpage = pdfpage.replace('{{ today }}', global_today)
699 pdfpage = pdfpage.replace('{{ today_iso }}', global_today_iso)
700 pdfpage = pdfpage.replace('src="/images/', 'src="images/') # makes images links relative
701 pdfpage = pdfpage.replace('url(\'/images/', 'url(\'images/') # CSS images links relative
702 # Write it to disk (optional, can be removed)
703 pdfpageFile = open(global_site_dir + 'pdf.html', 'w')
704 pdfpageFile.write(pdfpage)
707 # Generating the actual PDF with weasyprint (https://weasyprint.org/)
708 from weasyprint import HTML
709 from weasyprint.fonts import FontConfiguration
710 html_font_config = FontConfiguration()
711 doc = HTML(string = pdfpage, base_url = global_site_dir)
712 doc.write_pdf(global_site_dir + 'manual.pdf', font_config = html_font_config)
715 print('Processed ' + str(fileCount) + ' files.')