neuron-zk-generator/src/lib/transform_links.py

52 lines
1.5 KiB
Python
Raw Normal View History

2024-10-19 13:03:04 +01:00
import os
import re
2024-11-11 15:49:01 +00:00
2024-10-19 13:03:04 +01:00
from termcolor import colored
image_rgx = r"!\[.*?\]\((.*?)\)"
def process_image_links(line, links):
try:
for link in links:
stripped_img_ref = re.search(r"[^/\\]+$", link)
if stripped_img_ref:
stripped_img_ref = stripped_img_ref.group()
2024-11-11 15:49:01 +00:00
new_img_ref = f"static/{stripped_img_ref}"
2024-10-19 13:03:04 +01:00
line = line.replace(f"({link})", f"({new_img_ref})")
# print(colored(f"  {links}", "green"))
return line
except Exception as e:
2024-11-11 15:49:01 +00:00
print(colored(f"ERROR Error when transforming link: {str(e)}", "light_red"))
2024-10-19 13:03:04 +01:00
def transform_links(target_dir):
2024-11-11 15:49:01 +00:00
print(colored("INFO: Updating links...", "light_blue"))
2024-10-19 13:03:04 +01:00
for filename in os.listdir(target_dir):
if filename.endswith(".md"):
file_path = os.path.join(target_dir, filename)
with open(file_path, "r") as f:
lines = f.readlines()
modified = False
new_lines = []
for line in lines:
img_links = re.findall(image_rgx, line)
if img_links:
new_line = process_image_links(line, img_links)
new_lines.append(new_line)
modified = True
else:
new_lines.append(line)
if modified:
with open(file_path, "w") as f:
f.writelines(new_lines)
print(
colored(
2024-11-11 15:49:01 +00:00
"SUCCESS Links updated",
"light_green",
2024-10-19 13:03:04 +01:00
)
)