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')
108 implode.write('uri: ' + header['uri'] + '\n')
110 implode.write('part: ' + header['part'] + '\n' + '---\n')
112 # Only parts have no content...
113 if header['part'] != 'part':
117 fileCount = fileCount + 1
118 inclFile = 'include/' + header['include']
121 fromFile = open(inclFile)
122 except (FileNotFoundError):
123 print('Could not find include file "include/' + header['include'] + '"; aborting!')
124 os.remove('master-doc.txt')
125 os.rename('master-doc.bak', 'master-doc.txt')
128 #eventually this will go away, as this will never happen again...
129 if CheckForHeader(inclFile) == True:
132 while fromFile.readline().startswith('---') == False:
135 ln = fromFile.readline()
137 while fromFile.readline().startswith('---') == False:
140 # shutil.copyfileobj(fromFile, implode)
141 # Strip trailing newlines from content...
142 tempContent = fromFile.read().rstrip('\r\n')
143 implode.write(tempContent + '\n')
145 delList.append(inclFile)
150 print('Processed ' + str(lineCount) + ' lines.')
151 print('Imploded master document from ' + str(fileCount) + ' files.')
153 # Cleanup after successful implode
154 os.remove('master-doc.bak')