-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathgen-index.py
executable file
·121 lines (96 loc) · 2.78 KB
/
gen-index.py
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
#! /usr/bin/env python3
import os
import re
import string
assert __name__ == '__main__'
class Node(object):
kTagNameRE = re.compile('<([^ >]+)')
def __init__(self, before, close_tags=True):
self.before = before
self.after = ''
if close_tags:
match = self.kTagNameRE.match(before)
if match:
self.after = '</{}>'.format(match.group(1))
self.sub = []
return
def add_node(self, child):
self.sub.append(child)
return child
def add(self, before, close_tags=True):
return self.add_node(Node(before, close_tags))
def to_lines(self, indent=0):
sub_indent = indent
if self.before:
sub_indent += 1
sub_lines = []
for x in self.sub:
sub_lines += x.to_lines(sub_indent)
if not self.before:
return sub_lines
ret = [' '*4*indent + self.before]
if len(sub_lines) <= 1:
if sub_lines:
ret[0] += sub_lines[0].lstrip()
ret[0] += self.after
else:
ret += sub_lines
if self.after:
ret.append(' '*4*indent + self.after)
return ret
body = Node('')
src_url = 'https://github.com/jdashg/misc/blob/master/gen-index.py'
body.add("<h1><a href='{}'>Gen-Index:</a>".format(src_url))
dir_list = body.add('<ul>')
def should_add_to_index(name):
try:
(name, ext) = name.rsplit('.', 1)
except ValueError:
return False
return ext in ('html', 'md', 'txt')
for (cur, dirs, files) in os.walk('./'):
dirs[:] = sorted(filter(lambda x: x[0] != '.', dirs))
files = sorted(filter(lambda x: x[0] != '.', files))
htmls = filter(should_add_to_index, files)
htmls = list(htmls)
if not htmls:
continue
clean_path = cur[len('./'):].replace(os.sep, '/')
dir_item = dir_list.add('<li><h3>{}/</h3>'.format(clean_path), False)
file_list = dir_item.add('<ul>')
for x in htmls:
file_item = file_list.add('<li>', False)
url = x
if clean_path:
url = clean_path + '/' + url
print(url)
try:
(name, ext) = url.rsplit('.', 1)
if ext == 'md':
url = '{}.html'.format(name)
except ValueError:
pass
file_item.add("<a href='{}'>{}".format(url, x))
index_template = string.Template('''<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<title>Gen-Index</title>
</head>
<body>
<style>
body {
font-family: sans-serif;
}
ul {
margin-top: 4px;
}
</style>
$body
</body>
</html>
''')
body_text = '\n'.join(body.to_lines(2))
text = index_template.substitute(body=body_text)
with open('index.html', 'wb') as f:
f.write(text.encode())