-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathinject_toc.py
More file actions
40 lines (31 loc) · 1.38 KB
/
Copy pathinject_toc.py
File metadata and controls
40 lines (31 loc) · 1.38 KB
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
import os
import glob
import re
astro_files = glob.glob('src/pages/*.astro')
for fpath in astro_files:
if os.path.basename(fpath) in ['index.astro', '404.astro', 'sitemap.astro', 'sitemap-page.astro']:
continue
with open(fpath, 'r') as f:
content = f.read()
if '<TableOfContents' in content:
continue
if '<main' not in content:
continue
# Add import if missing
if 'import TableOfContents' not in content:
content = re.sub(r"(---.*?)\n(---)", r"\1\nimport TableOfContents from '../components/TableOfContents.astro';\n\2", content, count=1, flags=re.DOTALL)
# We want to insert <TableOfContents /> after the first </h1> or <p class="subtitle"...>
# Finding the end of the subtitle or h1
h1_match = re.search(r'</h1>', content)
subtitle_match = re.search(r'</p>', content[h1_match.end():] if h1_match else "")
insert_pos = -1
if h1_match:
if subtitle_match and 'class="subtitle"' in content[h1_match.end():h1_match.end()+subtitle_match.end()]:
insert_pos = h1_match.end() + subtitle_match.end()
else:
insert_pos = h1_match.end()
if insert_pos != -1:
content = content[:insert_pos] + "\n\n <TableOfContents />\n" + content[insert_pos:]
with open(fpath, 'w') as f:
f.write(content)
print(f"Updated {fpath}")