1use regex::{Captures, Regex};
10
11pub fn to_site_page(markdown: &str, page_dir: &str) -> String {
17 let (title, body) = lift_title(markdown);
18 let body = rewrite_links(&body, page_dir);
19 let mut out = format!("---\ntitle: {}\n---\n", yaml_string(&title));
20 out.push_str(body.trim_start_matches('\n'));
21 out
22}
23
24fn lift_title(source: &str) -> (String, String) {
26 let mut lines: Vec<&str> = source.split('\n').collect();
27 for i in 0..lines.len() {
28 if let Some(rest) = lines[i].strip_prefix("# ") {
29 let title = rest.trim().to_string();
30 lines.remove(i);
31 return (title, lines.join("\n"));
32 }
33 if !lines[i].trim().is_empty() {
34 break;
35 }
36 }
37 panic!("generated page has no leading `# H1` to lift into the title");
38}
39
40fn rewrite_links(body: &str, page_dir: &str) -> String {
45 let re = Regex::new(r"\]\(([^)]+)\)").unwrap();
46 re.replace_all(body, |caps: &Captures| {
47 let target = &caps[1];
48 if target.starts_with("http://")
49 || target.starts_with("https://")
50 || target.starts_with("mailto:")
51 || target.starts_with('#')
52 || target.starts_with('/')
53 {
54 return format!("]({target})");
55 }
56 let (path_part, anchor) = match target.split_once('#') {
57 Some((p, a)) => (p, Some(a)),
58 None => (target, None),
59 };
60 if !path_part.ends_with(".md") {
61 return format!("]({target})");
62 }
63 let joined = normalize(&format!("{page_dir}/{path_part}"));
64 if joined.starts_with("..") {
65 return format!("]({target})"); }
67 let mut slug = joined.strip_suffix(".md").unwrap().to_string();
68 if let Some(prefix) = slug.strip_suffix("/index") {
69 slug = prefix.to_string();
70 } else if slug == "index" {
71 slug.clear();
72 }
73 let hash = anchor.map(|a| format!("#{a}")).unwrap_or_default();
74 if slug == "reference" || slug.starts_with("reference/") {
75 format!("](/{slug}/{hash})")
76 } else if slug == "spec" || slug.starts_with("spec/") {
77 format!("](/reference/{slug}/{hash})")
80 } else {
81 format!("](/book/{slug}/{hash})")
82 }
83 })
84 .into_owned()
85}
86
87fn normalize(path: &str) -> String {
89 let mut stack: Vec<&str> = Vec::new();
90 for comp in path.split('/') {
91 match comp {
92 "" | "." => {}
93 ".." => {
94 if matches!(stack.last(), Some(&c) if c != "..") {
95 stack.pop();
96 } else {
97 stack.push("..");
98 }
99 }
100 c => stack.push(c),
101 }
102 }
103 stack.join("/")
104}
105
106fn yaml_string(value: &str) -> String {
109 let bare = Regex::new(r"^[A-Za-z][A-Za-z0-9_ ,.'’!?()&/-]*$").unwrap();
110 let colon_space = Regex::new(r":\s").unwrap();
111 if bare.is_match(value) && !colon_space.is_match(value) {
112 value.to_string()
113 } else {
114 format!("\"{}\"", value.replace('\\', "\\\\").replace('"', "\\\""))
115 }
116}
117
118#[cfg(test)]
119mod tests {
120 use super::rewrite_links;
121
122 #[test]
123 fn a_link_into_the_reference_is_a_reference_route() {
124 assert_eq!(
125 rewrite_links("[grammar](grammar.md#rule-x)", "reference"),
126 "[grammar](/reference/grammar/#rule-x)"
127 );
128 assert_eq!(
129 rewrite_links("[index](index.md)", "reference"),
130 "[index](/reference/)"
131 );
132 }
133
134 #[test]
135 fn a_link_out_of_the_reference_stays_a_book_route() {
136 assert_eq!(
137 rewrite_links("[guide](../guides/agents/index.md)", "reference"),
138 "[guide](/book/guides/agents/)"
139 );
140 assert_eq!(
141 rewrite_links("[spec](../spec/static-semantics.md#5)", "reference"),
142 "[spec](/reference/spec/static-semantics/#5)"
143 );
144 assert_eq!(
145 rewrite_links("[root](/reference/types/)", "reference"),
146 "[root](/reference/types/)"
147 );
148 }
149}