-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathupdateToc.py
executable file
·78 lines (67 loc) · 2.23 KB
/
updateToc.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
#!/usr/bin/python3
import sys, os, subprocess
from functools import reduce
# Simple script to update toc in README.md
# Example usage: ./updateToc.py README.md 3
# This will overwrite your README.md file.
# Use at your caution!
# *SUFFERS* Python version 3.4.3.......... Cannot upgrade it.
# TODO #1: Improve usage with
# file = sys.argv[1]
# as it is repetitive
# TODO #2: automatically detect where to input toc
# (remove targetLineNum variable)
def pipe(*fns):
def sub(data):
for fn in fns:
data = fn(data)
return data
return sub
def raiseExceptionOnErrors():
msg = "update.py takes 2 arguments: \n1. The name of a target file as the only argument. \n2. The line number to start pasting toc from (if you already have toc, you should input the number of the first line of the toc)\nFor example, ./updateToc.py README.md 3"
if len(sys.argv) != 3:
raise TypeError(msg)
return 1
def getToc(file):
toc = subprocess.Popen(['./gh-md-toc', file],
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
stdout,stderr = toc.communicate()
if stderr:
raise Exception(str(stderr, 'utf-8'))
return str(stdout, 'utf-8')
def addToc(toc):
file = sys.argv[1]
old = open(file,'r')
lines = old.readlines()
targetLineNum = int(sys.argv[2])
new = ''
def isEndOfPrevTocReached(line):
endOfPrevTocStr = 'Created by [gh-md-toc](https://github.com/ekalinin/github-markdown-toc)'
return endOfPrevTocStr in line
reached = False
for counter, line in enumerate(lines):
# insert toc
if targetLineNum == counter:
new = new + toc
elif counter < targetLineNum or reached:
new = new + line
elif isEndOfPrevTocReached(line):
# do not copy the previous toc
# just do nothing
reached = True
return new
def saveToFile(txt):
file = sys.argv[1]
with open(file, 'w') as filehandle:
filehandle.write(txt)
return 1
if __name__ == "__main__":
file = sys.argv[1]
main = pipe(
getToc,
addToc,
saveToFile
)
raiseExceptionOnErrors()
main(file)