feat: remove subdirs from internal links in output
This commit is contained in:
parent
f8275399df
commit
732398ff65
1 changed files with 23 additions and 24 deletions
|
@ -3,21 +3,29 @@ import re
|
||||||
|
|
||||||
from termcolor import colored
|
from termcolor import colored
|
||||||
|
|
||||||
image_rgx = r"!\[.*?\]\((.*?)\)"
|
|
||||||
|
|
||||||
|
def process_line(line):
|
||||||
def process_image_links(line, links):
|
image_rgx = r"!\[.*?\]\((.*?)\)"
|
||||||
try:
|
internal_link_rgx = r"\[.*?\]\((.*?)\)"
|
||||||
for link in links:
|
img_links = re.findall(image_rgx, line)
|
||||||
stripped_img_ref = re.search(r"[^/\\]+$", link)
|
internal_links = re.findall(internal_link_rgx, line)
|
||||||
if stripped_img_ref:
|
|
||||||
stripped_img_ref = stripped_img_ref.group()
|
if img_links:
|
||||||
new_img_ref = f"static/{stripped_img_ref}"
|
for img_link in img_links:
|
||||||
line = line.replace(f"({link})", f"({new_img_ref})")
|
stripped_img_ref = re.search(r"[^/\\]+$", img_link)
|
||||||
# print(colored(f" {links}", "green"))
|
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
|
return line
|
||||||
except Exception as e:
|
|
||||||
print(colored(f"ERROR Error when transforming link: {str(e)}", "light_red"))
|
|
||||||
|
|
||||||
|
|
||||||
def transform_links(target_dir):
|
def transform_links(target_dir):
|
||||||
|
@ -28,19 +36,10 @@ def transform_links(target_dir):
|
||||||
with open(file_path, "r") as f:
|
with open(file_path, "r") as f:
|
||||||
lines = f.readlines()
|
lines = f.readlines()
|
||||||
|
|
||||||
modified = False
|
|
||||||
new_lines = []
|
new_lines = []
|
||||||
for line in lines:
|
for line in lines:
|
||||||
img_links = re.findall(image_rgx, line)
|
new_lines.append(process_line(line))
|
||||||
if img_links:
|
if len(new_lines):
|
||||||
|
|
||||||
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:
|
with open(file_path, "w") as f:
|
||||||
f.writelines(new_lines)
|
f.writelines(new_lines)
|
||||||
print(
|
print(
|
||||||
|
|
Loading…
Add table
Reference in a new issue