From 732398ff65bb84294b68ba33133c52f2c215b81f Mon Sep 17 00:00:00 2001 From: thomasabishop Date: Thu, 16 Jan 2025 07:05:31 +0000 Subject: [PATCH] feat: remove subdirs from internal links in output --- src/lib/transform_links.py | 47 +++++++++++++++++++------------------- 1 file changed, 23 insertions(+), 24 deletions(-) diff --git a/src/lib/transform_links.py b/src/lib/transform_links.py index d94cef5..cf0a044 100644 --- a/src/lib/transform_links.py +++ b/src/lib/transform_links.py @@ -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(