Skip to content

Commit e408272

Browse files
authored
[Docs] Enable relative links in examples to function when rendered in the docs (vllm-project#24041)
Signed-off-by: Harry Mellor <[email protected]>
1 parent 4377b1a commit e408272

File tree

1 file changed

+36
-7
lines changed

1 file changed

+36
-7
lines changed

docs/mkdocs/hooks/generate_examples.py

Lines changed: 36 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -114,21 +114,50 @@ def determine_title(self) -> str:
114114
return match.group('title')
115115
return fix_case(self.path.stem.replace("_", " ").title())
116116

117+
def fix_relative_links(self, content: str) -> str:
118+
"""
119+
Fix relative links in markdown content by converting them to gh-file
120+
format.
121+
122+
Args:
123+
content (str): The markdown content to process
124+
125+
Returns:
126+
str: Content with relative links converted to gh-file format
127+
"""
128+
# Regex to match markdown links [text](relative_path)
129+
# This matches links that don't start with http, https, ftp, or #
130+
link_pattern = r'\[([^\]]*)\]\((?!(?:https?|ftp)://|#)([^)]+)\)'
131+
132+
def replace_link(match):
133+
link_text = match.group(1)
134+
relative_path = match.group(2)
135+
136+
# Make relative to repo root
137+
gh_file = (self.main_file.parent / relative_path).resolve()
138+
gh_file = gh_file.relative_to(ROOT_DIR)
139+
140+
return f'[{link_text}](gh-file:{gh_file})'
141+
142+
return re.sub(link_pattern, replace_link, content)
143+
117144
def generate(self) -> str:
118145
content = f"# {self.title}\n\n"
119146
content += f"Source <gh-file:{self.path.relative_to(ROOT_DIR)}>.\n\n"
120147

121148
# Use long code fence to avoid issues with
122149
# included files containing code fences too
123150
code_fence = "``````"
124-
# Skip the title from md snippets as it's been included above
125-
start_line = 2
126-
if self.is_code:
127-
content += f"{code_fence}{self.main_file.suffix[1:]}\n"
128-
start_line = 1
129-
content += f'--8<-- "{self.main_file}:{start_line}"\n'
151+
130152
if self.is_code:
131-
content += f"{code_fence}\n"
153+
content += (f"{code_fence}{self.main_file.suffix[1:]}\n"
154+
f'--8<-- "{self.main_file}"\n'
155+
f"{code_fence}\n")
156+
else:
157+
with open(self.main_file) as f:
158+
# Skip the title from md snippets as it's been included above
159+
main_content = f.readlines()[1:]
160+
content += self.fix_relative_links("".join(main_content))
132161
content += "\n"
133162

134163
if not self.other_files:

0 commit comments

Comments
 (0)