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'
30 # This matches all *non* letter/number, ' ', '.', '-', and '_' chars
31 cleanString = re.compile(r'[^a-zA-Z0-9 \._-]+')
32 # This matches new 'unbreakable' links, up to the closing quote or anchor
33 findLinks = re.compile(r'"@@[^#"]*[#"]')
36 # Create an all lowercase filename without special characters and with spaces
37 # replaced with dashes.
41 # Clean up the file name, removing all non letter/number or " .-_" chars.
42 # Also, convert to lower case and replace all spaces with dashes.
43 fn = cleanString.sub('', s).lower().replace(' ', '-')
44 # Double dashes can creep in from the above replacement, so we check for
46 fn = fn.replace('--', '-')
52 # Parse headers into a dictionary
54 def ParseHeader(fileObj):
58 hdrLine = fileObj.readline().rstrip('\r\n')
60 # Break out of the loop if we hit the end of header marker
61 if hdrLine.startswith('---'):
64 # Check to see that we have a well-formed header construct
65 match = re.findall(': ', hdrLine)
68 # Parse out foo: bar pairs & put into header dictionary
69 a = re.split(': ', hdrLine, 1)
76 # Turn a "part" name into an int
80 lvl = {'part': 0, 'chapter': 1, 'subchapter': 2}
88 # Converts a integer to a Roman numeral
91 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')]
103 # Capture the master document's structure (and content, if any) in a list
105 def GetFileStructure():
110 mf = open(global_master_doc)
113 if ln.startswith('---'):
114 # First, stuff any content that we may have read into the current
115 # header's dictionary
117 fs[-1]['content'] = content
121 # Then, get the new header and do things to it
122 hdr = ParseHeader(mf)
123 level = PartToLevel(hdr['part'])
125 fnames[level] = MakeFilename(hdr['title'])
127 # Ickyness--user specified URIs
129 hdr['filename'] = hdr['uri']
133 for i in range(level + 1):
134 fullName = fullName + fnames[i] + '/'
136 # Strip trailing '/' on filename
137 hdr['filename'] = fullName[:-1]
141 if ('include' not in hdr) and (level > 0):
145 content = content + ln
147 # Catch the last file, since it would be missed above
149 fs[-1]['content'] = content
156 # Determine if a particular node has child nodes
158 def HaveChildren(fs, pos):
159 # If we're at the end of the list, there can be no children
160 if pos == len(fs) - 1:
163 # If the next node is at a lower level than the current node, we have
165 if fs[pos]['level'] < fs[pos + 1]['level']:
168 # Otherwise, no children at this node.
173 # Get the children at this level, and return them in a list
175 def GetChildren(fs, pos):
178 childLevel = fs[pos]['level']
180 while fs[pos]['level'] >= childLevel:
181 if fs[pos]['level'] == childLevel:
194 # Get the parent at this level
196 def GetParent(fs, pos):
197 thisLevel = fs[pos]['level']
200 while pos >= 0 and fs[pos]['level'] >= thisLevel:
207 # Change the hierarchy of titles : h1->hn, h2->hn+1, etc... n being delta-1
209 def reheader(txt, delta):
210 for i in range(6, 0, -1):
211 txt = txt.replace('<h' + str(i),'<h' + str(i+delta))
212 txt = txt.replace('</h' + str(i),'</h' + str(i+delta))
217 # Creates the BreadCrumbs
219 def GetBreadCrumbs(fs, pos):
220 breadcrumbs = '<li class="active">'+ fs[pos]['title'] + '</li>'
223 pos = GetParent(fs, pos)
226 breadcrumbs='<li><a href="/' + fs[pos]['filename'] + '/">'+ fs[pos]['title'] + '</a></li>'+ breadcrumbs
228 breadcrumbs = '<ul class="breadcrumb"><li><a href="/toc/index.html">Home</a></li>' + breadcrumbs + '</ul>'
233 # Make an array of children attached to each node in the file structure
234 # (It's a quasi-tree structure, and can be traversed as such.)
236 def FindChildren(fs):
239 for i in range(len(fs)):
240 if HaveChildren(fs, i):
241 childArray.append(GetChildren(fs, i))
243 childArray.append([])
249 # Make an array of the top level nodes in the file structure
251 def FindTopLevelNodes(fs):
254 for i in range(len(fs)):
255 if fs[i]['level'] == 0:
262 # Find all header links and create a dictionary out of them
264 def FindInternalLinks(fs):
269 linkDict['"@@' + hdr['link'] + '"'] = '"/' + hdr['filename'] + '/"'
270 linkDict['"@@' + hdr['link'] + '#'] = '"/' + hdr['filename'] + '/index.html#'
275 # Same as above, but create anchors (for the one-page version)
277 def FindInternalAnchors(fs):
282 linkDict['"@@' + hdr['link'] + '"'] = '"#' + hdr['link'] + '"'
283 linkDict['"@@' + hdr['link'] + '#'] = '"#' + hdr['link'] + '"'
289 # Internal links are of the form '@@link-name', which are references to the
290 # 'link:' field in the part header. We have to find all occurrences and replace
291 # them with the appropriate link.
293 def FixInternalLinks(links, content, title):
295 match = findLinks.findall(content)
301 content = content.replace(s, links[s])
305 # Report missing link targets to the user (if any)
307 print('\nMissing link target' + ('s' if len(missing) > 1 else '') + ' in "' + title + '":')
318 # Recursively build a list of links based on the location of the page we're
319 # looking at currently
321 def BuildList(lst, fs, pagePos, cList):
322 content = '\n\n<ul>\n'
324 for i in range(len(lst)):
326 nextPos = lst[i + 1] if i + 1 < len(lst) else len(fs)
328 active = ' class=active' if curPos == pagePos else ''
329 menuTitle = fs[curPos]['menu_title'] if 'menu_title' in fs[curPos] else fs[curPos]['title']
330 content = content + '<li' + active + '><a href="/' + fs[curPos]['filename'] + '/">' + menuTitle + '</a></li>'
332 # If the current page is our page, and it has children, enumerate them
333 if curPos == pagePos:
334 if len(cList[curPos]) > 0:
335 content = content + BuildList(cList[curPos], fs, -1, cList)
337 # Otherwise, if our page lies between the current one and the next,
338 # build a list of links from those nodes one level down.
339 elif (pagePos > curPos) and (pagePos < nextPos):
340 content = content + BuildList(cList[curPos], fs, pagePos, cList)
342 content = content + '\n</ul>\n'
348 # Builds the sidebar for the one-page version
350 def BuildOnePageSidebar(fs):
352 content = '\n\n<ul class="toc" style="white-space:nowrap;">\n'
356 for i in range(len(fs)):
357 # Handle Part/Chapter/subchapter/section/subsection numbering
358 level = fs[i]['level']
361 levelNums[level] = levelNums[level] + 1;
364 while j > 0: #level 0 is the part number which is not shown
365 txtlevel = str(levelNums[j]) + '.' + txtlevel
367 if len(txtlevel) > 0:
368 txtlevel = txtlevel[:-1] + ' - '
371 anchor = fs[i]['link']
373 anchor = fs[i]['filename']
376 content = content + '<ul style="white-space:nowrap;">\n'
379 content = content + '</ul>\n'
382 content = content + '<li><a href="#' + anchor + '">' + txtlevel + fs[i]['title'] + '</a></li>\n'
384 content = content + '</ul>\n'
390 # Create link sidebar given a position in the list.
392 def CreateLinkSidebar(fs, pos, childList):
394 # Build the list recursively from the top level nodes
395 content = BuildList(FindTopLevelNodes(fs), fs, pos, childList)
396 # Shove the TOC link and one file link at the top...
397 active = ' class=active' if pos<0 else ''
398 content = content.replace('<ul>','<ul><li' + active + '><a href="/toc/">Table of Contents</a></li>\n',1)
404 # We have command line arguments now, so deal with them
405 parser = argparse.ArgumentParser(description='A build script for the Ardour Manual')
406 parser.add_argument('-v', '--verbose', action='store_true', help='Display the high-level structure of the manual')
407 parser.add_argument('-q', '--quiet', action='store_true', help='Suppress all output (overrides -v)')
408 parser.add_argument('-d', '--devmode', action='store_true', help='Add content to pages to help developers debug them')
409 parser.add_argument('-n', '--nopdf', action='store_true', help='Do not automatically generate PDF from content')
410 args = parser.parse_args()
411 verbose = args.verbose
413 devmode = args.devmode
431 if not quiet and devmode:
432 print('Devmode active: scribbling extra junk to the manual...')
434 if os.access(global_site_dir, os.F_OK):
436 print('Removing stale HTML data...')
438 shutil.rmtree(global_site_dir)
440 shutil.copytree('./source', global_site_dir)
443 # Read the template, and fix the stuff that's fixed for all pages
444 temp = open(global_screen_template)
445 template = temp.read()
447 template = template.replace('{{page.bootstrap_path}}', global_bootstrap_path)
448 template = template.replace('{{page.page_title}}', global_page_title)
450 # Same as above, but for the One-page version
451 temp = open(global_onepage_template)
452 onepage = temp.read()
454 onepage = onepage.replace('{{page.bootstrap_path}}', global_bootstrap_path)
455 onepage = onepage.replace('{{page.page_title}}', global_page_title)
458 # Same as above, but for the PDF version
459 temp = open(global_pdf_template)
460 pdfpage = temp.read()
462 pdfpage = pdfpage.replace('{{page.page_title}}', global_page_title)
464 # Parse out the master document's structure into a dictionary list
465 fileStruct = GetFileStructure()
467 # Build a quasi-tree structure listing children at level + 1 for each node
468 nodeChildren = FindChildren(fileStruct)
470 # Create a dictionary for translation of internal links to real links
471 links = FindInternalLinks(fileStruct)
472 oplinks = FindInternalAnchors(fileStruct)
475 print('Found ' + str(len(links)) + ' internal link target', end='')
476 print('.') if len(links) == 1 else print('s.')
479 master = open(global_master_doc)
480 firstLine = master.readline().rstrip('\r\n')
483 if firstLine == '<!-- exploded -->':
484 print('Parsing exploded file...')
485 elif firstLine == '<!-- imploded -->':
486 print('Parsing imploded file...')
488 print('Parsing unknown type...')
492 for header in fileStruct:
493 fileCount = fileCount + 1
498 level = header['level']
500 # Handle Part/Chapter/subchapter numbering
503 levelNums[level] = levelNums[level] + 1;
505 # This is totally unnecessary, but nice; besides which, you can capture
506 # the output to a file to look at later if you like :-)
508 for i in range(level):
512 print('\nPart ' + num2roman(levelNums[0]) + ': ', end='')
514 print('\n\tChapter ' + str(levelNums[1]) + ': ', end='')
516 print(header['title'])
518 # Handle TOC scriblings and one-page titles...
521 opl = ' id="' + header['link'] + '"'
523 opl = ' id="' + header['filename'] + '"'
526 toc = toc + '<h2>Part ' + num2roman(levelNums[level]) + ': ' + header['title'] + '</h2>\n';
527 oph = '<h1 class="clear"' + opl +'>Part ' + num2roman(levelNums[level]) + ' - ' + header['title'] + '</h1>\n';
529 toc = toc + '\t<p class="chapter">Ch. ' + str(levelNums[level]) + ': <a href="/' + header['filename'] + '/">' + header['title'] + '</a></p>\n'
530 oph = '<h2 class="clear"' + opl +'>' + str(levelNums[level]) + ' - ' + header['title'] + '</h3>\n';
532 toc = toc + '\t\t<p class="subchapter"><a href="/' + header['filename'] + '/">' + header['title'] + '</a></p>\n'
533 oph = '<h3 class="clear"' + opl +'>' + str(levelNums[level-1]) + '.' + str(levelNums[level]) + ' - ' + header['title'] + '</h3>\n';
535 # Make the 'this thing contains...' stuff
536 if HaveChildren(fileStruct, pageNumber):
537 pages = GetChildren(fileStruct, pageNumber)
540 more = more + '<li>' + '<a href="/' + fileStruct[pg]['filename'] + '/">' + fileStruct[pg]['title'] + '</a>' + '</li>\n'
542 more = '<div id=subtopics>\n' + '<h2>This section contains the following topics:</h2>\n' + '<ul>\n' + more + '</ul>\n' + '</div>\n'
544 parent = GetParent(fileStruct, pageNumber)
546 # Make the 'Previous', 'Up' & 'Next' content
552 pLink = '<li class="previous"><a title="' + fileStruct[pageNumber - 1]['title'] + '" href="/' + fileStruct[pageNumber - 1]['filename'] + '/" class="previous"> ← Previous </a></li>'
554 if pageNumber < len(fileStruct) - 1:
555 nLink = '<li class="next"><a title="' + fileStruct[pageNumber + 1]['title'] + '" href="/' + fileStruct[pageNumber + 1]['filename'] + '/" class="next"> Next → </a></li>'
558 uLink = '<li><a title="' + fileStruct[parent]['title'] + '" href="/' + fileStruct[parent]['filename'] + '/" class="active"> ↑ Up </a></li>'
560 uLink = '<li><a title="Ardour Table of Contents" href="/toc/index.html" class="active"> ↑ Up </a></li>'
562 prevnext = '<ul class="pager">' + pLink + uLink + nLink + '</ul>'
564 # Make the BreadCrumbs
565 breadcrumbs = GetBreadCrumbs(fileStruct, pageNumber)
567 # Create the link sidebar
568 sidebar = CreateLinkSidebar(fileStruct, pageNumber, nodeChildren)
570 # Parts DO NOT have any content, they are ONLY an organizing construct!
571 # Chapters, subchapters, sections & subsections can all have content,
572 # but the basic fundamental organizing unit WRT content is still the
577 if 'include' in header:
578 srcFile = open('include/' + header['include'])
579 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>'
580 content = srcFile.read()
583 # Get rid of any extant header in the include file
584 # (once this is accepted, we can nuke this bit, as content files
585 # will not have any headers or footers in them)
586 content = re.sub('---.*\n(.*\n)*---.*\n', '', content)
587 content = content.replace('{% children %}', '')
590 if 'content' in header:
591 content = header['content']
593 content = '[something went wrong]'
595 # Add header information to the page if in dev mode
597 devnote ='<aside style="background-color:indigo; color:white;">'
599 if 'filename' in header:
600 devnote = devnote + 'filename: ' + header['filename'] + '<br>'
602 if 'include' in header:
603 devnote = devnote + 'include: ' + header['include'] + '<br>'
606 devnote = devnote + 'link: ' + header['link'] + '<br>'
608 content = devnote + '</aside>' + content
610 # ----- One page and PDF version -----
612 # Fix up any internal links
613 opcontent = FixInternalLinks(oplinks, content, header['title'])
614 opcontent = reheader(opcontent, 2)
616 # Set up the actual page from the template
617 onepage = onepage.replace('{{ content }}', oph + '\n' + opcontent + '\n{{ content }}')
619 pdfpage = pdfpage.replace('{{ content }}', oph + '\n' + opcontent + '\n{{ content }}')
621 # ----- Normal version -----
623 # Fix up any internal links
624 content = FixInternalLinks(links, content, header['title'])
626 # Set up the actual page from the template
627 if 'style' not in header:
628 page = re.sub("{% if page.style %}.*\n.*\n{% endif %}.*\n", "", template)
630 page = template.replace('{{page.style}}', header['style'])
631 page = page.replace('{% if page.style %}', '')
632 page = page.replace('{% endif %}', '')
634 page = page.replace('{{ page.title }}', header['title'])
635 page = page.replace('{% tree %}', sidebar)
636 page = page.replace('{% prevnext %}', prevnext)
637 page = page.replace('{% githubedit %}', githubedit)
638 page = page.replace('{% breadcrumbs %}', breadcrumbs)
639 page = page.replace('{{ content }}', content + more)
641 # Create the directory for the index.html file to go into (we use makedirs,
642 # because we have to in order to accomodate the 'uri' keyword)
643 os.makedirs(global_site_dir + header['filename'], 0o775, exist_ok=True)
645 # Finally, write the file!
646 destFile = open(global_site_dir + header['filename'] + '/index.html', 'w')
650 # Save filename for next header...
651 lastFile = header['filename']
652 pageNumber = pageNumber + 1
654 # Finally, create the TOC
655 sidebar = CreateLinkSidebar(fileStruct, -1, nodeChildren)
657 page = re.sub("{% if page.style %}.*\n.*\n{% endif %}.*\n", "", template)
658 page = page.replace('{{ page.title }}', 'Ardour Table of Contents')
659 page = page.replace('{% tree %}', sidebar)
660 page = page.replace('{{ content }}', toc)
661 page = page.replace('{% prevnext %}', '')
662 page = page.replace('{% githubedit %}', '')
663 page = page.replace('{% breadcrumbs %}', '')
665 os.mkdir(global_site_dir + 'toc', 0o775)
666 tocFile = open(global_site_dir + 'toc/index.html', 'w')
670 # Create the one-page version of the documentation
671 onepageFile = open(global_site_dir + 'ardourmanual.html', 'w')
672 opsidebar = BuildOnePageSidebar(fileStruct) # create the link sidebar
673 onepage = onepage.replace('{% tree %}', opsidebar)
674 onepage = onepage.replace('{{ content }}', '') # cleans up the last spaceholder
675 onepageFile.write(onepage)
680 print('Generating the PDF...')
682 # Create the PDF version of the documentation
683 pdfpageFile = open(global_site_dir + 'pdf.html', 'w')
684 pdfpage = pdfpage.replace('{% tree %}', opsidebar) # create the TOC
685 pdfpage = pdfpage.replace('{{ content }}', '') # cleans up the last spaceholder
686 pdfpage = pdfpage.replace('src="/images/', 'src="images/') # makes images links relative
687 pdfpage = pdfpage.replace('url(\'/images/', 'url(\'images/') # CSS images links relative
688 pdfpageFile.write(pdfpage)
691 from weasyprint import HTML
692 doc = HTML(filename = global_site_dir + 'pdf.html')
693 doc.write_pdf(global_site_dir + 'manual.pdf')
696 print('Processed ' + str(fileCount) + ' files.')