]> Shamusworld >> Repos - ardour-manual/blob - build.py
Quick fix for the latest commit referencing an offline file
[ardour-manual] / build.py
1 #!/usr/bin/python3
2 #
3 # Script to take the master document and ancillary files and create the
4 # finished manual/website.
5 #
6 # by James Hammons
7 # (C) 2020 Underground Software
8 #
9 # Contributors: Ed Ward
10 #
11
12 # Remnants (could go into the master document as the first header)
13
14 import os
15 import re
16 import shutil
17 import argparse
18 import datetime
19
20 # Global vars
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')
33
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'"@@[^#"]*[#"]')
38
39 #
40 # Create an all lowercase filename without special characters and with spaces
41 # replaced with dashes.
42 #
43 def MakeFilename(s):
44         global cleanString
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
49         # that here.
50         fn = fn.replace('--', '-')
51
52         return fn
53
54
55 #
56 # Parse headers into a dictionary
57 #
58 def ParseHeader(fileObj):
59         header = {}
60
61         while (True):
62                 hdrLine = fileObj.readline().rstrip('\r\n')
63
64                 # Break out of the loop if we hit the end of header marker
65                 if hdrLine.startswith('---'):
66                         break
67
68                 # Check to see that we have a well-formed header construct
69                 match = re.findall(': ', hdrLine)
70
71                 if match:
72                         # Parse out foo: bar pairs & put into header dictionary
73                         a = re.split(': ', hdrLine, 1)
74                         header[a[0]] = a[1]
75
76         return header
77
78
79 #
80 # Turn a "part" name into an int
81 #
82 def PartToLevel(s):
83         lvl = {'part': 0, 'chapter': 1, 'subchapter': 2, 'section': 3, 'subsection': 4 }
84
85         if s in lvl:
86                 return lvl[s]
87
88         return -1
89
90
91 #
92 # Converts a integer to a Roman numeral
93 #
94 def num2roman(num):
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')]
96         roman = ''
97
98         while num > 0:
99                 for i, r in num_map:
100                         while num >= i:
101                                 roman += r
102                                 num -= i
103
104         return roman
105
106 #
107 # Capture the master document's structure (and content, if any) in a list
108 #
109 def GetFileStructure():
110         fs = []
111         fnames = [None] * 6
112         content = ''
113         grab = False
114         mf = open(global_master_doc)
115
116         for ln in mf:
117                 if ln.startswith('---'):
118                         # First, stuff any content that we may have read into the current
119                         # header's dictionary
120                         if grab:
121                                 fs[-1]['content'] = content
122                                 grab = False
123                                 content = ''
124
125                         # Then, get the new header and do things to it
126                         hdr = ParseHeader(mf)
127                         level = PartToLevel(hdr['part'])
128                         hdr['level'] = level
129                         fnames[level] = MakeFilename(hdr['title'])
130
131                         # Ickyness--user specified URIs
132                         if 'uri' in hdr:
133                                 hdr['filename'] = hdr['uri']
134                         else:
135                                 fullName = ''
136
137                                 for i in range(level + 1):
138                                         fullName = fullName + fnames[i] + '/'
139
140                                 # Strip trailing '/' on filename
141                                 hdr['filename'] = fullName[:-1]
142
143                         fs.append(hdr)
144
145                         if ('include' not in hdr) and (level > 0):
146                                 grab = True
147                 else:
148                         if grab:
149                                 content = content + ln
150
151         # Catch the last file, since it would be missed above
152         if grab:
153                 fs[-1]['content'] = content
154
155         mf.close()
156         return fs
157
158
159 #
160 # Determine if a particular node has child nodes
161 #
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:
165                 return False
166
167         # If the next node is at a lower level than the current node, we have
168         # children.
169         if fs[pos]['level'] < fs[pos + 1]['level']:
170                 return True
171
172         # Otherwise, no children at this node.
173         return False
174
175
176 #
177 # Get the children at this level, and return them in a list
178 #
179 def GetChildren(fs, pos):
180         children = []
181         pos = pos + 1
182         childLevel =  fs[pos]['level']
183
184         while fs[pos]['level'] >= childLevel:
185                 if fs[pos]['level'] == childLevel:
186                         children.append(pos)
187
188                 pos = pos + 1
189
190                 # Sanity check
191                 if pos == len(fs):
192                         break
193
194         return children
195
196
197 #
198 # Get the parent at this level
199 #
200 def GetParent(fs, pos):
201         thisLevel =  fs[pos]['level']
202         pos = pos - 1
203
204         while pos >= 0 and fs[pos]['level'] >= thisLevel:
205                 pos = pos - 1
206
207         return pos
208
209
210 #
211 # Change the hierarchy of titles : <h1>-><hn>, <h2>-><hn+1>, so that the
212 # highest hyerarchy level is maxlevel
213 #
214 def remapheader(txt, maxlevel):
215         maxlvl=1
216         # find the highest hierarchy level in the content
217         while maxlvl < 7 and txt.find('<h' + str(maxlvl)) == -1:
218                 maxlvl += 1
219         # if there is a hierarchy, remap it so that the highest level is maxlevel
220         if maxlvl < 7:
221                 for i in range(6, maxlvl-1, -1):
222                         txt = txt.replace('<h' + str(i), '<h' + str(i + maxlevel - maxlvl))
223                         txt = txt.replace('</h' + str(i), '</h' + str(i + maxlevel - maxlvl))
224
225         return txt
226         
227 #
228 # Creates the BreadCrumbs
229 #
230 def GetBreadCrumbs(fs, pos):
231         breadcrumbs = '<li class="active">'+ fs[pos]['title'] + '</li>'
232
233         while pos >= 0:
234                 pos = GetParent(fs, pos)
235
236                 if pos >= 0:
237                         breadcrumbs='<li><a href="/' + fs[pos]['filename'] + '/">'+ fs[pos]['title'] + '</a></li>'+ breadcrumbs
238
239         breadcrumbs = '<ul class="breadcrumb"><li><a href="/toc/index.html">Home</a></li>' + breadcrumbs + '</ul>'
240         return breadcrumbs
241
242
243 #
244 # Make an array of children attached to each node in the file structure
245 # (It's a quasi-tree structure, and can be traversed as such.)
246 #
247 def FindChildren(fs):
248         childArray = []
249
250         for i in range(len(fs)):
251                 if HaveChildren(fs, i):
252                         childArray.append(GetChildren(fs, i))
253                 else:
254                         childArray.append([])
255
256         return childArray
257
258
259 #
260 # Make an array of the top level nodes in the file structure
261 #
262 def FindTopLevelNodes(fs):
263         level0 = []
264
265         for i in range(len(fs)):
266                 if fs[i]['level'] == 0:
267                         level0.append(i)
268
269         return level0
270
271
272 #
273 # Find all header links and create a dictionary out of them
274 #
275 def FindInternalLinks(fs):
276         linkDict = {}
277
278         for hdr in fs:
279                 if 'link' in hdr:
280                         linkDict['"@@' + hdr['link'] + '"'] = '"/' + hdr['filename'] + '/"'
281                         linkDict['"@@' + hdr['link'] + '#'] = '"/' + hdr['filename'] + '/index.html#'
282
283         return linkDict
284
285
286 #
287 # Same as above, but create anchors (for the one-page version)
288 #
289 def FindInternalAnchors(fs):
290         linkDict = {}
291
292         for hdr in fs:
293                 if 'link' in hdr:
294                         linkDict['"@@' + hdr['link'] + '"'] = '"#' + hdr['link'] + '"'
295                         linkDict['"@@' + hdr['link'] + '#'] = '"#' + hdr['link'] + '"'
296
297         return linkDict
298
299
300 #
301 # Internal links are of the form '@@link-name', which are references to the
302 # 'link:' field in the part header. We have to find all occurrences and replace
303 # them with the appropriate link.
304 #
305 def FixInternalLinks(links, content, title):
306         global findLinks
307         match = findLinks.findall(content)
308         missing = []
309
310         if len(match) > 0:
311                 for s in match:
312                         if s in links:
313                                 content = content.replace(s, links[s])
314                         else:
315                                 missing.append(s)
316
317         # Report missing link targets to the user (if any)
318         if len(missing) > 0:
319                 print('\nMissing link target' + ('s' if len(missing) > 1 else '') + ' in "' + title + '":')
320
321                 for s in missing:
322                         print('  ' + s)
323
324                 print()
325
326         return content
327
328
329 #
330 # Recursively build a list of links based on the location of the page we're
331 # looking at currently
332 #
333 def BuildList(lst, fs, pagePos, cList):
334         content = '<ul>\n'
335
336         for i in range(len(lst)):
337                 curPos = lst[i]
338                 nextPos = lst[i + 1] if i + 1 < len(lst) else len(fs)
339
340                 active = ' class=active' if curPos == pagePos else ''
341                 menuTitle = fs[curPos]['menu_title'] if 'menu_title' in fs[curPos] else fs[curPos]['title']
342                 content = content + '\t<li' + active + '><a href="/' + fs[curPos]['filename'] + '/">' + menuTitle + '</a></li>\n'
343
344                 # If the current page is our page, and it has children, enumerate them
345                 if curPos == pagePos:
346                         if len(cList[curPos]) > 0:
347                                 content = content + BuildList(cList[curPos], fs, -1, cList)
348
349                 # Otherwise, if our page lies between the current one and the next,
350                 # build a list of links from those nodes one level down.
351                 elif (pagePos > curPos) and (pagePos < nextPos):
352                         content = content + BuildList(cList[curPos], fs, pagePos, cList)
353
354         content = content + '</ul>\n'
355
356         return content
357
358
359 #
360 # Builds the sidebar for the one-page version
361 #
362 def BuildOnePageSidebar(fs):
363
364         content = '\n\n<ul class="toc">\n'
365         lvl = 0
366         levelNums = [0] * 5
367
368         for i in range(len(fs)):
369                 # Handle Part/Chapter/subchapter/section/subsection numbering
370                 level = fs[i]['level']
371
372                 if level < 2:
373                         levelNums[2] = 0
374
375                 levelNums[level] = levelNums[level] + 1;
376                 j = level
377                 txtlevel = ''
378
379                 while j > 0:  #level 0 is the part number which is not shown
380                         txtlevel = str(levelNums[j]) + '.' + txtlevel
381                         j = j - 1
382
383                 if len(txtlevel) > 0:
384                         txtlevel = txtlevel[:-1] + ' - '
385
386                 if 'link' in fs[i]:
387                         anchor = fs[i]['link']
388                 else:
389                         anchor = fs[i]['filename']
390
391                 while lvl < level:
392                         content = content + '<ul class="toc">\n'
393                         lvl = lvl + 1
394
395                 while lvl > level:
396                         content = content + '</ul>\n'
397                         lvl = lvl - 1
398
399                 content = content + '<li><a href="#' + anchor + '">' + txtlevel + fs[i]['title'] + '</a></li>\n'
400
401         content = content + '</ul>\n'
402
403         return content
404
405
406 #
407 # Create link sidebar given a position in the list.
408 #
409 def CreateLinkSidebar(fs, pos, childList):
410
411         # Build the list recursively from the top level nodes
412         content = BuildList(FindTopLevelNodes(fs), fs, pos, childList)
413         # Shove the TOC link and one file link at the top...
414         active = ' class=active' if pos < 0 else ''
415         content = content.replace('<ul>', '<ul><li' + active + '><a href="/toc/">Table of Contents</a></li>\n', 1)
416
417         return content
418
419
420 # Preliminaries
421
422 # We have command line arguments now, so deal with them
423 parser = argparse.ArgumentParser(description='A build script for the Ardour Manual')
424 parser.add_argument('-v', '--verbose', action='store_true', help='Display the high-level structure of the manual')
425 parser.add_argument('-q', '--quiet', action='store_true', help='Suppress all output (overrides -v)')
426 parser.add_argument('-d', '--devmode', action='store_true', help='Add content to pages to help developers debug them')
427 parser.add_argument('-p', '--pdf', action='store_true', help='Automatically generate PDF from content')
428 args = parser.parse_args()
429 verbose = args.verbose
430 noisy = not args.quiet
431 devmode = args.devmode
432 pdf = args.pdf
433
434 # --quiet overrides --verbose, so tell it to shut up if user did both
435 if not noisy:
436         verbose = False
437
438 level = 0
439 fileCount = 0
440 levelNums = [0] * 5
441 lastFile = ''
442 page = ''
443 onepage = ''
444 pdfpage = ''
445 toc = ''
446 pageNumber = 0
447
448 if noisy and devmode:
449         print('Devmode active: scribbling extra junk to the manual...')
450
451 if os.access(global_site_dir, os.F_OK):
452         if noisy:
453                 print('Removing stale HTML data...')
454
455         shutil.rmtree(global_site_dir)
456
457 shutil.copytree('./source', global_site_dir)
458
459 # Read the template, and fix the stuff that's fixed for all pages
460 temp = open(global_screen_template)
461 template = temp.read()
462 temp.close()
463 template = template.replace('{{page.bootstrap_path}}', global_bootstrap_path)
464 template = template.replace('{{page.page_title}}', global_page_title)
465 if pdf:
466         template = template.replace('{{page.page_pdflink}}', global_pdflink)
467 else:
468         template = template.replace('{{page.page_pdflink}}', '')
469
470
471 # Same as above, but for the "One-Page" version
472 temp = open(global_onepage_template)
473 onepage = temp.read()
474 temp.close()
475 onepage = onepage.replace('{{page.bootstrap_path}}', global_bootstrap_path)
476 onepage = onepage.replace('{{page.page_title}}', global_page_title)
477
478 if pdf:
479         # Same as above, but for the PDF version
480         temp = open(global_pdf_template)
481         pdfpage = temp.read()
482         temp.close()
483         pdfpage = pdfpage.replace('{{page.page_title}}', global_page_title)
484
485 # Parse out the master document's structure into a dictionary list
486 fileStruct = GetFileStructure()
487
488 # Build a quasi-tree structure listing children at level + 1 for each node
489 nodeChildren = FindChildren(fileStruct)
490
491 # Create a dictionary for translation of internal links to real links
492 links = FindInternalLinks(fileStruct)
493 oplinks = FindInternalAnchors(fileStruct)
494
495 if noisy:
496         print('Found ' + str(len(links)) + ' internal link target', end='')
497         print('.') if len(links) == 1 else print('s.')
498
499 if noisy:
500         master = open(global_master_doc)
501         firstLine = master.readline().rstrip('\r\n')
502         master.close()
503
504         if firstLine == '<!-- exploded -->':
505                 print('Parsing exploded file...')
506         elif firstLine == '<!-- imploded -->':
507                 print('Parsing imploded file...')
508         else:
509                 print('Parsing unknown type...')
510
511 # Here we go!
512
513 for header in fileStruct:
514         fileCount = fileCount + 1
515         content = ''
516         more = ''
517
518         lastLevel = level
519         level = header['level']
520
521         # Handle Part/Chapter/subchapter/section/subsection numbering
522         if level < 2:
523                 levelNums[2] = 0
524
525         levelNums[level] = levelNums[level] + 1;
526
527         # This is totally unnecessary, but nice; besides which, you can capture
528         # the output to a file to look at later if you like :-)
529         if verbose:
530                 for i in range(level):
531                         print('\t', end='')
532
533                 if (level == 0):
534                         print('\nPart ' + num2roman(levelNums[0]) + ': ', end='')
535                 elif (level == 1):
536                         print('\n\tChapter ' + str(levelNums[1]) + ': ', end='')
537
538                 print(header['title'])
539
540         # Handle TOC scriblings...
541         if level == 0:
542                 toc = toc + '<h2>Part ' + num2roman(levelNums[level]) + ': ' + header['title'] + '</h2>\n';
543         elif level == 1:
544                 toc = toc + '\t<p class="chapter">Ch. ' + str(levelNums[level]) + ':&nbsp;&nbsp;<a href="/' + header['filename'] + '/">' + header['title'] + '</a></p>\n'
545         elif level == 2:
546                 toc = toc + '\t\t<p class="subchapter"><a href="/' + header['filename'] + '/">' + header['title'] + '</a></p>\n'
547         elif level == 3:
548                 toc = toc + '<p class="section"><a href="/' + header['filename'] + '/">' + header['title'] + '</a></p>\n'
549         elif level == 4:
550                 toc = toc + '<p class="subsection"><a href="/' + header['filename'] + '/">' + header['title'] + '</a></p>\n'
551
552         # Make the 'this thing contains...' stuff
553         if HaveChildren(fileStruct, pageNumber):
554                 pages = GetChildren(fileStruct, pageNumber)
555
556                 for pg in pages:
557                         more = more + '<li>' + '<a href="/' + fileStruct[pg]['filename'] + '/">' + fileStruct[pg]['title'] + '</a>' + '</li>\n'
558
559                 more = '<div id=subtopics>\n' + '<h2>This section contains the following topics:</h2>\n' + '<ul>\n' + more + '</ul>\n' + '</div>\n'
560
561         parent = GetParent(fileStruct, pageNumber)
562
563         # Make the 'Previous', 'Up' & 'Next' content
564         nLink = ''
565         pLink = ''
566         uLink = ''
567
568         if pageNumber > 0:
569                 pLink = '<li class="previous"><a title="' + fileStruct[pageNumber - 1]['title'] + '" href="/' + fileStruct[pageNumber - 1]['filename'] + '/" class="previous"> &larr; Previous </a></li>'
570
571         if pageNumber < len(fileStruct) - 1:
572                 nLink = '<li class="next"><a title="' + fileStruct[pageNumber + 1]['title'] + '" href="/' + fileStruct[pageNumber + 1]['filename'] + '/" class="next"> Next &rarr; </a></li>'
573
574         if level > 0:
575                 uLink = '<li><a title="' + fileStruct[parent]['title'] + '" href="/' + fileStruct[parent]['filename'] + '/" class="active"> &uarr; Up </a></li>'
576         else:
577                 uLink = '<li><a title="Ardour Table of Contents" href="/toc/index.html" class="active"> &uarr; Up </a></li>'
578
579         prevnext = '<ul class="pager">' + pLink + uLink + nLink + '</ul>'
580
581         # Make the BreadCrumbs
582         breadcrumbs = GetBreadCrumbs(fileStruct, pageNumber)
583
584         # Create the link sidebar
585         sidebar = CreateLinkSidebar(fileStruct, pageNumber, nodeChildren)
586
587         # Parts DO NOT have any content, they are ONLY an organizing construct!
588         # Chapters, subchapters, sections & subsections can all have content,
589         # but the basic fundamental organizing unit WRT content is still the
590         # chapter.
591         githubedit = ''
592
593         if level > 0:
594                 if 'include' in header:
595                         srcFile = open('include/' + header['include'])
596                         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>'
597                         content = srcFile.read()
598                         srcFile.close()
599
600                         # Get rid of any extant header in the include file
601                         # (once this is accepted, we can nuke this bit, as content files
602                         # will not have any headers or footers in them)
603                         content = re.sub('---.*\n(.*\n)*---.*\n', '', content)
604                         content = content.replace('{% children %}', '')
605
606                 else:
607                         if 'content' in header:
608                                 content = header['content']
609                         else:
610                                 content = '[something went wrong]'
611
612         # Add header information to the page if in dev mode
613         if devmode:
614                 devnote ='<aside style="background-color:indigo; color:white;">'
615
616                 if 'filename' in header:
617                         devnote = devnote + 'filename: ' + header['filename'] + '<br>'
618
619                 if 'include' in header:
620                         devnote = devnote + 'include: ' + header['include'] + '<br>'
621
622                 if 'link' in header:
623                         devnote = devnote + 'link: ' + header['link'] + '<br>'
624
625                 content = devnote + '</aside>' + content
626
627         # ----- One page and PDF version -----
628
629         # Fix up any internal links
630         opcontent = FixInternalLinks(oplinks, content, header['title'])
631         opcontent = remapheader(opcontent, level+2)
632
633         # Create "one page" header
634         oph = '<h' + str(level+1) + ' class="clear" id="' + header[('link' if 'link' in header else 'filename')] +'">' + header['title'] + '</h' + str(level+1) + '>\n';
635
636         # Set up the actual page from the template
637         onepage = onepage.replace('{{ content }}', oph + '\n' + opcontent + '\n{{ content }}')
638
639         if pdf:
640                 if not 'pdf-exclude' in header:
641                         pdfpage = pdfpage.replace('{{ content }}', oph + '\n' + opcontent + '\n{{ content }}')
642                 else:
643                         pdfpage = pdfpage.replace('{{ content }}', oph + '\n' + 'Please refer to the <a href="' + global_manual_url + '/' + header['filename'] + '/">online manual</a>.\n{{ content }}')
644
645         # ----- Normal version -----
646
647         # Fix up any internal links
648         content = FixInternalLinks(links, content, header['title'])
649
650         # Set up the actual page from the template
651         if 'style' not in header:
652                 page = re.sub("{% if page.style %}.*\n.*\n{% endif %}.*\n", "", template)
653         else:
654                 page = template.replace('{{page.style}}', header['style'])
655                 page = page.replace('{% if page.style %}', '')
656                 page = page.replace('{% endif %}', '')
657
658         page = page.replace('{{ page.title }}', header['title'])
659         page = page.replace('{% tree %}', sidebar)
660         page = page.replace('{% prevnext %}', prevnext)
661         page = page.replace('{% githubedit %}', githubedit)
662         page = page.replace('{% breadcrumbs %}', breadcrumbs)
663         page = page.replace('{{ content }}', content + more)
664
665         # Create the directory for the index.html file to go into (we use makedirs,
666         # because we have to in order to accomodate the 'uri' keyword)
667         os.makedirs(global_site_dir + header['filename'], 0o775, exist_ok=True)
668
669         # Finally, write the file!
670         destFile = open(global_site_dir + header['filename'] + '/index.html', 'w')
671         destFile.write(page)
672         destFile.close()
673
674         # Save filename for next header...
675         lastFile = header['filename']
676         pageNumber = pageNumber + 1
677
678 # Finally, create the TOC
679 sidebar = CreateLinkSidebar(fileStruct, -1, nodeChildren)
680
681 page = re.sub("{% if page.style %}.*\n.*\n{% endif %}.*\n", "", template)
682 page = page.replace('{{ page.title }}', 'Ardour Table of Contents')
683 page = page.replace('{% tree %}', sidebar)
684 page = page.replace('{{ content }}', toc)
685 page = page.replace('{% prevnext %}', '')
686 page = page.replace('{% githubedit %}', '')
687 page = page.replace('{% breadcrumbs %}', '')
688
689 os.mkdir(global_site_dir + 'toc', 0o775)
690 tocFile = open(global_site_dir + 'toc/index.html', 'w')
691 tocFile.write(page)
692 tocFile.close()
693
694 # Create the one-page version of the documentation
695 onepageFile = open(global_site_dir + 'ardourmanual.html', 'w')
696 opsidebar = BuildOnePageSidebar(fileStruct) # create the link sidebar
697 onepage = onepage.replace('{% tree %}', opsidebar)
698 onepage = onepage.replace('{{ content }}', '') # cleans up the last spaceholder
699 onepageFile.write(onepage)
700 onepageFile.close()
701
702 if pdf:
703         if noisy:
704                 print('Generating the PDF...')
705                 import logging
706                 logger = logging.getLogger('weasyprint')
707                 logger.addHandler(logging.StreamHandler())
708
709         # Create the PDF version of the documentation
710         pdfpage = pdfpage.replace('{% tree %}', opsidebar) # create the TOC
711         pdfpage = pdfpage.replace('{{ content }}', '') # cleans up the last spaceholder
712         pdfpage = pdfpage.replace('{{ today }}', global_today)
713         pdfpage = pdfpage.replace('src="/images/', 'src="images/') # makes images links relative
714         pdfpage = pdfpage.replace('url(\'/images/', 'url(\'images/') # CSS images links relative
715         # Write it to disk (optional, can be removed)
716         pdfpageFile = open(global_site_dir + 'pdf.html', 'w')
717         pdfpageFile.write(pdfpage)
718         pdfpageFile.close()
719
720         # Generating the actual PDF with weasyprint (https://weasyprint.org/)
721         from weasyprint import HTML
722         from weasyprint.text.fonts import FontConfiguration
723         
724         html_font_config = FontConfiguration()
725         doc = HTML(string = pdfpage, base_url = global_site_dir)
726         doc.write_pdf(global_site_dir + 'manual.pdf', font_config = html_font_config)
727
728 if noisy:
729         print('Processed ' + str(fileCount) + ' files.')
730