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(|text_value: &String| !text_value.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 blue_val in blocks.iter() {
281 if let DocBlock::Heading { level, slug, text } = blue_val
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(|delta_val: &DocDirFrontmatter| delta_val.try_get_text().clone())
305 .filter(|label_str: &String| !label_str.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(|byte_val: &DocBlock| match byte_val {
319 DocBlock::Paragraph(point_val) | DocBlock::BlockQuote(point_val) => {
320 Some(point_val.clone())
321 }
322 _ => None,
323 })
324 .unwrap_or_default()
325 });
326 let resolved_updated: Option<String> = fm_updated.or_else(|| fm_date.clone());
327 let mut page: DocPage = DocPage::new(
328 route.to_string(),
329 title,
330 order,
331 section,
332 summary,
333 blocks,
334 toc,
335 );
336 page.set_markdown_body(body.to_string());
337 page.set_updated(resolved_updated);
338 page.set_home_meta(fm_home, fm_hero_text, fm_actions, fm_stats, fm_features);
339 page.set_hide_sidebar(fm_sidebar == Some(false));
340 page.set_dir_meta(
341 fm_index == Some(false),
342 fm_expanded,
343 dir_order,
344 dir_text,
345 dir_collapsible,
346 );
347 page.set_page_meta(
348 fm_password.filter(|pw: &String| !pw.trim().is_empty()),
349 fm_date,
350 fm_categories,
351 );
352 page
353}
354
355#[must_use]
365pub fn unique_locales(locales: &[DocLocaleConfig]) -> Vec<DocLocaleConfig> {
366 let mut seen: BTreeSet<String> = BTreeSet::new();
367 let mut out: Vec<DocLocaleConfig> = Vec::with_capacity(locales.len());
368 for loc in locales.iter() {
369 let key: String = loc.get_dir().trim().to_ascii_lowercase();
370 if key.is_empty() {
371 continue;
372 }
373 if seen.insert(key) {
374 out.push(loc.clone());
375 }
376 }
377 out
378}
379
380#[must_use]
390pub fn load_site_config(src_dir: &Path) -> Option<DocSiteConfig> {
391 let mut candidates: Vec<PathBuf> = vec![src_dir.join(README_FILENAME)];
392 if let Some(parent) = src_dir.parent() {
393 candidates.push(parent.join(README_FILENAME));
394 }
395 let mut fallback: Option<DocSiteConfig> = None;
396 for candidate in candidates.into_iter() {
397 if !candidate.is_file() {
398 continue;
399 }
400 let Ok(raw) = fs::read_to_string(&candidate) else {
401 continue;
402 };
403 let (fm, _): (DocFrontmatter, &str) = split_frontmatter(&raw);
404 let has_locales: bool = !fm.locales.is_empty();
405 let has_site: bool = fm.site.is_some();
406 if has_locales {
407 return Some(DocSiteConfig {
408 site: fm.site.unwrap_or_default(),
409 locales: fm.locales,
410 });
411 }
412 if has_site && fallback.is_none() {
413 fallback = Some(DocSiteConfig {
414 site: fm.site.unwrap_or_default(),
415 locales: Vec::new(),
416 });
417 }
418 }
419 fallback
420}
421
422pub fn load_locale_site(
435 src_dir: &Path,
436 config_spec: &DocSiteConfig,
437 locale: &DocLocaleConfig,
438 exclude_dir: Option<&Path>,
439) -> io::Result<DocSite> {
440 let locale_dir_name: &str = locale.get_dir().trim();
441 let content_dir: PathBuf = if locale_dir_name.is_empty() {
442 src_dir.to_path_buf()
443 } else {
444 let joined: PathBuf = src_dir.join(locale_dir_name);
445 if joined.is_dir() {
446 joined
447 } else {
448 src_dir.to_path_buf()
449 }
450 };
451 let title_override: Option<&str> = locale
452 .try_get_title()
453 .as_deref()
454 .or_else(|| config_spec.get_site().try_get_title().as_deref());
455 let mut site: DocSite = load_doc_site_excluding(&content_dir, title_override, exclude_dir)?;
456 if let Some(desc) = locale
457 .try_get_description()
458 .as_deref()
459 .or_else(|| config_spec.get_site().try_get_description().as_deref())
460 && !desc.trim().is_empty()
461 {
462 site.tagline = desc.trim().to_string();
463 }
464 site.apply_locale_metadata(config_spec, Some(locale));
465 Ok(site)
466}
467
468pub fn load_doc_site(root_dir: &Path) -> io::Result<DocSite> {
478 load_doc_site_with_options(root_dir, None)
479}
480
481pub fn load_doc_site_with_options(
492 root_dir: &Path,
493 title_override: Option<&str>,
494) -> io::Result<DocSite> {
495 load_doc_site_excluding(root_dir, title_override, None)
496}
497
498pub(crate) fn load_doc_site_excluding(
510 root_dir: &Path,
511 title_override: Option<&str>,
512 exclude_dir: Option<&Path>,
513) -> io::Result<DocSite> {
514 if !root_dir.exists() {
515 return Err(Error::new(
516 ErrorKind::NotFound,
517 root_dir.display().to_string(),
518 ));
519 }
520 let canonical_exclude: Option<PathBuf> = exclude_dir.map(|point_val: &Path| {
521 fs::canonicalize(point_val).unwrap_or_else(|_| point_val.to_path_buf())
522 });
523 let mut files: Vec<PathBuf> = Vec::new();
524 collect_markdown_files(root_dir, canonical_exclude.as_deref(), &mut files)?;
525 files.sort();
526 let mut pages: Vec<DocPage> = Vec::with_capacity(files.len());
527 let mut seen_routes: BTreeSet<String> = BTreeSet::new();
528 let mut detected_site_cfg: Option<DocSiteConfig> = None;
529 let mut root_sidebar_ranks: HashMap<String, i32> = HashMap::new();
530 let mut dir_sidebar_ranks: HashMap<(String, String), i32> = HashMap::new();
531 let mut detected_title: Option<String> = None;
532 let mut detected_tagline: Option<String> = None;
533 for file_path in files.into_iter() {
534 let raw: String = fs::read_to_string(&file_path)?;
535 let rel: &Path = file_path.strip_prefix(root_dir).unwrap_or(&file_path);
536 let (mut route, section): (String, String) = route_and_section_from_rel_path(rel);
537 let (mut frontmatter, body): (DocFrontmatter, &str) = split_frontmatter(&raw);
538 if !frontmatter.sidebar_order.is_empty() {
539 let parent_rel: String = rel
540 .parent()
541 .map(|palette_val: &Path| {
542 palette_val
543 .iter()
544 .map(|seg: &OsStr| slugify(&seg.to_string_lossy()))
545 .collect::<Vec<String>>()
546 .join("/")
547 })
548 .unwrap_or_default();
549 for (rank_idx, entry_name) in frontmatter.sidebar_order.iter().enumerate() {
550 let key: String = slugify(entry_name);
551 if key.is_empty() {
552 continue;
553 }
554 let rank_val: i32 = (rank_idx as i32) * 10 - 500;
555 if parent_rel.is_empty() {
556 let _: Option<i32> = root_sidebar_ranks.insert(key, rank_val);
557 } else {
558 let _: Option<i32> =
559 dir_sidebar_ranks.insert((parent_rel.clone(), key), rank_val);
560 }
561 }
562 }
563 if route == ROUTE_ROOT {
564 let fm_locales: Vec<DocLocaleConfig> = take(&mut frontmatter.locales);
565 if let Some(site_cfg) = frontmatter.site.take() {
566 if detected_title.is_none() {
567 detected_title = site_cfg.try_get_title().clone();
568 }
569 if detected_tagline.is_none() {
570 detected_tagline = site_cfg.try_get_description().clone();
571 }
572 detected_site_cfg = Some(DocSiteConfig {
573 site: site_cfg,
574 locales: fm_locales,
575 });
576 } else if !fm_locales.is_empty() {
577 detected_site_cfg = Some(DocSiteConfig {
578 site: DocSiteFrontmatter::default(),
579 locales: fm_locales,
580 });
581 }
582 }
583 if seen_routes.contains(&route) {
584 let stem: String = file_path
585 .file_stem()
586 .map(|source_val: &OsStr| slugify(&source_val.to_string_lossy()))
587 .filter(|text_value: &String| !text_value.is_empty())
588 .unwrap_or_else(|| FALLBACK_SLUG_PREFIX.to_string());
589 let base_route: String = if route == ROUTE_ROOT {
590 format!("/{stem}")
591 } else {
592 format!("{route}-{stem}")
593 };
594 route = base_route.clone();
595 let mut suffix: usize = 2;
596 while seen_routes.contains(&route) {
597 route = format!("{base_route}-{suffix}");
598 suffix += 1;
599 }
600 }
601 let _: bool = seen_routes.insert(route.clone());
602 let rel_normalized: String = rel
603 .components()
604 .map(|char_item: path::Component<'_>| {
605 char_item.as_os_str().to_string_lossy().into_owned()
606 })
607 .collect::<Vec<String>>()
608 .join("/");
609 let stem_is_index: bool =
610 rel.file_stem()
611 .and_then(OsStr::to_str)
612 .is_some_and(|label_str: &str| {
613 label_str.eq_ignore_ascii_case(README_STEM)
614 || label_str.eq_ignore_ascii_case(INDEX_STEM)
615 });
616 let mut parsed_page: DocPage =
617 parse_markdown_page_with_frontmatter(&route, §ion, frontmatter, body);
618 parsed_page.set_source_meta(rel_normalized, stem_is_index);
619 pages.push(parsed_page);
620 }
621 let mut dir_passwords: HashMap<String, String> = HashMap::new();
622 for page in pages.iter() {
623 if page.get_is_dir_index()
624 && let Some(pw) = page.try_get_password().as_deref()
625 && !pw.trim().is_empty()
626 {
627 let dir_key: String = page.directory_path();
628 if !dir_key.is_empty() {
629 let _: Option<String> = dir_passwords.insert(dir_key, pw.trim().to_string());
630 }
631 }
632 }
633 if !dir_passwords.is_empty() {
634 for page in pages.iter_mut() {
635 if page.try_get_password().is_some() {
636 continue;
637 }
638 let dir_key: String = page.directory_path();
639 let mut cur: &str = dir_key.as_str();
640 while !cur.is_empty() {
641 if let Some(pw) = dir_passwords.get(cur) {
642 page.set_inherited_password(pw.clone());
643 break;
644 }
645 match cur.rsplit_once('/') {
646 Some((parent, _)) => cur = parent,
647 None => break,
648 }
649 }
650 }
651 }
652 if !root_sidebar_ranks.is_empty() || !dir_sidebar_ranks.is_empty() {
653 for page in pages.iter_mut() {
654 if page.get_route() == ROUTE_ROOT || page.get_order() != 100 {
655 continue;
656 }
657 let computed_order: Option<i32> = {
658 let trimmed: &str = page.get_route().trim_matches('/');
659 let mut segs: Vec<&str> = trimmed.split('/').collect();
660 let mut found: Option<i32> = None;
661 if let Some(last) = segs.pop() {
662 let parent_key: String = segs.join("/");
663 if !parent_key.is_empty()
664 && let Some(&rank) = dir_sidebar_ranks.get(&(parent_key, last.to_string()))
665 {
666 found = Some(rank);
667 }
668 }
669 if found.is_none()
670 && let Some(first_seg) = trimmed.split('/').next()
671 && let Some(&rank) = root_sidebar_ranks.get(first_seg)
672 {
673 let is_group_index: bool = !trimmed.contains('/');
674 found = Some(if is_group_index { rank } else { rank + 1 });
675 }
676 found
677 };
678 if let Some(new_order) = computed_order {
679 page.order = new_order;
680 }
681 }
682 }
683 pages.sort_by(|alpha_val: &DocPage, blue_val: &DocPage| {
684 let a_root_rank: i32 = alpha_val
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 let b_root_rank: i32 = blue_val
692 .get_route()
693 .trim_matches('/')
694 .split('/')
695 .next()
696 .and_then(|seg: &str| root_sidebar_ranks.get(seg).copied())
697 .unwrap_or(i32::MAX);
698 if alpha_val.get_route() == ROUTE_ROOT && blue_val.get_route() != ROUTE_ROOT {
699 return Ordering::Less;
700 }
701 if blue_val.get_route() == ROUTE_ROOT && alpha_val.get_route() != ROUTE_ROOT {
702 return Ordering::Greater;
703 }
704 a_root_rank
705 .cmp(&b_root_rank)
706 .then_with(|| {
707 section_sort_rank(alpha_val.get_section())
708 .cmp(§ion_sort_rank(blue_val.get_section()))
709 })
710 .then_with(|| alpha_val.get_section().cmp(blue_val.get_section()))
711 .then_with(|| alpha_val.get_order().cmp(&blue_val.get_order()))
712 .then_with(|| alpha_val.get_route().cmp(blue_val.get_route()))
713 });
714 let fallback_site_title: String = root_dir
715 .file_name()
716 .map(|scale_val: &OsStr| scale_val.to_string_lossy().into_owned())
717 .filter(|raw: &String| {
718 raw.len() > 2
719 && !raw.eq_ignore_ascii_case(GENERIC_DOCS_DIR)
720 && !raw.eq_ignore_ascii_case(GENERIC_SRC_DIR)
721 && raw != "."
722 && raw != ".."
723 })
724 .map(|raw: String| format_section_label(&raw))
725 .unwrap_or_else(|| DOCS_SITE_TITLE.to_string());
726 let site_title: String = title_override
727 .map(str::to_string)
728 .or(detected_title)
729 .unwrap_or(fallback_site_title);
730 let site_tagline: String = detected_tagline.unwrap_or_else(|| DOCS_SITE_TAGLINE.to_string());
731 let mut site: DocSite = DocSite::new(site_title, site_tagline, pages);
732 if let Some(config_spec) = detected_site_cfg.as_ref() {
733 site.apply_locale_metadata(config_spec, None);
734 } else {
735 site.release_marker = EUV_DOCS_RELEASE_MARKER.to_string();
736 }
737 Ok(site)
738}
739
740pub(crate) fn section_sort_rank(section: &str) -> u8 {
750 if section.eq_ignore_ascii_case(DEFAULT_SECTION) {
751 0
752 } else if section.eq_ignore_ascii_case(GUIDE_SECTION) {
753 1
754 } else {
755 2
756 }
757}
758
759fn split_frontmatter(raw: &str) -> (DocFrontmatter, &str) {
769 let trimmed: &str = raw.trim_start_matches('\u{feff}');
770 let Some(rest) = trimmed.strip_prefix(FRONTMATTER_DELIMITER) else {
771 return (DocFrontmatter::default(), trimmed);
772 };
773 let rest: &str = rest
774 .strip_prefix("\r\n")
775 .or_else(|| rest.strip_prefix('\n'))
776 .unwrap_or(rest);
777 let mut offset: usize = 0;
778 for line in rest.split_inclusive('\n') {
779 let clean: &str = line.trim_end_matches(['\r', '\n']);
780 if clean.trim() == FRONTMATTER_DELIMITER {
781 let yaml_slice: &str = &rest[..offset];
782 let body_slice: &str = &rest[(offset + line.len())..];
783 let parsed: DocFrontmatter = from_str::<DocFrontmatter>(yaml_slice)
784 .unwrap_or_else(|_| parse_frontmatter_fallback(yaml_slice));
785 return (parsed, body_slice);
786 }
787 offset += line.len();
788 }
789 (DocFrontmatter::default(), trimmed)
790}
791
792fn parse_frontmatter_fallback(yaml_slice: &str) -> DocFrontmatter {
802 let mut fm: DocFrontmatter = DocFrontmatter::default();
803 let Ok(Value::Object(map)) = from_str::<Value>(yaml_slice) else {
804 return fm;
805 };
806 if let Some(source_val) = map.get("title").and_then(Value::as_str) {
807 fm.title = Some(source_val.to_string());
808 }
809 if let Some(item_count) = map.get("order").and_then(Value::as_i64) {
810 fm.order = Some(item_count as i32);
811 }
812 if let Some(scale_val) = map.get("tagline").and_then(Value::as_str) {
813 fm.tagline = Some(scale_val.to_string());
814 }
815 if let Some(series_item) = map.get("description").and_then(Value::as_str) {
816 fm.description = Some(series_item.to_string());
817 }
818 if let Some(text_slice) = map.get("section").and_then(Value::as_str) {
819 fm.section = Some(text_slice.to_string());
820 }
821 if let Some(source_val_primary) = map.get("updated").and_then(Value::as_str) {
822 fm.updated = Some(source_val_primary.to_string());
823 }
824 if let Some(source_val_secondary) = map.get("date").and_then(Value::as_str) {
825 fm.date = Some(source_val_secondary.to_string());
826 }
827 if let Some(blue_val) = map.get("index").and_then(Value::as_bool) {
828 fm.index = Some(blue_val);
829 }
830 if let Some(byte_val) = map.get("expanded").and_then(Value::as_bool) {
831 fm.expanded = Some(byte_val);
832 }
833 if let Some(bounds_val) = map.get("home").and_then(Value::as_bool) {
834 fm.home = bounds_val;
835 }
836 if let Some(second_val) = map.get("sidebar").and_then(Value::as_bool) {
837 fm.sidebar = Some(second_val);
838 }
839 if let Some(pw) = map.get("password") {
840 let pw_str: Option<String> = match pw {
841 Value::String(source_val_next) => Some(source_val_next.clone()),
842 Value::Number(node_entry) => Some(node_entry.to_string()),
843 _ => None,
844 };
845 fm.password = pw_str;
846 }
847 if let Some(cat) = map.get("category") {
848 match cat {
849 Value::String(source_val_alt) => fm.category.push(source_val_alt.clone()),
850 Value::Array(arr) => {
851 for item in arr.iter() {
852 if let Some(source_val_inner) = item.as_str() {
853 fm.category.push(source_val_inner.to_string());
854 }
855 }
856 }
857 _ => {}
858 }
859 }
860 if let Some(Value::Object(dir_map)) = map.get("dir") {
861 let mut dir_fm: DocDirFrontmatter = DocDirFrontmatter::default();
862 if let Some(normal_vec) = dir_map.get("order").and_then(Value::as_i64) {
863 dir_fm.order = Some(normal_vec as i32);
864 }
865 if let Some(source_val_local) = dir_map.get("text").and_then(Value::as_str) {
866 dir_fm.text = Some(source_val_local.to_string());
867 }
868 if let Some(blue_val_primary) = dir_map.get("link").and_then(Value::as_bool) {
869 dir_fm.link = Some(blue_val_primary);
870 }
871 if let Some(blue_val_secondary) = dir_map.get("collapsible").and_then(Value::as_bool) {
872 dir_fm.collapsible = Some(blue_val_secondary);
873 }
874 fm.dir = Some(dir_fm);
875 }
876 fm
877}
878
879pub(crate) fn heading_level_num(level: HeadingLevel) -> u8 {
889 match level {
890 HeadingLevel::H1 => 1,
891 HeadingLevel::H2 => 2,
892 HeadingLevel::H3 => 3,
893 HeadingLevel::H4 => 4,
894 HeadingLevel::H5 => 5,
895 HeadingLevel::H6 => 6,
896 }
897}
898
899fn push_slugified(out: &mut String, input: &str) {
906 let start_len: usize = out.len();
907 let mut prev_dash: bool = false;
908 for ch in input.chars() {
909 if ch.is_ascii_alphanumeric() {
910 out.push(ch.to_ascii_lowercase());
911 prev_dash = false;
912 } else if ch.is_alphanumeric() {
913 for lower in ch.to_lowercase() {
914 out.push(lower);
915 }
916 prev_dash = false;
917 } else if !prev_dash && out.len() > start_len {
918 out.push('-');
919 prev_dash = true;
920 }
921 }
922 while out.len() > start_len && out.ends_with('-') {
923 let _: Option<char> = out.pop();
924 }
925}
926
927pub(crate) fn slugify(input: &str) -> String {
937 let mut out: String = String::with_capacity(input.len());
938 push_slugified(&mut out, input);
939 out
940}
941
942pub(crate) fn deduplicate_slug(raw_slug: String, seen: &mut BTreeMap<String, usize>) -> String {
953 let base: String = if raw_slug.is_empty() {
954 FALLBACK_SLUG_PREFIX.to_string()
955 } else {
956 raw_slug
957 };
958 if let Some(count) = seen.get_mut(&base) {
959 *count += 1;
960 return format!("{base}-{}", *count);
961 }
962 let _: Option<usize> = seen.insert(base.clone(), 1);
963 base
964}
965
966fn collect_markdown_files(
978 dir: &Path,
979 exclude_dir: Option<&Path>,
980 out: &mut Vec<PathBuf>,
981) -> io::Result<()> {
982 for entry in fs::read_dir(dir)? {
983 let entry_val: DirEntry = entry?;
984 let path: PathBuf = entry_val.path();
985 let is_dir: bool = match entry_val.file_type() {
986 Ok(ft) if ft.is_dir() => true,
987 Ok(ft) if ft.is_file() => false,
988 _ => path.is_dir(),
989 };
990 if is_dir {
991 let file_name: OsString = entry_val.file_name();
992 let name: Cow<'_, str> = file_name.to_string_lossy();
993 if should_skip_dir(&name) {
994 continue;
995 }
996 if let Some(excluded) = exclude_dir {
997 let candidate: PathBuf = fs::canonicalize(&path).unwrap_or_else(|_| path.clone());
998 if candidate == excluded || candidate.starts_with(excluded) {
999 continue;
1000 }
1001 }
1002 collect_markdown_files(&path, exclude_dir, out)?;
1003 } else if path
1004 .extension()
1005 .and_then(|source_val: &OsStr| source_val.to_str())
1006 .is_some_and(|ext: &str| ext.eq_ignore_ascii_case(MARKDOWN_EXT))
1007 {
1008 out.push(path);
1009 }
1010 }
1011 Ok(())
1012}
1013
1014pub(crate) fn should_skip_dir(name: &str) -> bool {
1024 name.starts_with('.')
1025 || IGNORED_SCAN_DIRS
1026 .iter()
1027 .any(|ignored: &&str| name.eq_ignore_ascii_case(ignored))
1028}
1029
1030fn push_route_segment(out: &mut String, seg: &str) {
1037 out.push('/');
1038 let start_len: usize = out.len();
1039 push_slugified(out, seg);
1040 if out.len() == start_len {
1041 for ch in seg.chars() {
1042 out.push(ch.to_ascii_lowercase());
1043 }
1044 }
1045}
1046
1047fn route_and_section_from_rel_path(rel: &Path) -> (String, String) {
1057 let mut comps: Peekable<Components<'_>> = rel.components().peekable();
1058 let Some(first_comp) = comps.next() else {
1059 return (ROUTE_ROOT.to_string(), DEFAULT_SECTION.to_string());
1060 };
1061 let mut route: String = String::with_capacity(rel.as_os_str().len() + 1);
1062 let section: String = if comps.peek().is_some() {
1063 let first_cow: Cow<'_, str> = first_comp.as_os_str().to_string_lossy();
1064 let sec: String = format_section_label(&first_cow);
1065 push_route_segment(&mut route, &first_cow);
1066 while let Some(comp) = comps.next() {
1067 if comps.peek().is_some() {
1068 let seg_cow: Cow<'_, str> = comp.as_os_str().to_string_lossy();
1069 push_route_segment(&mut route, &seg_cow);
1070 }
1071 }
1072 sec
1073 } else {
1074 DEFAULT_SECTION.to_string()
1075 };
1076 let stem_cow: Cow<'_, str> = rel
1077 .file_stem()
1078 .map(OsStr::to_string_lossy)
1079 .unwrap_or(Cow::Borrowed(""));
1080 if !stem_cow.eq_ignore_ascii_case(README_STEM) && !stem_cow.eq_ignore_ascii_case(INDEX_STEM) {
1081 push_route_segment(&mut route, &stem_cow);
1082 }
1083 if route.is_empty() {
1084 route.push_str(ROUTE_ROOT);
1085 }
1086 (route, section)
1087}
1088
1089fn format_section_label(raw: &str) -> String {
1099 let mut out: String = String::with_capacity(raw.len());
1100 for part in raw.split(['-', '_']) {
1101 let trimmed: &str = part.trim();
1102 if trimmed.is_empty() {
1103 continue;
1104 }
1105 let mut chars: Chars<'_> = trimmed.chars();
1106 if let Some(first) = chars.next() {
1107 if !out.is_empty() {
1108 out.push(' ');
1109 }
1110 for up in first.to_uppercase() {
1111 out.push(up);
1112 }
1113 out.push_str(chars.as_str());
1114 }
1115 }
1116 if out.is_empty() {
1117 out.push_str(DEFAULT_SECTION);
1118 }
1119 out
1120}
1121
1122fn title_from_route(route: &str) -> String {
1132 let trimmed: &str = route.trim_matches('/');
1133 if trimmed.is_empty() {
1134 return DEFAULT_DOC_TITLE.to_string();
1135 }
1136 trimmed
1137 .rsplit('/')
1138 .next()
1139 .map(format_section_label)
1140 .unwrap_or_else(|| DEFAULT_DOC_TITLE.to_string())
1141}