Skip to main content

xtask/
site_page.rs

1//! Shared test helper: turn a generated mdBook-format reference page into the
2//! Starlight page committed under `site/src/content/docs/`. This is the
3//! same transform `site/scripts/migrate-page.mjs` applied during the Book
4//! migration — lift the leading `# H1` into `title:` frontmatter (dropping the
5//! heading), and rewrite relative `.md` links to site routes — so the
6//! generated-page drift guards keep their committed site pages byte-identical to
7//! the migrated originals once `docs/` is gone.
8
9use regex::{Captures, Regex};
10
11/// Transform `markdown` (a generated reference page, mdBook form) into its
12/// committed Starlight form. `page_dir` is the page's directory, as the Book's
13/// mdBook sources lay it out (e.g. `"reference"`), used to resolve relative
14/// links. A link that resolves into `reference/` is a Reference route (web
15/// presence slice 5); any other, a Book route.
16pub 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
24/// Split off the first `# H1` as the title; the rest (heading removed) is the body.
25fn 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
40/// Rewrite relative `*.md` links to site routes, resolving each against
41/// `page_dir`: `/reference/<slug>/` under `reference/`, `/reference/spec/<slug>/`
42/// under `spec/` (the specification's mdBook home), else `/book/<slug>/`.
43/// External / in-page / already-rooted links are untouched.
44fn 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})"); // outside the Book tree — leave as-is
66        }
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            // The specification was the Book's `spec/` in the mdBook layout and
78            // lives under the Reference since slice 5.
79            format!("](/reference/{slug}/{hash})")
80        } else {
81            format!("](/book/{slug}/{hash})")
82        }
83    })
84    .into_owned()
85}
86
87/// Collapse `.` and `..` components in a `/`-separated relative path.
88fn 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
106/// Quote a frontmatter title only when YAML could misread the bare scalar —
107/// matching `migrate-page.mjs`'s rule so titles render identically.
108fn 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}