-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
303 lines (256 loc) · 7.99 KB
/
main.py
File metadata and controls
303 lines (256 loc) · 7.99 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
import argparse
import gzip
import hashlib
import itertools
from glob import glob
from os import chdir
from os import getcwd
from os import makedirs
from os import path
import markdown
from styles import get_string
class Build_HTML():
"""
Main class to build the file / folder tree. Currently creates files then folders. Both are in alphabetical order.
"""
def __init__(self, filepaths):
self.previous_filelist = []
self.html = ""
self.tree = {}
self.i = 0
self.position = 1
self.started = 0
self.closed = 0
self.filepaths = filepaths
self.build_html_front_page()
def build_html_front_page(self):
for filepath in self.filepaths:
filelist = filepath.split(path.sep)
self.i = 0
# Add folder or file
for entry in filelist:
if entry[-3:] == ".md":
self.add_file(entry, filepath)
else:
self.add_folder(entry)
self.i += 1
self.close_expansion(filelist)
self.position += 1
def close_expansion(self, filelist):
"""
Makes sure that you have the correct amount of </ul>.
:param filelist:
:return:
"""
filelist.pop(-1)
try:
next_path = self.filepaths[self.position].split(path.sep)[:-1]
except IndexError:
next_path = ""
if next_path != filelist and self.started > self.closed:
self.append_ul_breaks(filelist)
self.previous_filelist = filelist
self.closed += 1
def add_file(self, entry, filepath):
"""
Add files entry types.
:param entry:
:param filepath:
:return:
"""
try:
if entry not in self.tree[self.i]['file']:
self.tree[self.i]['file'].append(entry)
self.wrap_list_html(entry, filepath)
except KeyError:
self.tree[self.i] = {'file': [], 'folder': [],}
self.tree[self.i]['file'].append(entry)
self.wrap_list_html(entry, filepath)
def add_folder(self, entry):
"""
Add folder entry types.
:param entry:
:return:
"""
try:
if entry not in self.tree[self.i]['folder']:
self.tree[self.i]['folder'].append(entry)
self.wrap_list_html(entry)
self.html += self.add_tab() + "<ul>\n"
self.started += 1
except KeyError:
self.tree[self.i] = {'file': [], 'folder': [], }
self.tree[self.i]['folder'].append(entry)
self.wrap_list_html(entry)
self.html += self.add_tab() + "<ul>\n"
self.started += 1
def append_ul_breaks(self, filelist):
"""
Figure out if a </ul> need to be added.
:param filelist:
:return:
"""
increment = 2
for f, p in itertools.zip_longest(filelist, self.previous_filelist):
if f != p:
self.html += self.add_tab(increment) + "</ul>\n"
increment += 1
def wrap_list_html(self, entry, filepath=None):
"""
Main entry to add the correct html for a file or a folder.
:param entry:
:param filepath:
:return:
"""
if filepath is not None:
md5 = filename_md5(filepath)
self.html += self.add_tab() + '<li><a href="html/%s.html" target="_blank">%s</a></li>\n' % (md5, entry)
else:
self.html += self.add_tab() + '<li>%s</li>\n' % entry
def add_tab(self, increment=0):
"""
Add the correct amount of tabs to have proper line indents.
:param increment:
:return:
"""
return (self.i - increment) * "\t"
def read_mkd(filepath):
"""
Read the markdown files.
:param filepath:
:return:
"""
with open(filepath, 'r') as f:
markdown_data = f.read()
return markdown_data
def convert_mkd(markdown_data):
"""
Convert markdown files to html
:param markdown_data:
:return:
"""
html = markdown.markdown(markdown_data, ['markdown.extensions.extra', 'markdown.extensions.toc',
'codehilite', 'pymdownx.tasklist', 'pymdownx.progressbar',])
return html
def setup_html(html):
"""
Helper function to define the header / footer of the index.html file.
:param html:
:return:
"""
block_html = """<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
%s
</head>
<body>""" % html
return block_html
def write_html(html, filepath, buildpath):
"""
Write the html file to an md5 named file.
:param html:
:param filepath:
:return:
"""
md5_filename = filename_md5(filepath)
final_name = path.join(buildpath, "html", md5_filename + ".html")
with open(final_name, "w") as f:
f.write(html)
def file_rename(filename):
"""
Strip file and '.md' extension from filename to more easily rebuild.
:param filename: str(), filename.
:return: str(), filename, no extension.
"""
stripped_filename = filename.split(path.sep)[-1].replace('.md', '')
return stripped_filename
def get_markdown_files():
"""
Parse and get all files that end in '.md' in the current path.
:return:
"""
# TODO: Make it so you can specify the starting location.
filenames = glob("**/*.md", recursive=True)
return filenames
def filename_md5(markdown_data):
"""
Convert the filepath to an md5 hash.
:param markdown_data:
:return:
"""
hash = hashlib.new('md5', markdown_data.encode('utf-8'))
return hash.hexdigest()
def write_index(html, buildpath):
"""
Write the index.html file to the main folder.
:param html:
:return:
"""
# TODO: make sure the file is written to the correct folder.
with open(path.join(buildpath, 'index.html'), 'w') as f:
f.write(html)
def decompress_styles(buildpath):
"""
Decompress the stylesheet.
:return:
"""
data = get_string()
with open(path.join(buildpath, 'html', 'styles.css'), "w") as f:
f.write(data.decode('utf-8'))
def init_folder(buildpath):
"""
Helper functions to make certain supporting folders and files are present.
:return:
"""
try:
makedirs(path.join(buildpath, "html"))
except OSError:
pass
decompress_styles(buildpath)
def init_argparse():
parser = argparse.ArgumentParser(description='Convert Markdown files to HTML.')
parser.add_argument(
"-t", '--target',
help="Starting point to look for markdown files.",
# nargs="?",
# nargs=1,
default="", # Should be current folder. Also might need to be
metavar="PATH",
)
parser.add_argument(
'-b', '--build',
help="Location were index.html and the html folder will be dropped.",
# nargs=1,
metavar="PATH",
default="",
)
# TODO: Might need some basic path checking?
args = parser.parse_args()
return args
def change_dir(target):
if target != "":
chdir(args.target)
if __name__ == '__main__':
args = init_argparse()
current_path = getcwd()
change_dir(args.target)
filepaths = get_markdown_files()
build_html = Build_HTML(filepaths)
index_html = setup_html(build_html.html)
html_memory = {}
for filepath in filepaths:
filename = file_rename(filepath)
markdown_data = read_mkd(filepath)
html = convert_mkd(markdown_data)
block_html = setup_html(html)
html_memory[filepath] = block_html
# Write operations need to be done after folder change.
chdir(current_path)
init_folder(args.build)
write_index(index_html, args.build)
for filepath, block_html in html_memory.items():
write_html(block_html, filepath, args.build)