3 # Small program to 'implode' the master document automagically from separate
4 # files in the include/ directory.
7 # (C) 2017 Underground Software
18 # Parse headers into a dictionary
20 def ParseHeader(fileObj):
25 hdrLine = fileObj.readline().rstrip('\r\n')
26 lineCount = lineCount + 1
28 # Break out of the loop if we hit the end of header marker
29 if hdrLine.startswith('---'):
32 # Check to see that we have a well-formed header construct
33 match = re.findall(': ', hdrLine)
36 # Parse out foo: bar pairs & put into header dictionary
37 a = re.split(': ', hdrLine, 1)
44 # Check to see if a given file has a header (it shouldn't)
46 def CheckForHeader(fn):
50 if line.startswith('---'):
61 master = open('master-doc.txt')
62 firstLine = master.readline().rstrip('\r\n')
65 if firstLine == '<!-- imploded -->':
66 print('Master file has already been imploded.')
69 if os.rename('master-doc.txt', 'master-doc.bak') == False:
70 print('Could not rename master-doc.txt!')
73 master = open('master-doc.bak', 'r')
74 implode = open('master-doc.txt', 'w')
76 implode.write('<!-- imploded -->\n')
79 lineCount = lineCount + 1
81 # Do any header parsing if needed...
82 if line.startswith('---'):
85 header = ParseHeader(master)
87 # Pull in files and write the result to the master file
88 implode.write('\n---\n' + 'title: ' + header['title'] + '\n')
90 if header['part'] != 'part':
91 if 'menu_title' in header:
92 implode.write('menu_title: ' + header['menu_title'] + '\n')
95 implode.write('link: ' + header['link'] + '\n')
98 implode.write('style: ' + header['style'] + '\n')
100 implode.write('file: ' + header['include'] + '\n')
102 if ('exclude' in header) and ('include' in header):
104 implode.write('include: ' + header['include'] + '\n')
105 implode.write('exclude: yes\n')
107 implode.write('part: ' + header['part'] + '\n' + '---\n')
109 # Only parts have no content...
110 if header['part'] != 'part':
114 fileCount = fileCount + 1
115 inclFile = 'include/' + header['include']
118 fromFile = open(inclFile)
119 except (FileNotFoundError):
120 print('Could not find include file "include/' + header['include'] + '"; aborting!')
121 os.remove('master-doc.txt')
122 os.rename('master-doc.bak', 'master-doc.txt')
125 #eventually this will go away, as this will never happen again...
126 if CheckForHeader(inclFile) == True:
129 while fromFile.readline().startswith('---') == False:
132 ln = fromFile.readline()
134 while fromFile.readline().startswith('---') == False:
137 shutil.copyfileobj(fromFile, implode)
139 delList.append(inclFile)
144 print('Processed ' + str(lineCount) + ' lines.')
145 print('Imploded master document from ' + str(fileCount) + ' files.')
147 # Cleanup after successful implode
148 os.remove('master-doc.bak')