-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgenerate-toc.py
55 lines (44 loc) · 1.7 KB
/
generate-toc.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
#!/usr/bin/env python3
import os
import re
import argparse
import sys
def main():
parser = argparse.ArgumentParser()
parser.add_argument('-f', '--file',
required=True,
type=str,
action='store',
metavar='PATH',
help="Path to the markdown file"
)
parser.add_argument('-d', '--depth',
default=2,
type=int,
action='store',
metavar='DEPTH',
help="Up to which heading depth the TOC should be created: 0 = #, 1 = ##...")
parser.add_argument('-l', '--link',
default='',
type=str,
action='store',
metavar='PATH',
help="Link to an external file")
args = parser.parse_args()
if not os.path.isfile(args.file) or not args.file.lower().endswith('.md'):
sys.exit("File could not be found or the file type is incorrect!")
toc = []
with open(args.file) as file:
for line in file:
if line.startswith('#'):
depth = line.count('#') - 1
if depth < args.depth:
f_line = re.sub('[^.a-z\d\s-]', '', line.lower())
f_line = f_line.strip().replace(' ', '-')
f_line = re.sub('-+', '-', f_line)
link = '{}- [{}]({}#{})'.format(' ' * depth, line.replace('#', '').strip(), args.link, f_line)
toc.append(link)
for link in toc:
print(link)
if __name__ == '__main__':
main()