-
Notifications
You must be signed in to change notification settings - Fork 52
/
toc_fix.py
59 lines (46 loc) · 1.98 KB
/
toc_fix.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
# toc_fix.py
# Searches through directory tree for Restructured Text formatted table of contents (toc) and copy file while appending a language suffix to the filename.
# Replace references to TWP##_#.rst to TWP##_#_en.rst
import sys
import os
import re
import shutil
def rename_TOC_items(filename, lang="en"):
with open(filename, "r") as inp:
content = inp.read()
# Handle TOC item updates
actRegex = re.compile(r'\b(TWP\d{1,2}_\d{1,2}\.rst)\b')
for entry in actRegex.findall(content):
fname, ext = entry.split('.')
fname_lang = f'{fname}_{lang}.{ext}'
content = content.replace(entry, fname_lang)
with open(filename, "w") as outp:
outp.write(content)
inp.close()
outp.close()
def walk_files():
for root, dir,files in os.walk('_sources/lectures'):
for directory in dir:
for filename in os.listdir(os.path.join(root, directory)):
if filename == 'toctree.rst':
sfile = 'toctree.rst'
dfile = 'toctree_en.rst'
source_path = os.path.join(root, directory, sfile)
destination_path = os.path.join(root, directory, dfile)
# check if destination file already exist
if os.path.isfile(destination_path) == True:
print(f'{destination_path} already exist, skipping.')
else:
print(f'{destination_path} does not yet exist, creating.')
#open language toctree and update rst items to include the lang suffix
shutil.copy(source_path, destination_path)
rename_TOC_items(destination_path)
if __name__ == "__main__":
if '--all' in sys.argv:
walk_files()
elif (len(sys.argv) != 2):
print(f"usage: {sys.argv[0]} <filename> or --all")
exit()
else:
filename = sys.argv[1]
rename_TOC_items(filename)