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_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
84 lvl = {'part': 0, 'chapter': 1, 'subchapter': 2}
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))
221 # Creates the BreadCrumbs
223 def GetBreadCrumbs(fs, pos):
224 breadcrumbs = '<li class="active">'+ fs[pos]['title'] + '</li>'
227 pos = GetParent(fs, pos)
230 breadcrumbs='<li><a href="/' + fs[pos]['filename'] + '/">'+ fs[pos]['title'] + '</a></li>'+ breadcrumbs
232 breadcrumbs = '<ul class="breadcrumb"><li><a href="/toc/index.html">Home</a></li>' + breadcrumbs + '</ul>'
237 # Make an array of children attached to each node in the file structure
238 # (It's a quasi-tree structure, and can be traversed as such.)
240 def FindChildren(fs):
243 for i in range(len(fs)):
244 if HaveChildren(fs, i):
245 childArray.append(GetChildren(fs, i))
247 childArray.append([])
253 # Make an array of the top level nodes in the file structure
255 def FindTopLevelNodes(fs):
258 for i in range(len(fs)):
259 if fs[i]['level'] == 0:
266 # Find all header links and create a dictionary out of them
268 def FindInternalLinks(fs):
273 linkDict['"@@' + hdr['link'] + '"'] = '"/' + hdr['filename'] + '/"'
274 linkDict['"@@' + hdr['link'] + '#'] = '"/' + hdr['filename'] + '/index.html#'
279 # Same as above, but create anchors (for the one-page version)
281 def FindInternalAnchors(fs):
286 linkDict['"@@' + hdr['link'] + '"'] = '"#' + hdr['link'] + '"'
287 linkDict['"@@' + hdr['link'] + '#'] = '"#' + hdr['link'] + '"'
293 # Internal links are of the form '@@link-name', which are references to the
294 # 'link:' field in the part header. We have to find all occurrences and replace
295 # them with the appropriate link.
297 def FixInternalLinks(links, content, title):
299 match = findLinks.findall(content)
305 content = content.replace(s, links[s])
309 # Report missing link targets to the user (if any)
311 print('\nMissing link target' + ('s' if len(missing) > 1 else '') + ' in "' + title + '":')
322 # Recursively build a list of links based on the location of the page we're
323 # looking at currently
325 def BuildList(lst, fs, pagePos, cList):
328 for i in range(len(lst)):
330 nextPos = lst[i + 1] if i + 1 < len(lst) else len(fs)
332 active = ' class=active' if curPos == pagePos else ''
333 menuTitle = fs[curPos]['menu_title'] if 'menu_title' in fs[curPos] else fs[curPos]['title']
334 content = content + '\t<li' + active + '><a href="/' + fs[curPos]['filename'] + '/">' + menuTitle + '</a></li>\n'
336 # If the current page is our page, and it has children, enumerate them
337 if curPos == pagePos:
338 if len(cList[curPos]) > 0:
339 content = content + BuildList(cList[curPos], fs, -1, cList)
341 # Otherwise, if our page lies between the current one and the next,
342 # build a list of links from those nodes one level down.
343 elif (pagePos > curPos) and (pagePos < nextPos):
344 content = content + BuildList(cList[curPos], fs, pagePos, cList)
346 content = content + '</ul>\n'
352 # Builds the sidebar for the one-page version
354 def BuildOnePageSidebar(fs):
356 content = '\n\n<ul class="toc">\n'
360 for i in range(len(fs)):
361 # Handle Part/Chapter/subchapter numbering
362 level = fs[i]['level']
365 levelNums[level] = levelNums[level] + 1;
368 while j > 0: #level 0 is the part number which is not shown
369 txtlevel = str(levelNums[j]) + '.' + txtlevel
371 if len(txtlevel) > 0:
372 txtlevel = txtlevel[:-1] + ' - '
375 anchor = fs[i]['link']
377 anchor = fs[i]['filename']
380 content = content + '<ul class="toc">\n'
383 content = content + '</ul>\n'
386 content = content + '<li><a href="#' + anchor + '">' + txtlevel + fs[i]['title'] + '</a></li>\n'
388 content = content + '</ul>\n'
394 # Create link sidebar given a position in the list.
396 def CreateLinkSidebar(fs, pos, childList):
398 # Build the list recursively from the top level nodes
399 content = BuildList(FindTopLevelNodes(fs), fs, pos, childList)
400 # Shove the TOC link and one file link at the top...
401 active = ' class=active' if pos<0 else ''
402 content = content.replace('<ul>','<ul><li' + active + '><a href="/toc/">Table of Contents</a></li>',1)
408 # We have command line arguments now, so deal with them
409 parser = argparse.ArgumentParser(description='A build script for the Ardour Manual')
410 parser.add_argument('-v', '--verbose', action='store_true', help='Display the high-level structure of the manual')
411 parser.add_argument('-q', '--quiet', action='store_true', help='Suppress all output (overrides -v)')
412 parser.add_argument('-d', '--devmode', action='store_true', help='Add content to pages to help developers debug them')
413 parser.add_argument('-n', '--nopdf', action='store_true', help='Do not automatically generate PDF from content')
414 args = parser.parse_args()
415 verbose = args.verbose
417 devmode = args.devmode
435 if not quiet and devmode:
436 print('Devmode active: scribbling extra junk to the manual...')
438 if os.access(global_site_dir, os.F_OK):
440 print('Removing stale HTML data...')
442 shutil.rmtree(global_site_dir)
444 shutil.copytree('./source', global_site_dir)
447 # Read the template, and fix the stuff that's fixed for all pages
448 temp = open(global_screen_template)
449 template = temp.read()
451 template = template.replace('{{page.bootstrap_path}}', global_bootstrap_path)
452 template = template.replace('{{page.page_title}}', global_page_title)
454 # Same as above, but for the One-page version
455 temp = open(global_onepage_template)
456 onepage = temp.read()
458 onepage = onepage.replace('{{page.bootstrap_path}}', global_bootstrap_path)
459 onepage = onepage.replace('{{page.page_title}}', global_page_title)
462 # Same as above, but for the PDF version
463 temp = open(global_pdf_template)
464 pdfpage = temp.read()
466 pdfpage = pdfpage.replace('{{page.page_title}}', global_page_title)
468 # Parse out the master document's structure into a dictionary list
469 fileStruct = GetFileStructure()
471 # Build a quasi-tree structure listing children at level + 1 for each node
472 nodeChildren = FindChildren(fileStruct)
474 # Create a dictionary for translation of internal links to real links
475 links = FindInternalLinks(fileStruct)
476 oplinks = FindInternalAnchors(fileStruct)
479 print('Found ' + str(len(links)) + ' internal link target', end='')
480 print('.') if len(links) == 1 else print('s.')
483 master = open(global_master_doc)
484 firstLine = master.readline().rstrip('\r\n')
487 if firstLine == '<!-- exploded -->':
488 print('Parsing exploded file...')
489 elif firstLine == '<!-- imploded -->':
490 print('Parsing imploded file...')
492 print('Parsing unknown type...')
496 for header in fileStruct:
497 fileCount = fileCount + 1
502 level = header['level']
504 # Handle Part/Chapter/subchapter numbering
507 levelNums[level] = levelNums[level] + 1;
509 # This is totally unnecessary, but nice; besides which, you can capture
510 # the output to a file to look at later if you like :-)
512 for i in range(level):
516 print('\nPart ' + num2roman(levelNums[0]) + ': ', end='')
518 print('\n\tChapter ' + str(levelNums[1]) + ': ', end='')
520 print(header['title'])
522 # Handle TOC scriblings...
524 toc = toc + '<h2>Part ' + num2roman(levelNums[level]) + ': ' + header['title'] + '</h2>\n';
526 toc = toc + '\t<p class="chapter">Ch. ' + str(levelNums[level]) + ': <a href="/' + header['filename'] + '/">' + header['title'] + '</a></p>\n'
528 toc = toc + '\t\t<p class="subchapter"><a href="/' + header['filename'] + '/">' + header['title'] + '</a></p>\n'
530 # Handle one-page and PDF titles...
533 opl = ' id="' + header['link'] + '"'
535 opl = ' id="' + header['filename'] + '"'
536 oph = '<h' + str(level+1) + ' class="clear"' + opl +'>' + header['title'] + '</h' + str(level+1) + '>\n';
539 # Make the 'this thing contains...' stuff
540 if HaveChildren(fileStruct, pageNumber):
541 pages = GetChildren(fileStruct, pageNumber)
544 more = more + '<li>' + '<a href="/' + fileStruct[pg]['filename'] + '/">' + fileStruct[pg]['title'] + '</a>' + '</li>\n'
546 more = '<div id=subtopics>\n' + '<h2>This section contains the following topics:</h2>\n' + '<ul>\n' + more + '</ul>\n' + '</div>\n'
548 parent = GetParent(fileStruct, pageNumber)
550 # Make the 'Previous', 'Up' & 'Next' content
556 pLink = '<li class="previous"><a title="' + fileStruct[pageNumber - 1]['title'] + '" href="/' + fileStruct[pageNumber - 1]['filename'] + '/" class="previous"> ← Previous </a></li>'
558 if pageNumber < len(fileStruct) - 1:
559 nLink = '<li class="next"><a title="' + fileStruct[pageNumber + 1]['title'] + '" href="/' + fileStruct[pageNumber + 1]['filename'] + '/" class="next"> Next → </a></li>'
562 uLink = '<li><a title="' + fileStruct[parent]['title'] + '" href="/' + fileStruct[parent]['filename'] + '/" class="active"> ↑ Up </a></li>'
564 uLink = '<li><a title="Ardour Table of Contents" href="/toc/index.html" class="active"> ↑ Up </a></li>'
566 prevnext = '<ul class="pager">' + pLink + uLink + nLink + '</ul>'
568 # Make the BreadCrumbs
569 breadcrumbs = GetBreadCrumbs(fileStruct, pageNumber)
571 # Create the link sidebar
572 sidebar = CreateLinkSidebar(fileStruct, pageNumber, nodeChildren)
574 # Parts DO NOT have any content, they are ONLY an organizing construct!
575 # Chapters, subchapters, sections & subsections can all have content,
576 # but the basic fundamental organizing unit WRT content is still the
581 if 'include' in header:
582 srcFile = open('include/' + header['include'])
583 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>'
584 content = srcFile.read()
587 # Get rid of any extant header in the include file
588 # (once this is accepted, we can nuke this bit, as content files
589 # will not have any headers or footers in them)
590 content = re.sub('---.*\n(.*\n)*---.*\n', '', content)
591 content = content.replace('{% children %}', '')
594 if 'content' in header:
595 content = header['content']
597 content = '[something went wrong]'
599 # Add header information to the page if in dev mode
601 devnote ='<aside style="background-color:indigo; color:white;">'
603 if 'filename' in header:
604 devnote = devnote + 'filename: ' + header['filename'] + '<br>'
606 if 'include' in header:
607 devnote = devnote + 'include: ' + header['include'] + '<br>'
610 devnote = devnote + 'link: ' + header['link'] + '<br>'
612 content = devnote + '</aside>' + content
614 # ----- One page and PDF version -----
616 # Fix up any internal links
617 opcontent = FixInternalLinks(oplinks, content, header['title'])
618 opcontent = reheader(opcontent, 2)
620 # Set up the actual page from the template
621 onepage = onepage.replace('{{ content }}', oph + '\n' + opcontent + '\n{{ content }}')
623 if not 'pdf-exclude' in header:
624 pdfpage = pdfpage.replace('{{ content }}', oph + '\n' + opcontent + '\n{{ content }}')
626 pdfpage = pdfpage.replace('{{ content }}', oph + '\n' + 'Please refer to the <a href="' + global_manual_url + '/' + header['filename'] + '/">online manual</a>.\n{{ content }}')
628 # ----- Normal version -----
630 # Fix up any internal links
631 content = FixInternalLinks(links, content, header['title'])
633 # Set up the actual page from the template
634 if 'style' not in header:
635 page = re.sub("{% if page.style %}.*\n.*\n{% endif %}.*\n", "", template)
637 page = template.replace('{{page.style}}', header['style'])
638 page = page.replace('{% if page.style %}', '')
639 page = page.replace('{% endif %}', '')
641 page = page.replace('{{ page.title }}', header['title'])
642 page = page.replace('{% tree %}', sidebar)
643 page = page.replace('{% prevnext %}', prevnext)
644 page = page.replace('{% githubedit %}', githubedit)
645 page = page.replace('{% breadcrumbs %}', breadcrumbs)
646 page = page.replace('{{ content }}', content + more)
648 # Create the directory for the index.html file to go into (we use makedirs,
649 # because we have to in order to accomodate the 'uri' keyword)
650 os.makedirs(global_site_dir + header['filename'], 0o775, exist_ok=True)
652 # Finally, write the file!
653 destFile = open(global_site_dir + header['filename'] + '/index.html', 'w')
657 # Save filename for next header...
658 lastFile = header['filename']
659 pageNumber = pageNumber + 1
661 # Finally, create the TOC
662 sidebar = CreateLinkSidebar(fileStruct, -1, nodeChildren)
664 page = re.sub("{% if page.style %}.*\n.*\n{% endif %}.*\n", "", template)
665 page = page.replace('{{ page.title }}', 'Ardour Table of Contents')
666 page = page.replace('{% tree %}', sidebar)
667 page = page.replace('{{ content }}', toc)
668 page = page.replace('{% prevnext %}', '')
669 page = page.replace('{% githubedit %}', '')
670 page = page.replace('{% breadcrumbs %}', '')
672 os.mkdir(global_site_dir + 'toc', 0o775)
673 tocFile = open(global_site_dir + 'toc/index.html', 'w')
677 # Create the one-page version of the documentation
678 onepageFile = open(global_site_dir + 'ardourmanual.html', 'w')
679 opsidebar = BuildOnePageSidebar(fileStruct) # create the link sidebar
680 onepage = onepage.replace('{% tree %}', opsidebar)
681 onepage = onepage.replace('{{ content }}', '') # cleans up the last spaceholder
682 onepageFile.write(onepage)
687 print('Generating the PDF...')
689 # Create the PDF version of the documentation
690 pdfpage = pdfpage.replace('{% tree %}', opsidebar) # create the TOC
691 pdfpage = pdfpage.replace('{{ content }}', '') # cleans up the last spaceholder
692 pdfpage = pdfpage.replace('{{ today }}', global_today)
693 pdfpage = pdfpage.replace('{{ today_iso }}', global_today_iso)
694 pdfpage = pdfpage.replace('src="/images/', 'src="images/') # makes images links relative
695 pdfpage = pdfpage.replace('url(\'/images/', 'url(\'images/') # CSS images links relative
696 # Write it to disk (optional, can be removed)
697 pdfpageFile = open(global_site_dir + 'pdf.html', 'w')
698 pdfpageFile.write(pdfpage)
701 # Generating the actual PDF with weasyprint (https://weasyprint.org/)
702 from weasyprint import HTML
703 from weasyprint.fonts import FontConfiguration
704 html_font_config = FontConfiguration()
705 doc = HTML(string = pdfpage, base_url = global_site_dir)
706 doc.write_pdf(global_site_dir + 'manual.pdf', font_config = html_font_config)
709 print('Processed ' + str(fileCount) + ' files.')