1use super::*;
2
3#[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
20fn 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 date: fm_date,
266 category: fm_categories,
267 index: fm_index,
268 expanded: fm_expanded,
269 dir: fm_dir,
270 password: fm_password,
271 home: fm_home,
272 hero_text: fm_hero_text,
273 actions: fm_actions,
274 stats: fm_stats,
275 features: fm_features,
276 sidebar: fm_sidebar,
277 ..
278 } = frontmatter;
279 if toc.is_empty() {
280 for b in blocks.iter() {
281 if let DocBlock::Heading { level, slug, text } = b
282 && *level == 1
283 {
284 toc.push(DocTocItem::new(*level, slug.clone(), text.clone()));
285 }
286 }
287 }
288 let fallback_title: String = first_h1_title
289 .or_else(|| {
290 toc.first()
291 .map(|item: &DocTocItem| item.get_title().clone())
292 })
293 .unwrap_or_else(|| title_from_route(route));
294 let title: String = fm_title.unwrap_or(fallback_title);
295 if toc
296 .first()
297 .is_some_and(|item: &DocTocItem| item.get_title().trim().eq_ignore_ascii_case(title.trim()))
298 {
299 let _: DocTocItem = toc.remove(0);
300 }
301 let dir_order: Option<i32> = fm_dir.as_ref().and_then(DocDirFrontmatter::get_order);
302 let dir_text: Option<String> = fm_dir
303 .as_ref()
304 .and_then(|d: &DocDirFrontmatter| d.try_get_text().clone())
305 .filter(|s: &String| !s.trim().is_empty());
306 let dir_collapsible: Option<bool> =
307 fm_dir.as_ref().and_then(DocDirFrontmatter::get_collapsible);
308 let default_order: i32 = if route == ROUTE_ROOT || fm_home {
309 -1000
310 } else {
311 100
312 };
313 let order: i32 = fm_order.or(dir_order).unwrap_or(default_order);
314 let section: String = fm_section.unwrap_or_else(|| default_section.to_string());
315 let summary: String = fm_tagline.or(fm_description).unwrap_or_else(|| {
316 blocks
317 .iter()
318 .find_map(|b: &DocBlock| match b {
319 DocBlock::Paragraph(p) | DocBlock::BlockQuote(p) => Some(p.clone()),
320 _ => None,
321 })
322 .unwrap_or_default()
323 });
324 let resolved_updated: Option<String> = fm_updated.or_else(|| fm_date.clone());
325 let mut page: DocPage = DocPage::new(
326 route.to_string(),
327 title,
328 order,
329 section,
330 summary,
331 blocks,
332 toc,
333 );
334 page.set_markdown_body(body.to_string());
335 page.set_updated(resolved_updated);
336 page.set_home_meta(fm_home, fm_hero_text, fm_actions, fm_stats, fm_features);
337 page.set_hide_sidebar(fm_sidebar == Some(false));
338 page.set_dir_meta(
339 fm_index == Some(false),
340 fm_expanded,
341 dir_order,
342 dir_text,
343 dir_collapsible,
344 );
345 page.set_page_meta(
346 fm_password.filter(|pw: &String| !pw.trim().is_empty()),
347 fm_date,
348 fm_categories,
349 );
350 page
351}
352
353#[must_use]
363pub fn unique_locales(locales: &[DocLocaleConfig]) -> Vec<DocLocaleConfig> {
364 let mut seen: BTreeSet<String> = BTreeSet::new();
365 let mut out: Vec<DocLocaleConfig> = Vec::with_capacity(locales.len());
366 for loc in locales.iter() {
367 let key: String = loc.get_dir().trim().to_ascii_lowercase();
368 if key.is_empty() {
369 continue;
370 }
371 if seen.insert(key) {
372 out.push(loc.clone());
373 }
374 }
375 out
376}
377
378#[must_use]
388pub fn load_site_config(src_dir: &Path) -> Option<DocSiteConfig> {
389 let mut candidates: Vec<PathBuf> = vec![src_dir.join(README_FILENAME)];
390 if let Some(parent) = src_dir.parent() {
391 candidates.push(parent.join(README_FILENAME));
392 }
393 let mut fallback: Option<DocSiteConfig> = None;
394 for candidate in candidates.into_iter() {
395 if !candidate.is_file() {
396 continue;
397 }
398 let Ok(raw) = fs::read_to_string(&candidate) else {
399 continue;
400 };
401 let (fm, _): (DocFrontmatter, &str) = split_frontmatter(&raw);
402 let has_locales: bool = !fm.locales.is_empty();
403 let has_site: bool = fm.site.is_some();
404 if has_locales {
405 return Some(DocSiteConfig {
406 site: fm.site.unwrap_or_default(),
407 locales: fm.locales,
408 });
409 }
410 if has_site && fallback.is_none() {
411 fallback = Some(DocSiteConfig {
412 site: fm.site.unwrap_or_default(),
413 locales: Vec::new(),
414 });
415 }
416 }
417 fallback
418}
419
420pub fn load_locale_site(
433 src_dir: &Path,
434 cfg: &DocSiteConfig,
435 locale: &DocLocaleConfig,
436 exclude_dir: Option<&Path>,
437) -> io::Result<DocSite> {
438 let locale_dir_name: &str = locale.get_dir().trim();
439 let content_dir: PathBuf = if locale_dir_name.is_empty() {
440 src_dir.to_path_buf()
441 } else {
442 let joined: PathBuf = src_dir.join(locale_dir_name);
443 if joined.is_dir() {
444 joined
445 } else {
446 src_dir.to_path_buf()
447 }
448 };
449 let title_override: Option<&str> = locale
450 .try_get_title()
451 .as_deref()
452 .or_else(|| cfg.get_site().try_get_title().as_deref());
453 let mut site: DocSite = load_doc_site_excluding(&content_dir, title_override, exclude_dir)?;
454 if let Some(desc) = locale
455 .try_get_description()
456 .as_deref()
457 .or_else(|| cfg.get_site().try_get_description().as_deref())
458 && !desc.trim().is_empty()
459 {
460 site.tagline = desc.trim().to_string();
461 }
462 site.apply_locale_metadata(cfg, Some(locale));
463 Ok(site)
464}
465
466pub fn load_doc_site(root_dir: &Path) -> io::Result<DocSite> {
476 load_doc_site_with_options(root_dir, None)
477}
478
479pub fn load_doc_site_with_options(
490 root_dir: &Path,
491 title_override: Option<&str>,
492) -> io::Result<DocSite> {
493 load_doc_site_excluding(root_dir, title_override, None)
494}
495
496pub(crate) fn load_doc_site_excluding(
508 root_dir: &Path,
509 title_override: Option<&str>,
510 exclude_dir: Option<&Path>,
511) -> io::Result<DocSite> {
512 if !root_dir.exists() {
513 return Err(Error::new(
514 ErrorKind::NotFound,
515 root_dir.display().to_string(),
516 ));
517 }
518 let canonical_exclude: Option<PathBuf> =
519 exclude_dir.map(|p: &Path| fs::canonicalize(p).unwrap_or_else(|_| p.to_path_buf()));
520 let mut files: Vec<PathBuf> = Vec::new();
521 collect_markdown_files(root_dir, canonical_exclude.as_deref(), &mut files)?;
522 files.sort();
523 let mut pages: Vec<DocPage> = Vec::with_capacity(files.len());
524 let mut seen_routes: BTreeSet<String> = BTreeSet::new();
525 let mut detected_site_cfg: Option<DocSiteConfig> = None;
526 let mut root_sidebar_ranks: HashMap<String, i32> = HashMap::new();
527 let mut dir_sidebar_ranks: HashMap<(String, String), i32> = HashMap::new();
528 let mut detected_title: Option<String> = None;
529 let mut detected_tagline: Option<String> = None;
530 for file_path in files.into_iter() {
531 let raw: String = fs::read_to_string(&file_path)?;
532 let rel: &Path = file_path.strip_prefix(root_dir).unwrap_or(&file_path);
533 let (mut route, section): (String, String) = route_and_section_from_rel_path(rel);
534 let (mut frontmatter, body): (DocFrontmatter, &str) = split_frontmatter(&raw);
535 if !frontmatter.sidebar_order.is_empty() {
536 let parent_rel: String = rel
537 .parent()
538 .map(|p: &Path| {
539 p.iter()
540 .map(|seg: &OsStr| slugify(&seg.to_string_lossy()))
541 .collect::<Vec<String>>()
542 .join("/")
543 })
544 .unwrap_or_default();
545 for (rank_idx, entry_name) in frontmatter.sidebar_order.iter().enumerate() {
546 let key: String = slugify(entry_name);
547 if key.is_empty() {
548 continue;
549 }
550 let rank_val: i32 = (rank_idx as i32) * 10 - 500;
551 if parent_rel.is_empty() {
552 let _: Option<i32> = root_sidebar_ranks.insert(key, rank_val);
553 } else {
554 let _: Option<i32> =
555 dir_sidebar_ranks.insert((parent_rel.clone(), key), rank_val);
556 }
557 }
558 }
559 if route == ROUTE_ROOT {
560 let fm_locales: Vec<DocLocaleConfig> = take(&mut frontmatter.locales);
561 if let Some(site_cfg) = frontmatter.site.take() {
562 if detected_title.is_none() {
563 detected_title = site_cfg.try_get_title().clone();
564 }
565 if detected_tagline.is_none() {
566 detected_tagline = site_cfg.try_get_description().clone();
567 }
568 detected_site_cfg = Some(DocSiteConfig {
569 site: site_cfg,
570 locales: fm_locales,
571 });
572 } else if !fm_locales.is_empty() {
573 detected_site_cfg = Some(DocSiteConfig {
574 site: DocSiteFrontmatter::default(),
575 locales: fm_locales,
576 });
577 }
578 }
579 if seen_routes.contains(&route) {
580 let stem: String = file_path
581 .file_stem()
582 .map(|s: &OsStr| slugify(&s.to_string_lossy()))
583 .filter(|s: &String| !s.is_empty())
584 .unwrap_or_else(|| FALLBACK_SLUG_PREFIX.to_string());
585 let base_route: String = if route == ROUTE_ROOT {
586 format!("/{stem}")
587 } else {
588 format!("{route}-{stem}")
589 };
590 route = base_route.clone();
591 let mut suffix: usize = 2;
592 while seen_routes.contains(&route) {
593 route = format!("{base_route}-{suffix}");
594 suffix += 1;
595 }
596 }
597 let _: bool = seen_routes.insert(route.clone());
598 let rel_normalized: String = rel
599 .components()
600 .map(|c: path::Component<'_>| c.as_os_str().to_string_lossy().into_owned())
601 .collect::<Vec<String>>()
602 .join("/");
603 let stem_is_index: bool = rel
604 .file_stem()
605 .and_then(OsStr::to_str)
606 .is_some_and(|s: &str| {
607 s.eq_ignore_ascii_case(README_STEM) || s.eq_ignore_ascii_case(INDEX_STEM)
608 });
609 let mut parsed_page: DocPage =
610 parse_markdown_page_with_frontmatter(&route, §ion, frontmatter, body);
611 parsed_page.set_source_meta(rel_normalized, stem_is_index);
612 pages.push(parsed_page);
613 }
614 let mut dir_passwords: HashMap<String, String> = HashMap::new();
615 for page in pages.iter() {
616 if page.get_is_dir_index()
617 && let Some(pw) = page.try_get_password().as_deref()
618 && !pw.trim().is_empty()
619 {
620 let dir_key: String = page.directory_path();
621 if !dir_key.is_empty() {
622 let _: Option<String> = dir_passwords.insert(dir_key, pw.trim().to_string());
623 }
624 }
625 }
626 if !dir_passwords.is_empty() {
627 for page in pages.iter_mut() {
628 if page.try_get_password().is_some() {
629 continue;
630 }
631 let dir_key: String = page.directory_path();
632 let mut cur: &str = dir_key.as_str();
633 while !cur.is_empty() {
634 if let Some(pw) = dir_passwords.get(cur) {
635 page.set_inherited_password(pw.clone());
636 break;
637 }
638 match cur.rsplit_once('/') {
639 Some((parent, _)) => cur = parent,
640 None => break,
641 }
642 }
643 }
644 }
645 if !root_sidebar_ranks.is_empty() || !dir_sidebar_ranks.is_empty() {
646 for page in pages.iter_mut() {
647 if page.get_route() == ROUTE_ROOT || page.get_order() != 100 {
648 continue;
649 }
650 let computed_order: Option<i32> = {
651 let trimmed: &str = page.get_route().trim_matches('/');
652 let mut segs: Vec<&str> = trimmed.split('/').collect();
653 let mut found: Option<i32> = None;
654 if let Some(last) = segs.pop() {
655 let parent_key: String = segs.join("/");
656 if !parent_key.is_empty()
657 && let Some(&rank) = dir_sidebar_ranks.get(&(parent_key, last.to_string()))
658 {
659 found = Some(rank);
660 }
661 }
662 if found.is_none()
663 && let Some(first_seg) = trimmed.split('/').next()
664 && let Some(&rank) = root_sidebar_ranks.get(first_seg)
665 {
666 let is_group_index: bool = !trimmed.contains('/');
667 found = Some(if is_group_index { rank } else { rank + 1 });
668 }
669 found
670 };
671 if let Some(new_order) = computed_order {
672 page.order = new_order;
673 }
674 }
675 }
676 pages.sort_by(|a: &DocPage, b: &DocPage| {
677 let a_root_rank: i32 = a
678 .get_route()
679 .trim_matches('/')
680 .split('/')
681 .next()
682 .and_then(|seg: &str| root_sidebar_ranks.get(seg).copied())
683 .unwrap_or(i32::MAX);
684 let b_root_rank: i32 = b
685 .get_route()
686 .trim_matches('/')
687 .split('/')
688 .next()
689 .and_then(|seg: &str| root_sidebar_ranks.get(seg).copied())
690 .unwrap_or(i32::MAX);
691 if a.get_route() == ROUTE_ROOT && b.get_route() != ROUTE_ROOT {
692 return Ordering::Less;
693 }
694 if b.get_route() == ROUTE_ROOT && a.get_route() != ROUTE_ROOT {
695 return Ordering::Greater;
696 }
697 a_root_rank
698 .cmp(&b_root_rank)
699 .then_with(|| {
700 section_sort_rank(a.get_section()).cmp(§ion_sort_rank(b.get_section()))
701 })
702 .then_with(|| a.get_section().cmp(b.get_section()))
703 .then_with(|| a.get_order().cmp(&b.get_order()))
704 .then_with(|| a.get_route().cmp(b.get_route()))
705 });
706 let fallback_site_title: String = root_dir
707 .file_name()
708 .map(|s: &OsStr| s.to_string_lossy().into_owned())
709 .filter(|raw: &String| {
710 raw.len() > 2
711 && !raw.eq_ignore_ascii_case(GENERIC_DOCS_DIR)
712 && !raw.eq_ignore_ascii_case(GENERIC_SRC_DIR)
713 && raw != "."
714 && raw != ".."
715 })
716 .map(|raw: String| format_section_label(&raw))
717 .unwrap_or_else(|| DOCS_SITE_TITLE.to_string());
718 let site_title: String = title_override
719 .map(str::to_string)
720 .or(detected_title)
721 .unwrap_or(fallback_site_title);
722 let site_tagline: String = detected_tagline.unwrap_or_else(|| DOCS_SITE_TAGLINE.to_string());
723 let mut site: DocSite = DocSite::new(site_title, site_tagline, pages);
724 if let Some(cfg) = detected_site_cfg.as_ref() {
725 site.apply_locale_metadata(cfg, None);
726 } else {
727 site.release_marker = EUV_DOCS_RELEASE_MARKER.to_string();
728 }
729 Ok(site)
730}
731
732pub(crate) fn section_sort_rank(section: &str) -> u8 {
742 if section.eq_ignore_ascii_case(DEFAULT_SECTION) {
743 0
744 } else if section.eq_ignore_ascii_case(GUIDE_SECTION) {
745 1
746 } else {
747 2
748 }
749}
750
751fn split_frontmatter(raw: &str) -> (DocFrontmatter, &str) {
761 let trimmed: &str = raw.trim_start_matches('\u{feff}');
762 let Some(rest) = trimmed.strip_prefix(FRONTMATTER_DELIMITER) else {
763 return (DocFrontmatter::default(), trimmed);
764 };
765 let rest: &str = rest
766 .strip_prefix("\r\n")
767 .or_else(|| rest.strip_prefix('\n'))
768 .unwrap_or(rest);
769 let mut offset: usize = 0;
770 for line in rest.split_inclusive('\n') {
771 let clean: &str = line.trim_end_matches(['\r', '\n']);
772 if clean.trim() == FRONTMATTER_DELIMITER {
773 let yaml_slice: &str = &rest[..offset];
774 let body_slice: &str = &rest[(offset + line.len())..];
775 let parsed: DocFrontmatter = from_str::<DocFrontmatter>(yaml_slice)
776 .unwrap_or_else(|_| parse_frontmatter_fallback(yaml_slice));
777 return (parsed, body_slice);
778 }
779 offset += line.len();
780 }
781 (DocFrontmatter::default(), trimmed)
782}
783
784fn parse_frontmatter_fallback(yaml_slice: &str) -> DocFrontmatter {
794 let mut fm: DocFrontmatter = DocFrontmatter::default();
795 let Ok(Value::Object(map)) = from_str::<Value>(yaml_slice) else {
796 return fm;
797 };
798 if let Some(s) = map.get("title").and_then(Value::as_str) {
799 fm.title = Some(s.to_string());
800 }
801 if let Some(n) = map.get("order").and_then(Value::as_i64) {
802 fm.order = Some(n as i32);
803 }
804 if let Some(s) = map.get("tagline").and_then(Value::as_str) {
805 fm.tagline = Some(s.to_string());
806 }
807 if let Some(s) = map.get("description").and_then(Value::as_str) {
808 fm.description = Some(s.to_string());
809 }
810 if let Some(s) = map.get("section").and_then(Value::as_str) {
811 fm.section = Some(s.to_string());
812 }
813 if let Some(s) = map.get("updated").and_then(Value::as_str) {
814 fm.updated = Some(s.to_string());
815 }
816 if let Some(s) = map.get("date").and_then(Value::as_str) {
817 fm.date = Some(s.to_string());
818 }
819 if let Some(b) = map.get("index").and_then(Value::as_bool) {
820 fm.index = Some(b);
821 }
822 if let Some(b) = map.get("expanded").and_then(Value::as_bool) {
823 fm.expanded = Some(b);
824 }
825 if let Some(b) = map.get("home").and_then(Value::as_bool) {
826 fm.home = b;
827 }
828 if let Some(b) = map.get("sidebar").and_then(Value::as_bool) {
829 fm.sidebar = Some(b);
830 }
831 if let Some(pw) = map.get("password") {
832 let pw_str: Option<String> = match pw {
833 Value::String(s) => Some(s.clone()),
834 Value::Number(n) => Some(n.to_string()),
835 _ => None,
836 };
837 fm.password = pw_str;
838 }
839 if let Some(cat) = map.get("category") {
840 match cat {
841 Value::String(s) => fm.category.push(s.clone()),
842 Value::Array(arr) => {
843 for item in arr.iter() {
844 if let Some(s) = item.as_str() {
845 fm.category.push(s.to_string());
846 }
847 }
848 }
849 _ => {}
850 }
851 }
852 if let Some(Value::Object(dir_map)) = map.get("dir") {
853 let mut dir_fm: DocDirFrontmatter = DocDirFrontmatter::default();
854 if let Some(n) = dir_map.get("order").and_then(Value::as_i64) {
855 dir_fm.order = Some(n as i32);
856 }
857 if let Some(s) = dir_map.get("text").and_then(Value::as_str) {
858 dir_fm.text = Some(s.to_string());
859 }
860 if let Some(b) = dir_map.get("link").and_then(Value::as_bool) {
861 dir_fm.link = Some(b);
862 }
863 if let Some(b) = dir_map.get("collapsible").and_then(Value::as_bool) {
864 dir_fm.collapsible = Some(b);
865 }
866 fm.dir = Some(dir_fm);
867 }
868 fm
869}
870
871pub(crate) fn heading_level_num(level: HeadingLevel) -> u8 {
881 match level {
882 HeadingLevel::H1 => 1,
883 HeadingLevel::H2 => 2,
884 HeadingLevel::H3 => 3,
885 HeadingLevel::H4 => 4,
886 HeadingLevel::H5 => 5,
887 HeadingLevel::H6 => 6,
888 }
889}
890
891fn push_slugified(out: &mut String, input: &str) {
898 let start_len: usize = out.len();
899 let mut prev_dash: bool = false;
900 for ch in input.chars() {
901 if ch.is_ascii_alphanumeric() {
902 out.push(ch.to_ascii_lowercase());
903 prev_dash = false;
904 } else if ch.is_alphanumeric() {
905 for lower in ch.to_lowercase() {
906 out.push(lower);
907 }
908 prev_dash = false;
909 } else if !prev_dash && out.len() > start_len {
910 out.push('-');
911 prev_dash = true;
912 }
913 }
914 while out.len() > start_len && out.ends_with('-') {
915 let _: Option<char> = out.pop();
916 }
917}
918
919pub(crate) fn slugify(input: &str) -> String {
929 let mut out: String = String::with_capacity(input.len());
930 push_slugified(&mut out, input);
931 out
932}
933
934pub(crate) fn deduplicate_slug(raw_slug: String, seen: &mut BTreeMap<String, usize>) -> String {
945 let base: String = if raw_slug.is_empty() {
946 FALLBACK_SLUG_PREFIX.to_string()
947 } else {
948 raw_slug
949 };
950 if let Some(count) = seen.get_mut(&base) {
951 *count += 1;
952 return format!("{base}-{}", *count);
953 }
954 let _: Option<usize> = seen.insert(base.clone(), 1);
955 base
956}
957
958fn collect_markdown_files(
970 dir: &Path,
971 exclude_dir: Option<&Path>,
972 out: &mut Vec<PathBuf>,
973) -> io::Result<()> {
974 for entry in fs::read_dir(dir)? {
975 let entry_val: DirEntry = entry?;
976 let path: PathBuf = entry_val.path();
977 let is_dir: bool = match entry_val.file_type() {
978 Ok(ft) if ft.is_dir() => true,
979 Ok(ft) if ft.is_file() => false,
980 _ => path.is_dir(),
981 };
982 if is_dir {
983 let file_name: OsString = entry_val.file_name();
984 let name: Cow<'_, str> = file_name.to_string_lossy();
985 if should_skip_dir(&name) {
986 continue;
987 }
988 if let Some(excluded) = exclude_dir {
989 let candidate: PathBuf = fs::canonicalize(&path).unwrap_or_else(|_| path.clone());
990 if candidate == excluded || candidate.starts_with(excluded) {
991 continue;
992 }
993 }
994 collect_markdown_files(&path, exclude_dir, out)?;
995 } else if path
996 .extension()
997 .and_then(|s: &OsStr| s.to_str())
998 .is_some_and(|ext: &str| ext.eq_ignore_ascii_case(MARKDOWN_EXT))
999 {
1000 out.push(path);
1001 }
1002 }
1003 Ok(())
1004}
1005
1006pub(crate) fn should_skip_dir(name: &str) -> bool {
1016 name.starts_with('.')
1017 || IGNORED_SCAN_DIRS
1018 .iter()
1019 .any(|ignored: &&str| name.eq_ignore_ascii_case(ignored))
1020}
1021
1022fn push_route_segment(out: &mut String, seg: &str) {
1029 out.push('/');
1030 let start_len: usize = out.len();
1031 push_slugified(out, seg);
1032 if out.len() == start_len {
1033 for ch in seg.chars() {
1034 out.push(ch.to_ascii_lowercase());
1035 }
1036 }
1037}
1038
1039fn route_and_section_from_rel_path(rel: &Path) -> (String, String) {
1049 let mut comps: Peekable<Components<'_>> = rel.components().peekable();
1050 let Some(first_comp) = comps.next() else {
1051 return (ROUTE_ROOT.to_string(), DEFAULT_SECTION.to_string());
1052 };
1053 let mut route: String = String::with_capacity(rel.as_os_str().len() + 1);
1054 let section: String = if comps.peek().is_some() {
1055 let first_cow: Cow<'_, str> = first_comp.as_os_str().to_string_lossy();
1056 let sec: String = format_section_label(&first_cow);
1057 push_route_segment(&mut route, &first_cow);
1058 while let Some(comp) = comps.next() {
1059 if comps.peek().is_some() {
1060 let seg_cow: Cow<'_, str> = comp.as_os_str().to_string_lossy();
1061 push_route_segment(&mut route, &seg_cow);
1062 }
1063 }
1064 sec
1065 } else {
1066 DEFAULT_SECTION.to_string()
1067 };
1068 let stem_cow: Cow<'_, str> = rel
1069 .file_stem()
1070 .map(OsStr::to_string_lossy)
1071 .unwrap_or(Cow::Borrowed(""));
1072 if !stem_cow.eq_ignore_ascii_case(README_STEM) && !stem_cow.eq_ignore_ascii_case(INDEX_STEM) {
1073 push_route_segment(&mut route, &stem_cow);
1074 }
1075 if route.is_empty() {
1076 route.push_str(ROUTE_ROOT);
1077 }
1078 (route, section)
1079}
1080
1081fn format_section_label(raw: &str) -> String {
1091 let mut out: String = String::with_capacity(raw.len());
1092 for part in raw.split(['-', '_']) {
1093 let trimmed: &str = part.trim();
1094 if trimmed.is_empty() {
1095 continue;
1096 }
1097 let mut chars: Chars<'_> = trimmed.chars();
1098 if let Some(first) = chars.next() {
1099 if !out.is_empty() {
1100 out.push(' ');
1101 }
1102 for up in first.to_uppercase() {
1103 out.push(up);
1104 }
1105 out.push_str(chars.as_str());
1106 }
1107 }
1108 if out.is_empty() {
1109 out.push_str(DEFAULT_SECTION);
1110 }
1111 out
1112}
1113
1114fn title_from_route(route: &str) -> String {
1124 let trimmed: &str = route.trim_matches('/');
1125 if trimmed.is_empty() {
1126 return DEFAULT_DOC_TITLE.to_string();
1127 }
1128 trimmed
1129 .rsplit('/')
1130 .next()
1131 .map(format_section_label)
1132 .unwrap_or_else(|| DEFAULT_DOC_TITLE.to_string())
1133}