feat: remove subdirs from internal links in output

This commit is contained in:
thomasabishop 2025-01-16 07:05:31 +00:00
parent f8275399df
commit 732398ff65

View file

@ -3,21 +3,29 @@ import re
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()
new_img_ref = f"static/{stripped_img_ref}"
line = line.replace(f"({link})", f"({new_img_ref})")
# print(colored(f"  {links}", "green"))
def process_line(line):
image_rgx = r"!\[.*?\]\((.*?)\)"
internal_link_rgx = r"\[.*?\]\((.*?)\)"
img_links = re.findall(image_rgx, line)
internal_links = re.findall(internal_link_rgx, line)
if img_links:
for img_link in img_links:
stripped_img_ref = re.search(r"[^/\\]+$", img_link)
if stripped_img_ref:
stripped_img_ref = stripped_img_ref.group()
new_img_ref = f"static/{stripped_img_ref}"
line = line.replace(f"({img_link})", f"({new_img_ref})")
if internal_links:
for internal_link in internal_links:
if internal_link.endswith('.md') and ('/' in internal_link):
stripped_path = (re.search(r"[^/\\]+$", internal_link))
if stripped_path:
stripped_path = stripped_path.group()
line = line.replace(f"({internal_link})", f"({stripped_path})")
return line
except Exception as e:
print(colored(f"ERROR Error when transforming link: {str(e)}", "light_red"))
def transform_links(target_dir):
@ -28,19 +36,10 @@ def transform_links(target_dir):
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:
new_lines.append(process_line(line))
if len(new_lines):
with open(file_path, "w") as f:
f.writelines(new_lines)
print(