-
Notifications
You must be signed in to change notification settings - Fork 23
/
fix-relative.py
executable file
·35 lines (28 loc) · 1.31 KB
/
fix-relative.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
import os
rootdir = '/workspaces/the-programmers-field-guide/book'
for subdir, dirs, files in os.walk(rootdir):
for file in files:
if file.endswith(".md") or file.endswith(".mdx"):
fname = os.path.join(subdir, file)
print(f"Processing {fname}")
bookPath = subdir.removeprefix("/workspaces/the-programmers-field-guide/book").split('/')
depth = len(bookPath)
maxDepth = depth
# Opening the file in read and write mode
with open(fname,'r+') as f:
# Reading the file into content
content = f.read()
# Determine replacements
while depth > 0:
search = f"]({'../' * depth}"
depth -= 1
replacement = f"](/book{'/'.join(bookPath[:(maxDepth - depth)])}/"
print(f" - searching for {search} -> {replacement}")
# Replacing search text
content = content.replace(search, replacement)
# Move to the start of the file
f.seek(0)
# Replace file content
f.write(content)
# Truncating the file size
f.truncate()