-
Notifications
You must be signed in to change notification settings - Fork 4
/
create_book.py
executable file
·62 lines (45 loc) · 1.6 KB
/
create_book.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
#!/usr/bin/env python3
import sys
import re
import os
import shutil
def break_file(filepath):
print(f"Processing file {filepath}")
with open(filepath, 'r') as f:
contents = f.read()
filename = os.path.basename(filepath).split(".")[0]
new_dir = filename
try:
shutil.rmtree(new_dir)
except:
pass
os.mkdir(new_dir)
marker = 0
titles = [filename]
header_map = []
for idx, match in enumerate(re.finditer("^#\s(.*?)($|\{)", contents, flags=re.M)):
[start, end] = match.span()
header_title = match.group(1)
titles.append(header_title)
new_file = f"{new_dir}/{filename}-{idx}.md"
with open(new_file, "w") as f:
f.write(contents[marker:start])
marker = start
header_map.append((new_file, titles[idx]))
new_file = f"{new_dir}/{filename}-{len(titles)-1}.md"
with open(new_file, "w") as f:
f.write(contents[marker:])
header_map.append((new_file, titles[-1]))
print(header_map)
return header_map
if __name__ == '__main__':
input_files = sys.argv[1:]
maps = map(lambda x: (x, break_file(x)), input_files)
with open("SUMMARY.md", "w") as f:
f.writelines(["# Table of contents\n", "* [Introduction](README.md)\n"])
for input_file, header_map in maps:
dirname = os.path.basename(input_file).split(".")[0]
f.write(f"* [{header_map[0][1]}]({header_map[0][0]})\n")
if len(header_map) > 1:
f.writelines(map(lambda x: f"\t* [{x[1]}]({x[0]})\n", header_map[1:]))
os.remove(input_file)