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    parse_markdown_page_with_frontmatter(route, default_section, frontmatter, body)
18}
19
20/// Parses a Markdown body whose YAML frontmatter has already been extracted into a `DocPage`.
21///
22/// # Arguments
23///
24/// - `&str` - Canonical route path for this page.
25/// - `&str` - Section label derived from directory hierarchy.
26/// - `DocFrontmatter` - Pre-parsed YAML frontmatter metadata.
27/// - `&str` - Markdown body slice following frontmatter.
28///
29/// # Returns
30///
31/// - `DocPage` - Parsed structured documentation page.
32fn parse_markdown_page_with_frontmatter(
33    route: &str,
34    default_section: &str,
35    frontmatter: DocFrontmatter,
36    body: &str,
37) -> DocPage {
38    let mut blocks: Vec<DocBlock> = Vec::with_capacity((body.len() / 160).clamp(8, 256));
39    let mut toc: Vec<DocTocItem> = Vec::with_capacity((body.len() / 512).clamp(4, 32));
40    let mut seen_slugs: BTreeMap<String, usize> = BTreeMap::new();
41    let mut active_heading: Option<(u8, Option<CowStr<'_>>)> = None;
42    let mut first_h1_title: Option<String> = None;
43    let mut in_paragraph: bool = false;
44    let mut list_stack: Vec<String> = Vec::new();
45    let mut blockquote_depth: usize = 0;
46    let mut in_table: bool = false;
47    let mut in_table_head: bool = false;
48    let mut in_table_cell: bool = false;
49    let mut table_headers: Vec<String> = Vec::new();
50    let mut table_rows: Vec<Vec<String>> = Vec::new();
51    let mut current_row: Vec<String> = Vec::new();
52    let mut active_code_lang: Option<String> = None;
53    let mut active_image_src: Option<String> = None;
54    let mut image_alt_buf: String = String::new();
55    let mut buffer: String = String::with_capacity(256);
56    let parser: Parser<'_> = Parser::new_ext(body, Options::all());
57    for event in parser {
58        match event {
59            Event::Start(Tag::Heading { level, id, .. }) => {
60                active_heading = Some((heading_level_num(level), id));
61                buffer.clear();
62            }
63            Event::End(TagEnd::Heading(_)) => {
64                if let Some((level, custom_id)) = active_heading.take() {
65                    let text: String = buffer.trim().to_string();
66                    if !text.is_empty() {
67                        if level == 1 && first_h1_title.is_none() {
68                            first_h1_title = Some(text.clone());
69                        }
70                        let raw_slug: String = custom_id
71                            .as_deref()
72                            .map(slugify)
73                            .filter(|s: &String| !s.is_empty())
74                            .unwrap_or_else(|| slugify(&text));
75                        let slug: String = deduplicate_slug(raw_slug, &mut seen_slugs);
76                        if (2..=4).contains(&level) {
77                            toc.push(DocTocItem::new(level, slug.clone(), text.clone()));
78                        }
79                        blocks.push(DocBlock::Heading { level, slug, text });
80                    }
81                }
82                buffer.clear();
83            }
84            Event::Start(Tag::BlockQuote(_)) => {
85                blockquote_depth += 1;
86            }
87            Event::End(TagEnd::BlockQuote(_)) => {
88                blockquote_depth = blockquote_depth.saturating_sub(1);
89            }
90            Event::Start(Tag::Table(_)) => {
91                in_table = true;
92                table_headers.clear();
93                table_rows.clear();
94            }
95            Event::End(TagEnd::Table) => {
96                if in_table {
97                    in_table = false;
98                    let headers: Vec<String> = take(&mut table_headers);
99                    let rows: Vec<Vec<String>> = take(&mut table_rows);
100                    if !headers.is_empty() || !rows.is_empty() {
101                        blocks.push(DocBlock::Table { headers, rows });
102                    }
103                }
104            }
105            Event::Start(Tag::TableHead) => {
106                in_table_head = true;
107                current_row.clear();
108            }
109            Event::End(TagEnd::TableHead) => {
110                in_table_head = false;
111                table_headers = take(&mut current_row);
112            }
113            Event::Start(Tag::TableRow) => {
114                current_row.clear();
115            }
116            Event::End(TagEnd::TableRow) => {
117                if !in_table_head {
118                    table_rows.push(take(&mut current_row));
119                }
120            }
121            Event::Start(Tag::TableCell) => {
122                in_table_cell = true;
123                buffer.clear();
124            }
125            Event::End(TagEnd::TableCell) => {
126                if in_table_cell {
127                    in_table_cell = false;
128                    current_row.push(buffer.trim().to_string());
129                }
130                buffer.clear();
131            }
132            Event::Start(Tag::Paragraph) => {
133                if list_stack.is_empty() {
134                    in_paragraph = true;
135                    buffer.clear();
136                }
137            }
138            Event::End(TagEnd::Paragraph) => {
139                if in_paragraph {
140                    in_paragraph = false;
141                    let text: String = buffer.trim().to_string();
142                    if !text.is_empty() {
143                        if blockquote_depth > 0 {
144                            blocks.push(DocBlock::BlockQuote(text));
145                        } else {
146                            blocks.push(DocBlock::Paragraph(text));
147                        }
148                    }
149                    buffer.clear();
150                } else if let Some(top) = list_stack.last_mut()
151                    && !top.is_empty()
152                {
153                    top.push(' ');
154                }
155            }
156            Event::Start(Tag::Item) => {
157                if let Some(parent_text) = list_stack.last_mut() {
158                    let trimmed: String = parent_text.trim().to_string();
159                    if !trimmed.is_empty() {
160                        blocks.push(DocBlock::ListItem(trimmed));
161                        parent_text.clear();
162                    }
163                }
164                list_stack.push(String::new());
165            }
166            Event::End(TagEnd::Item) => {
167                if let Some(item_buf) = list_stack.pop() {
168                    let text: String = item_buf.trim().to_string();
169                    if !text.is_empty() {
170                        blocks.push(DocBlock::ListItem(text));
171                    }
172                }
173            }
174            Event::Start(Tag::CodeBlock(kind)) => {
175                let lang: String = match kind {
176                    CodeBlockKind::Fenced(tag) => {
177                        let trimmed: &str = tag.split_whitespace().next().unwrap_or("");
178                        if trimmed.is_empty() {
179                            DEFAULT_CODE_LANG.to_string()
180                        } else {
181                            trimmed.to_string()
182                        }
183                    }
184                    CodeBlockKind::Indented => DEFAULT_CODE_LANG.to_string(),
185                };
186                active_code_lang = Some(lang);
187                buffer.clear();
188            }
189            Event::End(TagEnd::CodeBlock) => {
190                if let Some(language) = active_code_lang.take() {
191                    let code: String = buffer.trim_end().to_string();
192                    blocks.push(DocBlock::Code { language, code });
193                }
194                buffer.clear();
195            }
196            Event::Start(Tag::Image { dest_url, .. }) => {
197                active_image_src = Some(dest_url.into_string());
198                image_alt_buf.clear();
199            }
200            Event::End(TagEnd::Image) => {
201                if let Some(src) = active_image_src.take() {
202                    let alt: String = image_alt_buf.trim().to_string();
203                    image_alt_buf.clear();
204                    if !src.is_empty() {
205                        blocks.push(DocBlock::Image { alt, src });
206                    }
207                }
208            }
209            Event::TaskListMarker(checked) => {
210                let marker: &str = if checked { "[x] " } else { "[ ] " };
211                if let Some(top) = list_stack.last_mut() {
212                    top.push_str(marker);
213                } else {
214                    buffer.push_str(marker);
215                }
216            }
217            Event::Rule => {
218                blocks.push(DocBlock::HorizontalRule);
219            }
220            Event::Text(text) | Event::Code(text) => {
221                if active_image_src.is_some() {
222                    image_alt_buf.push_str(&text);
223                } else if !list_stack.is_empty()
224                    && active_code_lang.is_none()
225                    && active_heading.is_none()
226                    && !in_table_cell
227                {
228                    if let Some(top) = list_stack.last_mut() {
229                        top.push_str(&text);
230                    }
231                } else {
232                    buffer.push_str(&text);
233                }
234            }
235            Event::SoftBreak | Event::HardBreak => {
236                let sep: char = if active_code_lang.is_some() {
237                    '\n'
238                } else {
239                    ' '
240                };
241                if active_image_src.is_some() {
242                    image_alt_buf.push(sep);
243                } else if !list_stack.is_empty()
244                    && active_code_lang.is_none()
245                    && active_heading.is_none()
246                    && !in_table_cell
247                {
248                    if let Some(top) = list_stack.last_mut() {
249                        top.push(sep);
250                    }
251                } else {
252                    buffer.push(sep);
253                }
254            }
255            _ => {}
256        }
257    }
258    let DocFrontmatter {
259        title: fm_title,
260        order: fm_order,
261        tagline: fm_tagline,
262        description: fm_description,
263        section: fm_section,
264        updated: fm_updated,
265        home: fm_home,
266        hero_text: fm_hero_text,
267        actions: fm_actions,
268        stats: fm_stats,
269        features: fm_features,
270        sidebar: fm_sidebar,
271        ..
272    } = frontmatter;
273    let fallback_title: String = first_h1_title
274        .or_else(|| {
275            toc.first()
276                .map(|item: &DocTocItem| item.get_title().clone())
277        })
278        .unwrap_or_else(|| title_from_route(route));
279    let title: String = fm_title.unwrap_or(fallback_title);
280    if toc
281        .first()
282        .is_some_and(|item: &DocTocItem| item.get_title().trim().eq_ignore_ascii_case(title.trim()))
283    {
284        let _: DocTocItem = toc.remove(0);
285    }
286    let default_order: i32 = if route == ROUTE_ROOT || fm_home {
287        -1000
288    } else {
289        100
290    };
291    let order: i32 = fm_order.unwrap_or(default_order);
292    let section: String = fm_section.unwrap_or_else(|| default_section.to_string());
293    let summary: String = fm_tagline.or(fm_description).unwrap_or_else(|| {
294        blocks
295            .iter()
296            .find_map(|b: &DocBlock| match b {
297                DocBlock::Paragraph(p) | DocBlock::BlockQuote(p) => Some(p.clone()),
298                _ => None,
299            })
300            .unwrap_or_default()
301    });
302    let mut page: DocPage = DocPage::new(
303        route.to_string(),
304        title,
305        order,
306        section,
307        summary,
308        blocks,
309        toc,
310    );
311    page.set_markdown_body(body.to_string());
312    page.set_updated(fm_updated);
313    page.set_home_meta(fm_home, fm_hero_text, fm_actions, fm_stats, fm_features);
314    page.set_hide_sidebar(fm_sidebar == Some(false));
315    page
316}
317
318/// Deduplicates locale entries by content directory while preserving declaration order.
319///
320/// # Arguments
321///
322/// - `&[DocLocaleConfig]` - Declared locale entries from frontmatter.
323///
324/// # Returns
325///
326/// - `Vec<DocLocaleConfig>` - Unique locale entries ordered by first occurrence of `dir`.
327#[must_use]
328pub fn unique_locales(locales: &[DocLocaleConfig]) -> Vec<DocLocaleConfig> {
329    let mut seen: BTreeSet<String> = BTreeSet::new();
330    let mut out: Vec<DocLocaleConfig> = Vec::with_capacity(locales.len());
331    for loc in locales.iter() {
332        let key: String = loc.get_dir().trim().to_ascii_lowercase();
333        if key.is_empty() {
334            continue;
335        }
336        if seen.insert(key) {
337            out.push(loc.clone());
338        }
339    }
340    out
341}
342
343/// Inspects `<src_dir>/README.md` and `<src_dir>/../README.md` for a multi-locale `DocSiteConfig` frontmatter block.
344///
345/// # Arguments
346///
347/// - `&Path` - Source documentation directory (for example `docs/`).
348///
349/// # Returns
350///
351/// - `Option<DocSiteConfig>` - Parsed site and locale configuration when `site:` or `locales:` is declared.
352#[must_use]
353pub fn load_site_config(src_dir: &Path) -> Option<DocSiteConfig> {
354    let mut candidates: Vec<PathBuf> = vec![src_dir.join(README_FILENAME)];
355    if let Some(parent) = src_dir.parent() {
356        candidates.push(parent.join(README_FILENAME));
357    }
358    let mut fallback: Option<DocSiteConfig> = None;
359    for candidate in candidates.into_iter() {
360        if !candidate.is_file() {
361            continue;
362        }
363        let Ok(raw) = fs::read_to_string(&candidate) else {
364            continue;
365        };
366        let (fm, _): (DocFrontmatter, &str) = split_frontmatter(&raw);
367        let has_locales: bool = !fm.locales.is_empty();
368        let has_site: bool = fm.site.is_some();
369        if has_locales {
370            return Some(DocSiteConfig {
371                site: fm.site.unwrap_or_default(),
372                locales: fm.locales,
373            });
374        }
375        if has_site && fallback.is_none() {
376            fallback = Some(DocSiteConfig {
377                site: fm.site.unwrap_or_default(),
378                locales: Vec::new(),
379            });
380        }
381    }
382    fallback
383}
384
385/// Loads a single locale content directory using shared `DocSiteConfig` and active `DocLocaleConfig` metadata.
386///
387/// # Arguments
388///
389/// - `&Path` - Root Markdown source directory containing per-locale folders (e.g. `docs/`).
390/// - `&DocSiteConfig` - Shared site configuration parsed from root `README.md`.
391/// - `&DocLocaleConfig` - Active locale entry specifying `dir`, `prefix`, `lang`, and labels.
392/// - `Option<&Path>` - Optional output directory excluded from scanning.
393///
394/// # Returns
395///
396/// - `io::Result<DocSite>` - Loaded, ordered, and metadata-annotated documentation site for this locale.
397pub fn load_locale_site(
398    src_dir: &Path,
399    cfg: &DocSiteConfig,
400    locale: &DocLocaleConfig,
401    exclude_dir: Option<&Path>,
402) -> io::Result<DocSite> {
403    let locale_dir_name: &str = locale.get_dir().trim();
404    let content_dir: PathBuf = if locale_dir_name.is_empty() {
405        src_dir.to_path_buf()
406    } else {
407        let joined: PathBuf = src_dir.join(locale_dir_name);
408        if joined.is_dir() {
409            joined
410        } else {
411            src_dir.to_path_buf()
412        }
413    };
414    let title_override: Option<&str> = locale
415        .try_get_title()
416        .as_deref()
417        .or_else(|| cfg.get_site().try_get_title().as_deref());
418    let mut site: DocSite = load_doc_site_excluding(&content_dir, title_override, exclude_dir)?;
419    if let Some(desc) = locale
420        .try_get_description()
421        .as_deref()
422        .or_else(|| cfg.get_site().try_get_description().as_deref())
423        && !desc.trim().is_empty()
424    {
425        site.tagline = desc.trim().to_string();
426    }
427    site.apply_locale_metadata(cfg, Some(locale));
428    Ok(site)
429}
430
431/// Recursively loads all `.md` files under `root_dir` into a sorted `DocSite`.
432///
433/// # Arguments
434///
435/// - `&Path` - Root Markdown or project directory.
436///
437/// # Returns
438///
439/// - `io::Result<DocSite>` - Loaded documentation site or I/O error.
440pub fn load_doc_site(root_dir: &Path) -> io::Result<DocSite> {
441    load_doc_site_with_options(root_dir, None)
442}
443
444/// Recursively loads all `.md` files under `root_dir` with optional site title override and smart directory filtering.
445///
446/// # Arguments
447///
448/// - `&Path` - Root Markdown or project directory.
449/// - `Option<&str>` - Optional explicit site title overriding frontmatter and folder heuristics.
450///
451/// # Returns
452///
453/// - `io::Result<DocSite>` - Loaded documentation site or I/O error.
454pub fn load_doc_site_with_options(
455    root_dir: &Path,
456    title_override: Option<&str>,
457) -> io::Result<DocSite> {
458    load_doc_site_excluding(root_dir, title_override, None)
459}
460
461/// Recursively loads all `.md` files under `root_dir`, skipping `exclude_dir` when it sits inside `root_dir`.
462///
463/// # Arguments
464///
465/// - `&Path` - Root Markdown or project directory.
466/// - `Option<&str>` - Optional explicit site title override.
467/// - `Option<&Path>` - Optional output directory excluded from traversal.
468///
469/// # Returns
470///
471/// - `io::Result<DocSite>` - Loaded and section-ordered documentation site or I/O error.
472pub(crate) fn load_doc_site_excluding(
473    root_dir: &Path,
474    title_override: Option<&str>,
475    exclude_dir: Option<&Path>,
476) -> io::Result<DocSite> {
477    if !root_dir.exists() {
478        return Err(Error::new(
479            ErrorKind::NotFound,
480            root_dir.display().to_string(),
481        ));
482    }
483    let canonical_exclude: Option<PathBuf> =
484        exclude_dir.map(|p: &Path| fs::canonicalize(p).unwrap_or_else(|_| p.to_path_buf()));
485    let mut files: Vec<PathBuf> = Vec::new();
486    collect_markdown_files(root_dir, canonical_exclude.as_deref(), &mut files)?;
487    files.sort();
488    let mut pages: Vec<DocPage> = Vec::with_capacity(files.len());
489    let mut seen_routes: BTreeSet<String> = BTreeSet::new();
490    let mut detected_site_cfg: Option<DocSiteConfig> = None;
491    let mut root_sidebar_ranks: HashMap<String, i32> = HashMap::new();
492    let mut dir_sidebar_ranks: HashMap<(String, String), i32> = HashMap::new();
493    let mut detected_title: Option<String> = None;
494    let mut detected_tagline: Option<String> = None;
495    for file_path in files.into_iter() {
496        let raw: String = fs::read_to_string(&file_path)?;
497        let rel: &Path = file_path.strip_prefix(root_dir).unwrap_or(&file_path);
498        let (mut route, section): (String, String) = route_and_section_from_rel_path(rel);
499        let (mut frontmatter, body): (DocFrontmatter, &str) = split_frontmatter(&raw);
500        if !frontmatter.sidebar_order.is_empty() {
501            let parent_rel: String = rel
502                .parent()
503                .map(|p: &Path| {
504                    p.iter()
505                        .map(|seg: &OsStr| slugify(&seg.to_string_lossy()))
506                        .collect::<Vec<String>>()
507                        .join("/")
508                })
509                .unwrap_or_default();
510            for (rank_idx, entry_name) in frontmatter.sidebar_order.iter().enumerate() {
511                let key: String = slugify(entry_name);
512                if key.is_empty() {
513                    continue;
514                }
515                let rank_val: i32 = (rank_idx as i32) * 10 - 500;
516                if parent_rel.is_empty() {
517                    let _: Option<i32> = root_sidebar_ranks.insert(key, rank_val);
518                } else {
519                    let _: Option<i32> =
520                        dir_sidebar_ranks.insert((parent_rel.clone(), key), rank_val);
521                }
522            }
523        }
524        if route == ROUTE_ROOT {
525            let fm_locales: Vec<DocLocaleConfig> = take(&mut frontmatter.locales);
526            if let Some(site_cfg) = frontmatter.site.take() {
527                if detected_title.is_none() {
528                    detected_title = site_cfg.try_get_title().clone();
529                }
530                if detected_tagline.is_none() {
531                    detected_tagline = site_cfg.try_get_description().clone();
532                }
533                detected_site_cfg = Some(DocSiteConfig {
534                    site: site_cfg,
535                    locales: fm_locales,
536                });
537            } else if !fm_locales.is_empty() {
538                detected_site_cfg = Some(DocSiteConfig {
539                    site: DocSiteFrontmatter::default(),
540                    locales: fm_locales,
541                });
542            }
543        }
544        if seen_routes.contains(&route) {
545            let stem: String = file_path
546                .file_stem()
547                .map(|s: &OsStr| slugify(&s.to_string_lossy()))
548                .filter(|s: &String| !s.is_empty())
549                .unwrap_or_else(|| FALLBACK_SLUG_PREFIX.to_string());
550            let base_route: String = if route == ROUTE_ROOT {
551                format!("/{stem}")
552            } else {
553                format!("{route}-{stem}")
554            };
555            route = base_route.clone();
556            let mut suffix: usize = 2;
557            while seen_routes.contains(&route) {
558                route = format!("{base_route}-{suffix}");
559                suffix += 1;
560            }
561        }
562        let _: bool = seen_routes.insert(route.clone());
563        pages.push(parse_markdown_page_with_frontmatter(
564            &route,
565            &section,
566            frontmatter,
567            body,
568        ));
569    }
570    if !root_sidebar_ranks.is_empty() || !dir_sidebar_ranks.is_empty() {
571        for page in pages.iter_mut() {
572            if page.get_route() == ROUTE_ROOT || page.get_order() != 100 {
573                continue;
574            }
575            let computed_order: Option<i32> = {
576                let trimmed: &str = page.get_route().trim_matches('/');
577                let mut segs: Vec<&str> = trimmed.split('/').collect();
578                let mut found: Option<i32> = None;
579                if let Some(last) = segs.pop() {
580                    let parent_key: String = segs.join("/");
581                    if !parent_key.is_empty()
582                        && let Some(&rank) = dir_sidebar_ranks.get(&(parent_key, last.to_string()))
583                    {
584                        found = Some(rank);
585                    }
586                }
587                if found.is_none()
588                    && let Some(first_seg) = trimmed.split('/').next()
589                    && let Some(&rank) = root_sidebar_ranks.get(first_seg)
590                {
591                    let is_group_index: bool = !trimmed.contains('/');
592                    found = Some(if is_group_index { rank } else { rank + 1 });
593                }
594                found
595            };
596            if let Some(new_order) = computed_order {
597                page.order = new_order;
598            }
599        }
600    }
601    pages.sort_by(|a: &DocPage, b: &DocPage| {
602        let a_root_rank: i32 = a
603            .get_route()
604            .trim_matches('/')
605            .split('/')
606            .next()
607            .and_then(|seg: &str| root_sidebar_ranks.get(seg).copied())
608            .unwrap_or(i32::MAX);
609        let b_root_rank: i32 = b
610            .get_route()
611            .trim_matches('/')
612            .split('/')
613            .next()
614            .and_then(|seg: &str| root_sidebar_ranks.get(seg).copied())
615            .unwrap_or(i32::MAX);
616        if a.get_route() == ROUTE_ROOT && b.get_route() != ROUTE_ROOT {
617            return Ordering::Less;
618        }
619        if b.get_route() == ROUTE_ROOT && a.get_route() != ROUTE_ROOT {
620            return Ordering::Greater;
621        }
622        a_root_rank
623            .cmp(&b_root_rank)
624            .then_with(|| {
625                section_sort_rank(a.get_section()).cmp(&section_sort_rank(b.get_section()))
626            })
627            .then_with(|| a.get_section().cmp(b.get_section()))
628            .then_with(|| a.get_order().cmp(&b.get_order()))
629            .then_with(|| a.get_route().cmp(b.get_route()))
630    });
631    let fallback_site_title: String = root_dir
632        .file_name()
633        .map(|s: &OsStr| s.to_string_lossy().into_owned())
634        .filter(|raw: &String| {
635            raw.len() > 2
636                && !raw.eq_ignore_ascii_case(GENERIC_DOCS_DIR)
637                && !raw.eq_ignore_ascii_case(GENERIC_SRC_DIR)
638                && raw != "."
639                && raw != ".."
640        })
641        .map(|raw: String| format_section_label(&raw))
642        .unwrap_or_else(|| DOCS_SITE_TITLE.to_string());
643    let site_title: String = title_override
644        .map(str::to_string)
645        .or(detected_title)
646        .unwrap_or(fallback_site_title);
647    let site_tagline: String = detected_tagline.unwrap_or_else(|| DOCS_SITE_TAGLINE.to_string());
648    let mut site: DocSite = DocSite::new(site_title, site_tagline, pages);
649    if let Some(cfg) = detected_site_cfg.as_ref() {
650        site.apply_locale_metadata(cfg, None);
651    } else {
652        site.release_marker = EUV_DOCS_RELEASE_MARKER.to_string();
653    }
654    Ok(site)
655}
656
657/// Returns the canonical sidebar and pagination ordering rank for a section label.
658///
659/// # Arguments
660///
661/// - `&str` - Section display label.
662///
663/// # Returns
664///
665/// - `u8` - Priority rank (`0` General, `1` Guide, `2` all other sections alphabetically).
666pub(crate) fn section_sort_rank(section: &str) -> u8 {
667    if section.eq_ignore_ascii_case(DEFAULT_SECTION) {
668        0
669    } else if section.eq_ignore_ascii_case(GUIDE_SECTION) {
670        1
671    } else {
672        2
673    }
674}
675
676/// Extracts optional YAML frontmatter delimited by `---` lines.
677///
678/// # Arguments
679///
680/// - `&str` - Full raw Markdown document.
681///
682/// # Returns
683///
684/// - `(DocFrontmatter, &str)` - Parsed frontmatter and remaining Markdown body slice.
685fn split_frontmatter(raw: &str) -> (DocFrontmatter, &str) {
686    let trimmed: &str = raw.trim_start_matches('\u{feff}');
687    let Some(rest) = trimmed.strip_prefix(FRONTMATTER_DELIMITER) else {
688        return (DocFrontmatter::default(), trimmed);
689    };
690    let rest: &str = rest
691        .strip_prefix("\r\n")
692        .or_else(|| rest.strip_prefix('\n'))
693        .unwrap_or(rest);
694    let mut offset: usize = 0;
695    for line in rest.split_inclusive('\n') {
696        let clean: &str = line.trim_end_matches(['\r', '\n']);
697        if clean.trim() == FRONTMATTER_DELIMITER {
698            let yaml_slice: &str = &rest[..offset];
699            let body_slice: &str = &rest[(offset + line.len())..];
700            let parsed: DocFrontmatter = from_str::<DocFrontmatter>(yaml_slice).unwrap_or_default();
701            return (parsed, body_slice);
702        }
703        offset += line.len();
704    }
705    (DocFrontmatter::default(), trimmed)
706}
707
708/// Converts a `pulldown_cmark::HeadingLevel` into its `u8` depth (`1..=6`).
709///
710/// # Arguments
711///
712/// - `HeadingLevel` - Heading level enum.
713///
714/// # Returns
715///
716/// - `u8` - Numeric heading depth.
717pub(crate) fn heading_level_num(level: HeadingLevel) -> u8 {
718    match level {
719        HeadingLevel::H1 => 1,
720        HeadingLevel::H2 => 2,
721        HeadingLevel::H3 => 3,
722        HeadingLevel::H4 => 4,
723        HeadingLevel::H5 => 5,
724        HeadingLevel::H6 => 6,
725    }
726}
727
728/// Appends a lowercase Unicode-safe URL anchor slug for `input` directly into `out`.
729///
730/// # Arguments
731///
732/// - `&mut String` - Destination slug buffer.
733/// - `&str` - Heading text or path segment.
734fn push_slugified(out: &mut String, input: &str) {
735    let start_len: usize = out.len();
736    let mut prev_dash: bool = false;
737    for ch in input.chars() {
738        if ch.is_ascii_alphanumeric() {
739            out.push(ch.to_ascii_lowercase());
740            prev_dash = false;
741        } else if ch.is_alphanumeric() {
742            for lower in ch.to_lowercase() {
743                out.push(lower);
744            }
745            prev_dash = false;
746        } else if !prev_dash && out.len() > start_len {
747            out.push('-');
748            prev_dash = true;
749        }
750    }
751    while out.len() > start_len && out.ends_with('-') {
752        let _: Option<char> = out.pop();
753    }
754}
755
756/// Produces a lowercase Unicode-safe URL anchor slug from heading text or path segments.
757///
758/// # Arguments
759///
760/// - `&str` - Heading text or path segment.
761///
762/// # Returns
763///
764/// - `String` - Hyphenated URL slug.
765pub(crate) fn slugify(input: &str) -> String {
766    let mut out: String = String::with_capacity(input.len());
767    push_slugified(&mut out, input);
768    out
769}
770
771/// Ensures every heading anchor slug within a single page is unique (`slug`, `slug-2`, ...).
772///
773/// # Arguments
774///
775/// - `String` - Candidate slug string.
776/// - `&mut BTreeMap<String, usize>` - Per-page occurrence map.
777///
778/// # Returns
779///
780/// - `String` - Unique anchor slug.
781pub(crate) fn deduplicate_slug(raw_slug: String, seen: &mut BTreeMap<String, usize>) -> String {
782    let base: String = if raw_slug.is_empty() {
783        FALLBACK_SLUG_PREFIX.to_string()
784    } else {
785        raw_slug
786    };
787    if let Some(count) = seen.get_mut(&base) {
788        *count += 1;
789        return format!("{base}-{}", *count);
790    }
791    let _: Option<usize> = seen.insert(base.clone(), 1);
792    base
793}
794
795/// Recursively collects `.md` file paths beneath `dir`, skipping build artifacts, hidden folders, and `exclude_dir`.
796///
797/// # Arguments
798///
799/// - `&Path` - Directory to walk.
800/// - `Option<&Path>` - Optional canonical output directory to skip.
801/// - `&mut Vec<PathBuf>` - Output path accumulator.
802///
803/// # Returns
804///
805/// - `io::Result<()>` - Traversal result.
806fn collect_markdown_files(
807    dir: &Path,
808    exclude_dir: Option<&Path>,
809    out: &mut Vec<PathBuf>,
810) -> io::Result<()> {
811    for entry in fs::read_dir(dir)? {
812        let entry_val: DirEntry = entry?;
813        let path: PathBuf = entry_val.path();
814        let is_dir: bool = match entry_val.file_type() {
815            Ok(ft) if ft.is_dir() => true,
816            Ok(ft) if ft.is_file() => false,
817            _ => path.is_dir(),
818        };
819        if is_dir {
820            let file_name: OsString = entry_val.file_name();
821            let name: Cow<'_, str> = file_name.to_string_lossy();
822            if should_skip_dir(&name) {
823                continue;
824            }
825            if let Some(excluded) = exclude_dir {
826                let candidate: PathBuf = fs::canonicalize(&path).unwrap_or_else(|_| path.clone());
827                if candidate == excluded || candidate.starts_with(excluded) {
828                    continue;
829                }
830            }
831            collect_markdown_files(&path, exclude_dir, out)?;
832        } else if path
833            .extension()
834            .and_then(|s: &OsStr| s.to_str())
835            .is_some_and(|ext: &str| ext.eq_ignore_ascii_case(MARKDOWN_EXT))
836        {
837            out.push(path);
838        }
839    }
840    Ok(())
841}
842
843/// Returns `true` when directory `name` is an ignored build, cache, or hidden metadata directory.
844///
845/// # Arguments
846///
847/// - `&str` - Directory base name.
848///
849/// # Returns
850///
851/// - `bool` - Whether traversal should skip this directory.
852pub(crate) fn should_skip_dir(name: &str) -> bool {
853    name.starts_with('.')
854        || IGNORED_SCAN_DIRS
855            .iter()
856            .any(|ignored: &&str| name.eq_ignore_ascii_case(ignored))
857}
858
859/// Appends a single `/` plus slugified (or ASCII-lowercased fallback) route segment into `out`.
860///
861/// # Arguments
862///
863/// - `&mut String` - Destination route buffer.
864/// - `&str` - Raw directory name or file stem segment.
865fn push_route_segment(out: &mut String, seg: &str) {
866    out.push('/');
867    let start_len: usize = out.len();
868    push_slugified(out, seg);
869    if out.len() == start_len {
870        for ch in seg.chars() {
871            out.push(ch.to_ascii_lowercase());
872        }
873    }
874}
875
876/// Derives canonical route and formatted section label from a relative Markdown path.
877///
878/// # Arguments
879///
880/// - `&Path` - Relative path inside the docs root directory.
881///
882/// # Returns
883///
884/// - `(String, String)` - Canonical route path and section label.
885fn route_and_section_from_rel_path(rel: &Path) -> (String, String) {
886    let mut comps: Peekable<Components<'_>> = rel.components().peekable();
887    let Some(first_comp) = comps.next() else {
888        return (ROUTE_ROOT.to_string(), DEFAULT_SECTION.to_string());
889    };
890    let mut route: String = String::with_capacity(rel.as_os_str().len() + 1);
891    let section: String = if comps.peek().is_some() {
892        let first_cow: Cow<'_, str> = first_comp.as_os_str().to_string_lossy();
893        let sec: String = format_section_label(&first_cow);
894        push_route_segment(&mut route, &first_cow);
895        while let Some(comp) = comps.next() {
896            if comps.peek().is_some() {
897                let seg_cow: Cow<'_, str> = comp.as_os_str().to_string_lossy();
898                push_route_segment(&mut route, &seg_cow);
899            }
900        }
901        sec
902    } else {
903        DEFAULT_SECTION.to_string()
904    };
905    let stem_cow: Cow<'_, str> = rel
906        .file_stem()
907        .map(OsStr::to_string_lossy)
908        .unwrap_or(Cow::Borrowed(""));
909    if !stem_cow.eq_ignore_ascii_case(README_STEM) && !stem_cow.eq_ignore_ascii_case(INDEX_STEM) {
910        push_route_segment(&mut route, &stem_cow);
911    }
912    if route.is_empty() {
913        route.push_str(ROUTE_ROOT);
914    }
915    (route, section)
916}
917
918/// Formats a directory or filename slug into a readable Title-Case label.
919///
920/// # Arguments
921///
922/// - `&str` - Raw path segment or filename stem.
923///
924/// # Returns
925///
926/// - `String` - Formatted display label.
927fn format_section_label(raw: &str) -> String {
928    let mut out: String = String::with_capacity(raw.len());
929    for part in raw.split(['-', '_']) {
930        let trimmed: &str = part.trim();
931        if trimmed.is_empty() {
932            continue;
933        }
934        let mut chars: Chars<'_> = trimmed.chars();
935        if let Some(first) = chars.next() {
936            if !out.is_empty() {
937                out.push(' ');
938            }
939            for up in first.to_uppercase() {
940                out.push(up);
941            }
942            out.push_str(chars.as_str());
943        }
944    }
945    if out.is_empty() {
946        out.push_str(DEFAULT_SECTION);
947    }
948    out
949}
950
951/// Derives a human-readable fallback page title from a canonical route string.
952///
953/// # Arguments
954///
955/// - `&str` - Canonical route path.
956///
957/// # Returns
958///
959/// - `String` - Display title fallback.
960fn title_from_route(route: &str) -> String {
961    let trimmed: &str = route.trim_matches('/');
962    if trimmed.is_empty() {
963        return DEFAULT_DOC_TITLE.to_string();
964    }
965    trimmed
966        .rsplit('/')
967        .next()
968        .map(format_section_label)
969        .unwrap_or_else(|| DEFAULT_DOC_TITLE.to_string())
970}