Skip to main content

euv_docs/parser/
fn.rs

1use super::*;
2
3/// Parses a single Markdown document with optional YAML frontmatter into a `DocPage`.
4///
5/// # Arguments
6///
7/// - `&str` - Canonical route path for this page.
8/// - `&str` - Section label derived from directory hierarchy.
9/// - `&str` - Raw Markdown source text.
10///
11/// # Returns
12///
13/// - `DocPage` - Parsed structured documentation page.
14#[must_use]
15pub fn parse_markdown_page(route: &str, default_section: &str, raw: &str) -> DocPage {
16    let (frontmatter, body): (DocFrontmatter, &str) = split_frontmatter(raw);
17    let mut blocks: Vec<DocBlock> = Vec::new();
18    let mut toc: Vec<DocTocItem> = Vec::new();
19    let mut seen_slugs: BTreeMap<String, usize> = BTreeMap::new();
20    let mut active_heading: Option<(u8, Option<String>)> = None;
21    let mut first_h1_title: Option<String> = None;
22    let mut in_paragraph: bool = false;
23    let mut list_stack: Vec<String> = Vec::new();
24    let mut blockquote_depth: usize = 0;
25    let mut in_table: bool = false;
26    let mut in_table_head: bool = false;
27    let mut in_table_cell: bool = false;
28    let mut table_headers: Vec<String> = Vec::new();
29    let mut table_rows: Vec<Vec<String>> = Vec::new();
30    let mut current_row: Vec<String> = Vec::new();
31    let mut active_code_lang: Option<String> = None;
32    let mut active_image_src: Option<String> = None;
33    let mut image_alt_buf: String = String::new();
34    let mut buffer: String = String::new();
35    let parser: Parser<'_> = Parser::new_ext(body, Options::all());
36    for event in parser {
37        match event {
38            Event::Start(Tag::Heading { level, id, .. }) => {
39                active_heading = Some((heading_level_num(level), id.map(CowStr::into_string)));
40                buffer.clear();
41            }
42            Event::End(TagEnd::Heading(_)) => {
43                if let Some((level, custom_id)) = active_heading.take() {
44                    let text: String = buffer.trim().to_string();
45                    if !text.is_empty() {
46                        if level == 1 && first_h1_title.is_none() {
47                            first_h1_title = Some(text.clone());
48                        }
49                        let raw_slug: String = custom_id
50                            .map(|id_str: String| slugify(&id_str))
51                            .filter(|s: &String| !s.is_empty())
52                            .unwrap_or_else(|| slugify(&text));
53                        let slug: String = deduplicate_slug(raw_slug, &mut seen_slugs);
54                        if (2..=4).contains(&level) {
55                            toc.push(DocTocItem::new(level, slug.clone(), text.clone()));
56                        }
57                        blocks.push(DocBlock::Heading { level, slug, text });
58                    }
59                }
60                buffer.clear();
61            }
62            Event::Start(Tag::BlockQuote(_)) => {
63                blockquote_depth += 1;
64            }
65            Event::End(TagEnd::BlockQuote(_)) => {
66                blockquote_depth = blockquote_depth.saturating_sub(1);
67            }
68            Event::Start(Tag::Table(_)) => {
69                in_table = true;
70                table_headers.clear();
71                table_rows.clear();
72            }
73            Event::End(TagEnd::Table) => {
74                if in_table {
75                    in_table = false;
76                    let headers: Vec<String> = take(&mut table_headers);
77                    let rows: Vec<Vec<String>> = take(&mut table_rows);
78                    if !headers.is_empty() || !rows.is_empty() {
79                        blocks.push(DocBlock::Table { headers, rows });
80                    }
81                }
82            }
83            Event::Start(Tag::TableHead) => {
84                in_table_head = true;
85                current_row.clear();
86            }
87            Event::End(TagEnd::TableHead) => {
88                in_table_head = false;
89                table_headers = take(&mut current_row);
90            }
91            Event::Start(Tag::TableRow) => {
92                current_row.clear();
93            }
94            Event::End(TagEnd::TableRow) => {
95                if !in_table_head {
96                    table_rows.push(take(&mut current_row));
97                }
98            }
99            Event::Start(Tag::TableCell) => {
100                in_table_cell = true;
101                buffer.clear();
102            }
103            Event::End(TagEnd::TableCell) => {
104                if in_table_cell {
105                    in_table_cell = false;
106                    current_row.push(buffer.trim().to_string());
107                }
108                buffer.clear();
109            }
110            Event::Start(Tag::Paragraph) => {
111                if list_stack.is_empty() {
112                    in_paragraph = true;
113                    buffer.clear();
114                }
115            }
116            Event::End(TagEnd::Paragraph) => {
117                if in_paragraph {
118                    in_paragraph = false;
119                    let text: String = buffer.trim().to_string();
120                    if !text.is_empty() {
121                        if blockquote_depth > 0 {
122                            blocks.push(DocBlock::BlockQuote(text));
123                        } else {
124                            blocks.push(DocBlock::Paragraph(text));
125                        }
126                    }
127                    buffer.clear();
128                } else if let Some(top) = list_stack.last_mut()
129                    && !top.is_empty()
130                {
131                    top.push(' ');
132                }
133            }
134            Event::Start(Tag::Item) => {
135                if let Some(parent_text) = list_stack.last_mut() {
136                    let trimmed: String = parent_text.trim().to_string();
137                    if !trimmed.is_empty() {
138                        blocks.push(DocBlock::ListItem(trimmed));
139                        parent_text.clear();
140                    }
141                }
142                list_stack.push(String::new());
143            }
144            Event::End(TagEnd::Item) => {
145                if let Some(item_buf) = list_stack.pop() {
146                    let text: String = item_buf.trim().to_string();
147                    if !text.is_empty() {
148                        blocks.push(DocBlock::ListItem(text));
149                    }
150                }
151            }
152            Event::Start(Tag::CodeBlock(kind)) => {
153                let lang: String = match kind {
154                    CodeBlockKind::Fenced(tag) => {
155                        let trimmed: &str = tag.split_whitespace().next().unwrap_or("");
156                        if trimmed.is_empty() {
157                            DEFAULT_CODE_LANG.to_string()
158                        } else {
159                            trimmed.to_string()
160                        }
161                    }
162                    CodeBlockKind::Indented => DEFAULT_CODE_LANG.to_string(),
163                };
164                active_code_lang = Some(lang);
165                buffer.clear();
166            }
167            Event::End(TagEnd::CodeBlock) => {
168                if let Some(language) = active_code_lang.take() {
169                    let code: String = buffer.trim_end().to_string();
170                    blocks.push(DocBlock::Code { language, code });
171                }
172                buffer.clear();
173            }
174            Event::Start(Tag::Image { dest_url, .. }) => {
175                active_image_src = Some(dest_url.into_string());
176                image_alt_buf.clear();
177            }
178            Event::End(TagEnd::Image) => {
179                if let Some(src) = active_image_src.take() {
180                    let alt: String = take(&mut image_alt_buf).trim().to_string();
181                    if !src.is_empty() {
182                        blocks.push(DocBlock::Image { alt, src });
183                    }
184                }
185            }
186            Event::TaskListMarker(checked) => {
187                let marker: &str = if checked { "[x] " } else { "[ ] " };
188                if let Some(top) = list_stack.last_mut() {
189                    top.push_str(marker);
190                } else {
191                    buffer.push_str(marker);
192                }
193            }
194            Event::Rule => {
195                blocks.push(DocBlock::HorizontalRule);
196            }
197            Event::Text(text) | Event::Code(text) => {
198                if active_image_src.is_some() {
199                    image_alt_buf.push_str(&text);
200                } else if !list_stack.is_empty()
201                    && active_code_lang.is_none()
202                    && active_heading.is_none()
203                    && !in_table_cell
204                {
205                    if let Some(top) = list_stack.last_mut() {
206                        top.push_str(&text);
207                    }
208                } else {
209                    buffer.push_str(&text);
210                }
211            }
212            Event::SoftBreak | Event::HardBreak => {
213                let sep: char = if active_code_lang.is_some() {
214                    '\n'
215                } else {
216                    ' '
217                };
218                if active_image_src.is_some() {
219                    image_alt_buf.push(sep);
220                } else if !list_stack.is_empty()
221                    && active_code_lang.is_none()
222                    && active_heading.is_none()
223                    && !in_table_cell
224                {
225                    if let Some(top) = list_stack.last_mut() {
226                        top.push(sep);
227                    }
228                } else {
229                    buffer.push(sep);
230                }
231            }
232            _ => {}
233        }
234    }
235    let DocFrontmatter {
236        title: fm_title,
237        order: fm_order,
238        tagline: fm_tagline,
239        section: fm_section,
240        ..
241    } = frontmatter;
242    let fallback_title: String = first_h1_title
243        .or_else(|| {
244            toc.first()
245                .map(|item: &DocTocItem| item.get_title().clone())
246        })
247        .unwrap_or_else(|| title_from_route(route));
248    let title: String = fm_title.unwrap_or(fallback_title);
249    if toc
250        .first()
251        .is_some_and(|item: &DocTocItem| item.get_title().trim().eq_ignore_ascii_case(title.trim()))
252    {
253        let _: DocTocItem = toc.remove(0);
254    }
255    let default_order: i32 = if route == ROUTE_ROOT { -1000 } else { 100 };
256    let order: i32 = fm_order.unwrap_or(default_order);
257    let section: String = fm_section.unwrap_or_else(|| default_section.to_string());
258    let summary: String = fm_tagline.unwrap_or_else(|| {
259        blocks
260            .iter()
261            .find_map(|b: &DocBlock| match b {
262                DocBlock::Paragraph(p) | DocBlock::BlockQuote(p) => Some(p.clone()),
263                _ => None,
264            })
265            .unwrap_or_default()
266    });
267    let mut page: DocPage = DocPage::new(
268        route.to_string(),
269        title,
270        order,
271        section,
272        summary,
273        blocks,
274        toc,
275    );
276    page.set_markdown_body(body.to_string());
277    page
278}
279
280/// Recursively loads all `.md` files under `root_dir` into a sorted `DocSite`.
281///
282/// # Arguments
283///
284/// - `&Path` - Root Markdown or project directory.
285///
286/// # Returns
287///
288/// - `io::Result<DocSite>` - Loaded documentation site or I/O error.
289pub fn load_doc_site(root_dir: &Path) -> io::Result<DocSite> {
290    load_doc_site_with_options(root_dir, None)
291}
292
293/// Recursively loads all `.md` files under `root_dir` with optional site title override and smart directory filtering.
294///
295/// # Arguments
296///
297/// - `&Path` - Root Markdown or project directory.
298/// - `Option<&str>` - Optional explicit site title overriding frontmatter and folder heuristics.
299///
300/// # Returns
301///
302/// - `io::Result<DocSite>` - Loaded documentation site or I/O error.
303pub fn load_doc_site_with_options(
304    root_dir: &Path,
305    title_override: Option<&str>,
306) -> io::Result<DocSite> {
307    load_doc_site_excluding(root_dir, title_override, None)
308}
309
310/// Recursively loads all `.md` files under `root_dir`, skipping `exclude_dir` when it sits inside `root_dir`.
311///
312/// # Arguments
313///
314/// - `&Path` - Root Markdown or project directory.
315/// - `Option<&str>` - Optional explicit site title override.
316/// - `Option<&Path>` - Optional output directory excluded from traversal.
317///
318/// # Returns
319///
320/// - `io::Result<DocSite>` - Loaded and section-ordered documentation site or I/O error.
321pub(crate) fn load_doc_site_excluding(
322    root_dir: &Path,
323    title_override: Option<&str>,
324    exclude_dir: Option<&Path>,
325) -> io::Result<DocSite> {
326    if !root_dir.exists() {
327        return Err(Error::new(
328            ErrorKind::NotFound,
329            root_dir.display().to_string(),
330        ));
331    }
332    let canonical_exclude: Option<PathBuf> =
333        exclude_dir.map(|p: &Path| fs::canonicalize(p).unwrap_or_else(|_| p.to_path_buf()));
334    let mut files: Vec<PathBuf> = Vec::new();
335    collect_markdown_files(root_dir, canonical_exclude.as_deref(), &mut files)?;
336    files.sort();
337    let mut pages: Vec<DocPage> = Vec::new();
338    let mut seen_routes: BTreeSet<String> = BTreeSet::new();
339    let mut detected_title: Option<String> = None;
340    let mut detected_tagline: Option<String> = None;
341    for file_path in files.into_iter() {
342        let raw: String = fs::read_to_string(&file_path)?;
343        let rel: &Path = file_path.strip_prefix(root_dir).unwrap_or(&file_path);
344        let (mut route, section): (String, String) = route_and_section_from_rel_path(rel);
345        if route == ROUTE_ROOT {
346            let (fm, _): (DocFrontmatter, &str) = split_frontmatter(&raw);
347            if let Some(site_cfg) = fm.site {
348                if detected_title.is_none() {
349                    detected_title = site_cfg.try_get_title().clone();
350                }
351                if detected_tagline.is_none() {
352                    detected_tagline = site_cfg.try_get_description().clone();
353                }
354            }
355        }
356        if seen_routes.contains(&route) {
357            let stem: String = file_path
358                .file_stem()
359                .map(|s: &OsStr| slugify(&s.to_string_lossy()))
360                .filter(|s: &String| !s.is_empty())
361                .unwrap_or_else(|| FALLBACK_SLUG_PREFIX.to_string());
362            let base_route: String = if route == ROUTE_ROOT {
363                format!("/{stem}")
364            } else {
365                format!("{route}-{stem}")
366            };
367            route = base_route.clone();
368            let mut suffix: usize = 2;
369            while seen_routes.contains(&route) {
370                route = format!("{base_route}-{suffix}");
371                suffix += 1;
372            }
373        }
374        let _: bool = seen_routes.insert(route.clone());
375        pages.push(parse_markdown_page(&route, &section, &raw));
376    }
377    pages.sort_by(|a: &DocPage, b: &DocPage| {
378        section_sort_rank(a.get_section())
379            .cmp(&section_sort_rank(b.get_section()))
380            .then_with(|| a.get_section().cmp(b.get_section()))
381            .then_with(|| a.get_order().cmp(&b.get_order()))
382            .then_with(|| a.get_route().cmp(b.get_route()))
383    });
384    let fallback_site_title: String = root_dir
385        .file_name()
386        .map(|s: &OsStr| s.to_string_lossy().into_owned())
387        .filter(|raw: &String| {
388            let low: String = raw.to_ascii_lowercase();
389            raw.len() > 2
390                && low != GENERIC_DOCS_DIR
391                && low != GENERIC_SRC_DIR
392                && raw != "."
393                && raw != ".."
394        })
395        .map(|raw: String| format_section_label(&raw))
396        .unwrap_or_else(|| DOCS_SITE_TITLE.to_string());
397    let site_title: String = title_override
398        .map(str::to_string)
399        .or(detected_title)
400        .unwrap_or(fallback_site_title);
401    let site_tagline: String = detected_tagline.unwrap_or_else(|| DOCS_SITE_TAGLINE.to_string());
402    Ok(DocSite::new(site_title, site_tagline, pages))
403}
404
405/// Returns the canonical sidebar and pagination ordering rank for a section label.
406///
407/// # Arguments
408///
409/// - `&str` - Section display label.
410///
411/// # Returns
412///
413/// - `u8` - Priority rank (`0` General, `1` Guide, `2` all other sections alphabetically).
414pub(crate) fn section_sort_rank(section: &str) -> u8 {
415    if section.eq_ignore_ascii_case(DEFAULT_SECTION) {
416        0
417    } else if section.eq_ignore_ascii_case(GUIDE_SECTION) {
418        1
419    } else {
420        2
421    }
422}
423
424/// Extracts optional YAML frontmatter delimited by `---` lines.
425///
426/// # Arguments
427///
428/// - `&str` - Full raw Markdown document.
429///
430/// # Returns
431///
432/// - `(DocFrontmatter, &str)` - Parsed frontmatter and remaining Markdown body slice.
433fn split_frontmatter(raw: &str) -> (DocFrontmatter, &str) {
434    let trimmed: &str = raw.trim_start_matches('\u{feff}');
435    let Some(rest) = trimmed.strip_prefix(FRONTMATTER_DELIMITER) else {
436        return (DocFrontmatter::default(), trimmed);
437    };
438    let rest: &str = rest
439        .strip_prefix("\r\n")
440        .or_else(|| rest.strip_prefix('\n'))
441        .unwrap_or(rest);
442    let mut offset: usize = 0;
443    for line in rest.split_inclusive('\n') {
444        let clean: &str = line.trim_end_matches(['\r', '\n']);
445        if clean.trim() == FRONTMATTER_DELIMITER {
446            let yaml_slice: &str = &rest[..offset];
447            let body_slice: &str = &rest[(offset + line.len())..];
448            let parsed: DocFrontmatter = from_str::<DocFrontmatter>(yaml_slice).unwrap_or_default();
449            return (parsed, body_slice);
450        }
451        offset += line.len();
452    }
453    (DocFrontmatter::default(), trimmed)
454}
455
456/// Converts a `pulldown_cmark::HeadingLevel` into its `u8` depth (`1..=6`).
457///
458/// # Arguments
459///
460/// - `HeadingLevel` - Heading level enum.
461///
462/// # Returns
463///
464/// - `u8` - Numeric heading depth.
465pub(crate) fn heading_level_num(level: HeadingLevel) -> u8 {
466    match level {
467        HeadingLevel::H1 => 1,
468        HeadingLevel::H2 => 2,
469        HeadingLevel::H3 => 3,
470        HeadingLevel::H4 => 4,
471        HeadingLevel::H5 => 5,
472        HeadingLevel::H6 => 6,
473    }
474}
475
476/// Produces a lowercase Unicode-safe URL anchor slug from heading text or path segments.
477///
478/// # Arguments
479///
480/// - `&str` - Heading text or path segment.
481///
482/// # Returns
483///
484/// - `String` - Hyphenated URL slug.
485pub(crate) fn slugify(input: &str) -> String {
486    let mut out: String = String::new();
487    let mut prev_dash: bool = false;
488    for ch in input.chars() {
489        if ch.is_alphanumeric() {
490            for lower in ch.to_lowercase() {
491                out.push(lower);
492            }
493            prev_dash = false;
494        } else if !prev_dash && !out.is_empty() {
495            out.push('-');
496            prev_dash = true;
497        }
498    }
499    out.trim_end_matches('-').to_string()
500}
501
502/// Ensures every heading anchor slug within a single page is unique (`slug`, `slug-2`, ...).
503///
504/// # Arguments
505///
506/// - `String` - Candidate slug string.
507/// - `&mut BTreeMap<String, usize>` - Per-page occurrence map.
508///
509/// # Returns
510///
511/// - `String` - Unique anchor slug.
512pub(crate) fn deduplicate_slug(raw_slug: String, seen: &mut BTreeMap<String, usize>) -> String {
513    let base: String = if raw_slug.is_empty() {
514        FALLBACK_SLUG_PREFIX.to_string()
515    } else {
516        raw_slug
517    };
518    let count: &mut usize = seen.entry(base.clone()).or_insert(0);
519    *count += 1;
520    if *count == 1 {
521        base
522    } else {
523        format!("{base}-{}", *count)
524    }
525}
526
527/// Recursively collects `.md` file paths beneath `dir`, skipping build artifacts, hidden folders, and `exclude_dir`.
528///
529/// # Arguments
530///
531/// - `&Path` - Directory to walk.
532/// - `Option<&Path>` - Optional canonical output directory to skip.
533/// - `&mut Vec<PathBuf>` - Output path accumulator.
534///
535/// # Returns
536///
537/// - `io::Result<()>` - Traversal result.
538fn collect_markdown_files(
539    dir: &Path,
540    exclude_dir: Option<&Path>,
541    out: &mut Vec<PathBuf>,
542) -> io::Result<()> {
543    for entry in fs::read_dir(dir)? {
544        let entry_val: DirEntry = entry?;
545        let path: PathBuf = entry_val.path();
546        if path.is_dir() {
547            let name: String = entry_val.file_name().to_string_lossy().into_owned();
548            if should_skip_dir(&name) {
549                continue;
550            }
551            if let Some(excluded) = exclude_dir {
552                let candidate: PathBuf = fs::canonicalize(&path).unwrap_or_else(|_| path.clone());
553                if candidate == excluded || candidate.starts_with(excluded) {
554                    continue;
555                }
556            }
557            collect_markdown_files(&path, exclude_dir, out)?;
558        } else if path
559            .extension()
560            .and_then(|s: &OsStr| s.to_str())
561            .is_some_and(|ext: &str| ext.eq_ignore_ascii_case(MARKDOWN_EXT))
562        {
563            out.push(path);
564        }
565    }
566    Ok(())
567}
568
569/// Returns `true` when directory `name` is an ignored build, cache, or hidden metadata directory.
570///
571/// # Arguments
572///
573/// - `&str` - Directory base name.
574///
575/// # Returns
576///
577/// - `bool` - Whether traversal should skip this directory.
578pub(crate) fn should_skip_dir(name: &str) -> bool {
579    name.starts_with('.')
580        || IGNORED_SCAN_DIRS
581            .iter()
582            .any(|ignored: &&str| name.eq_ignore_ascii_case(ignored))
583}
584
585/// Derives canonical route and formatted section label from a relative Markdown path.
586///
587/// # Arguments
588///
589/// - `&Path` - Relative path inside the docs root directory.
590///
591/// # Returns
592///
593/// - `(String, String)` - Canonical route path and section label.
594fn route_and_section_from_rel_path(rel: &Path) -> (String, String) {
595    let parts: Vec<String> = rel
596        .components()
597        .map(|c: Component<'_>| c.as_os_str().to_string_lossy().into_owned())
598        .collect();
599    if parts.is_empty() {
600        return (ROUTE_ROOT.to_string(), DEFAULT_SECTION.to_string());
601    }
602    let section: String = if parts.len() > 1 {
603        format_section_label(&parts[0])
604    } else {
605        DEFAULT_SECTION.to_string()
606    };
607    let stem: String = rel
608        .file_stem()
609        .map(|s: &OsStr| s.to_string_lossy().into_owned())
610        .unwrap_or_default();
611    let mut route_segments: Vec<String> = parts[..parts.len().saturating_sub(1)]
612        .iter()
613        .map(|seg: &String| {
614            let cleaned: String = slugify(seg);
615            if cleaned.is_empty() {
616                seg.to_ascii_lowercase()
617            } else {
618                cleaned
619            }
620        })
621        .collect();
622    if !stem.eq_ignore_ascii_case(README_STEM) && !stem.eq_ignore_ascii_case(INDEX_STEM) {
623        let cleaned_stem: String = slugify(&stem);
624        route_segments.push(if cleaned_stem.is_empty() {
625            stem.to_ascii_lowercase()
626        } else {
627            cleaned_stem
628        });
629    }
630    let route: String = if route_segments.is_empty() {
631        ROUTE_ROOT.to_string()
632    } else {
633        format!("/{}", route_segments.join("/"))
634    };
635    (route, section)
636}
637
638/// Formats a directory or filename slug into a readable Title-Case label.
639///
640/// # Arguments
641///
642/// - `&str` - Raw path segment or filename stem.
643///
644/// # Returns
645///
646/// - `String` - Formatted display label.
647fn format_section_label(raw: &str) -> String {
648    let mut words: Vec<String> = Vec::new();
649    for part in raw.split(['-', '_']) {
650        let trimmed: &str = part.trim();
651        if trimmed.is_empty() {
652            continue;
653        }
654        let mut chars: Chars<'_> = trimmed.chars();
655        if let Some(first) = chars.next() {
656            let mut word: String = String::new();
657            for up in first.to_uppercase() {
658                word.push(up);
659            }
660            word.push_str(chars.as_str());
661            words.push(word);
662        }
663    }
664    if words.is_empty() {
665        DEFAULT_SECTION.to_string()
666    } else {
667        words.join(" ")
668    }
669}
670
671/// Derives a human-readable fallback page title from a canonical route string.
672///
673/// # Arguments
674///
675/// - `&str` - Canonical route path.
676///
677/// # Returns
678///
679/// - `String` - Display title fallback.
680fn title_from_route(route: &str) -> String {
681    let trimmed: &str = route.trim_matches('/');
682    if trimmed.is_empty() {
683        return DEFAULT_DOC_TITLE.to_string();
684    }
685    trimmed
686        .rsplit('/')
687        .next()
688        .map(format_section_label)
689        .unwrap_or_else(|| DEFAULT_DOC_TITLE.to_string())
690}