-
Notifications
You must be signed in to change notification settings - Fork 105
/
Copy pathgithub-toc-maker-for-sphinx.py
75 lines (57 loc) · 2.16 KB
/
github-toc-maker-for-sphinx.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
import os
import re
import git
import linecache
from glob import glob
pwd = os.getcwd()
source_dir = os.path.join(pwd, "source")
def get_chapter_name(file):
return linecache.getline(file, 2).strip()
def get_title(file):
first_line = linecache.getline(file, 1)
if first_line.startswith("#"):
return first_line.replace("# ", "").strip()
def get_all_chapter():
all_chapters_path = []
os.chdir(source_dir)
for dir_name in glob("c*"):
if dir_name == "chapters" or dir_name == "conf.py":
continue
all_chapters_path.append(os.path.join(dir_name))
return all_chapters_path
def generate_mapping(all_chapters_path):
mapping = dict.fromkeys([os.path.basename(chapter_path) for chapter_path in all_chapters_path])
for key in mapping.keys():
chapter_file = os.path.join(pwd, "source", "chapters", key.replace("c", "p") + ".rst")
mapping[key] = get_chapter_name(chapter_file)
return mapping
def get_toc_info(all_chapters_path):
toc = {}
for dir_name in all_chapters_path:
chapter_toc = {}
os.chdir(os.path.join(source_dir, dir_name))
for file_name in sorted(glob(dir_name + "*.md")):
section = int(re.findall(r"c\d{2}_(\d{2}).md", file_name)[0])
md_path = os.path.join("https://pycharm.iswbm.com/", dir_name, file_name.replace("md", "html"))
title = get_title(file_name)
if not title:
continue
chapter_toc[section] = (title, md_path)
toc[dir_name] = chapter_toc
return toc
def print_md_toc(toc_info, mapping):
for chapter in sorted(toc_info.items(), key=lambda item: item[0]):
posts = chapter[1]
chapter_name = mapping[chapter[0]]
print(f"- **{chapter_name}**")
for post in sorted(posts.items(), key=lambda item:item[0]):
# print title only
# print(f"{post[1][0]}")
print(" ", f"* [{post[1][0]}]({post[1][1]})")
def main():
all_chapter = get_all_chapter()
mapping = generate_mapping(all_chapter)
toc_info = get_toc_info(all_chapter)
print_md_toc(toc_info, mapping)
if __name__ == '__main__':
main()