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 section: fm_section,
263 ..
264 } = frontmatter;
265 let fallback_title: String = first_h1_title
266 .or_else(|| {
267 toc.first()
268 .map(|item: &DocTocItem| item.get_title().clone())
269 })
270 .unwrap_or_else(|| title_from_route(route));
271 let title: String = fm_title.unwrap_or(fallback_title);
272 if toc
273 .first()
274 .is_some_and(|item: &DocTocItem| item.get_title().trim().eq_ignore_ascii_case(title.trim()))
275 {
276 let _: DocTocItem = toc.remove(0);
277 }
278 let default_order: i32 = if route == ROUTE_ROOT { -1000 } else { 100 };
279 let order: i32 = fm_order.unwrap_or(default_order);
280 let section: String = fm_section.unwrap_or_else(|| default_section.to_string());
281 let summary: String = fm_tagline.unwrap_or_else(|| {
282 blocks
283 .iter()
284 .find_map(|b: &DocBlock| match b {
285 DocBlock::Paragraph(p) | DocBlock::BlockQuote(p) => Some(p.clone()),
286 _ => None,
287 })
288 .unwrap_or_default()
289 });
290 let mut page: DocPage = DocPage::new(
291 route.to_string(),
292 title,
293 order,
294 section,
295 summary,
296 blocks,
297 toc,
298 );
299 page.set_markdown_body(body.to_string());
300 page
301}
302
303pub fn load_doc_site(root_dir: &Path) -> io::Result<DocSite> {
313 load_doc_site_with_options(root_dir, None)
314}
315
316pub fn load_doc_site_with_options(
327 root_dir: &Path,
328 title_override: Option<&str>,
329) -> io::Result<DocSite> {
330 load_doc_site_excluding(root_dir, title_override, None)
331}
332
333pub(crate) fn load_doc_site_excluding(
345 root_dir: &Path,
346 title_override: Option<&str>,
347 exclude_dir: Option<&Path>,
348) -> io::Result<DocSite> {
349 if !root_dir.exists() {
350 return Err(Error::new(
351 ErrorKind::NotFound,
352 root_dir.display().to_string(),
353 ));
354 }
355 let canonical_exclude: Option<PathBuf> =
356 exclude_dir.map(|p: &Path| fs::canonicalize(p).unwrap_or_else(|_| p.to_path_buf()));
357 let mut files: Vec<PathBuf> = Vec::new();
358 collect_markdown_files(root_dir, canonical_exclude.as_deref(), &mut files)?;
359 files.sort();
360 let mut pages: Vec<DocPage> = Vec::with_capacity(files.len());
361 let mut seen_routes: BTreeSet<String> = BTreeSet::new();
362 let mut detected_title: Option<String> = None;
363 let mut detected_tagline: Option<String> = None;
364 for file_path in files.into_iter() {
365 let raw: String = fs::read_to_string(&file_path)?;
366 let rel: &Path = file_path.strip_prefix(root_dir).unwrap_or(&file_path);
367 let (mut route, section): (String, String) = route_and_section_from_rel_path(rel);
368 let (mut frontmatter, body): (DocFrontmatter, &str) = split_frontmatter(&raw);
369 if route == ROUTE_ROOT
370 && let Some(site_cfg) = frontmatter.site.take()
371 {
372 if detected_title.is_none() {
373 detected_title = site_cfg.try_get_title().clone();
374 }
375 if detected_tagline.is_none() {
376 detected_tagline = site_cfg.try_get_description().clone();
377 }
378 }
379 if seen_routes.contains(&route) {
380 let stem: String = file_path
381 .file_stem()
382 .map(|s: &OsStr| slugify(&s.to_string_lossy()))
383 .filter(|s: &String| !s.is_empty())
384 .unwrap_or_else(|| FALLBACK_SLUG_PREFIX.to_string());
385 let base_route: String = if route == ROUTE_ROOT {
386 format!("/{stem}")
387 } else {
388 format!("{route}-{stem}")
389 };
390 route = base_route.clone();
391 let mut suffix: usize = 2;
392 while seen_routes.contains(&route) {
393 route = format!("{base_route}-{suffix}");
394 suffix += 1;
395 }
396 }
397 let _: bool = seen_routes.insert(route.clone());
398 pages.push(parse_markdown_page_with_frontmatter(
399 &route,
400 §ion,
401 frontmatter,
402 body,
403 ));
404 }
405 pages.sort_by(|a: &DocPage, b: &DocPage| {
406 section_sort_rank(a.get_section())
407 .cmp(§ion_sort_rank(b.get_section()))
408 .then_with(|| a.get_section().cmp(b.get_section()))
409 .then_with(|| a.get_order().cmp(&b.get_order()))
410 .then_with(|| a.get_route().cmp(b.get_route()))
411 });
412 let fallback_site_title: String = root_dir
413 .file_name()
414 .map(|s: &OsStr| s.to_string_lossy().into_owned())
415 .filter(|raw: &String| {
416 raw.len() > 2
417 && !raw.eq_ignore_ascii_case(GENERIC_DOCS_DIR)
418 && !raw.eq_ignore_ascii_case(GENERIC_SRC_DIR)
419 && raw != "."
420 && raw != ".."
421 })
422 .map(|raw: String| format_section_label(&raw))
423 .unwrap_or_else(|| DOCS_SITE_TITLE.to_string());
424 let site_title: String = title_override
425 .map(str::to_string)
426 .or(detected_title)
427 .unwrap_or(fallback_site_title);
428 let site_tagline: String = detected_tagline.unwrap_or_else(|| DOCS_SITE_TAGLINE.to_string());
429 Ok(DocSite::new(site_title, site_tagline, pages))
430}
431
432pub(crate) fn section_sort_rank(section: &str) -> u8 {
442 if section.eq_ignore_ascii_case(DEFAULT_SECTION) {
443 0
444 } else if section.eq_ignore_ascii_case(GUIDE_SECTION) {
445 1
446 } else {
447 2
448 }
449}
450
451fn split_frontmatter(raw: &str) -> (DocFrontmatter, &str) {
461 let trimmed: &str = raw.trim_start_matches('\u{feff}');
462 let Some(rest) = trimmed.strip_prefix(FRONTMATTER_DELIMITER) else {
463 return (DocFrontmatter::default(), trimmed);
464 };
465 let rest: &str = rest
466 .strip_prefix("\r\n")
467 .or_else(|| rest.strip_prefix('\n'))
468 .unwrap_or(rest);
469 let mut offset: usize = 0;
470 for line in rest.split_inclusive('\n') {
471 let clean: &str = line.trim_end_matches(['\r', '\n']);
472 if clean.trim() == FRONTMATTER_DELIMITER {
473 let yaml_slice: &str = &rest[..offset];
474 let body_slice: &str = &rest[(offset + line.len())..];
475 let parsed: DocFrontmatter = from_str::<DocFrontmatter>(yaml_slice).unwrap_or_default();
476 return (parsed, body_slice);
477 }
478 offset += line.len();
479 }
480 (DocFrontmatter::default(), trimmed)
481}
482
483pub(crate) fn heading_level_num(level: HeadingLevel) -> u8 {
493 match level {
494 HeadingLevel::H1 => 1,
495 HeadingLevel::H2 => 2,
496 HeadingLevel::H3 => 3,
497 HeadingLevel::H4 => 4,
498 HeadingLevel::H5 => 5,
499 HeadingLevel::H6 => 6,
500 }
501}
502
503fn push_slugified(out: &mut String, input: &str) {
510 let start_len: usize = out.len();
511 let mut prev_dash: bool = false;
512 for ch in input.chars() {
513 if ch.is_ascii_alphanumeric() {
514 out.push(ch.to_ascii_lowercase());
515 prev_dash = false;
516 } else if ch.is_alphanumeric() {
517 for lower in ch.to_lowercase() {
518 out.push(lower);
519 }
520 prev_dash = false;
521 } else if !prev_dash && out.len() > start_len {
522 out.push('-');
523 prev_dash = true;
524 }
525 }
526 while out.len() > start_len && out.ends_with('-') {
527 let _: Option<char> = out.pop();
528 }
529}
530
531pub(crate) fn slugify(input: &str) -> String {
541 let mut out: String = String::with_capacity(input.len());
542 push_slugified(&mut out, input);
543 out
544}
545
546pub(crate) fn deduplicate_slug(raw_slug: String, seen: &mut BTreeMap<String, usize>) -> String {
557 let base: String = if raw_slug.is_empty() {
558 FALLBACK_SLUG_PREFIX.to_string()
559 } else {
560 raw_slug
561 };
562 if let Some(count) = seen.get_mut(&base) {
563 *count += 1;
564 return format!("{base}-{}", *count);
565 }
566 let _: Option<usize> = seen.insert(base.clone(), 1);
567 base
568}
569
570fn collect_markdown_files(
582 dir: &Path,
583 exclude_dir: Option<&Path>,
584 out: &mut Vec<PathBuf>,
585) -> io::Result<()> {
586 for entry in fs::read_dir(dir)? {
587 let entry_val: DirEntry = entry?;
588 let path: PathBuf = entry_val.path();
589 let is_dir: bool = match entry_val.file_type() {
590 Ok(ft) if ft.is_dir() => true,
591 Ok(ft) if ft.is_file() => false,
592 _ => path.is_dir(),
593 };
594 if is_dir {
595 let file_name: OsString = entry_val.file_name();
596 let name: Cow<'_, str> = file_name.to_string_lossy();
597 if should_skip_dir(&name) {
598 continue;
599 }
600 if let Some(excluded) = exclude_dir {
601 let candidate: PathBuf = fs::canonicalize(&path).unwrap_or_else(|_| path.clone());
602 if candidate == excluded || candidate.starts_with(excluded) {
603 continue;
604 }
605 }
606 collect_markdown_files(&path, exclude_dir, out)?;
607 } else if path
608 .extension()
609 .and_then(|s: &OsStr| s.to_str())
610 .is_some_and(|ext: &str| ext.eq_ignore_ascii_case(MARKDOWN_EXT))
611 {
612 out.push(path);
613 }
614 }
615 Ok(())
616}
617
618pub(crate) fn should_skip_dir(name: &str) -> bool {
628 name.starts_with('.')
629 || IGNORED_SCAN_DIRS
630 .iter()
631 .any(|ignored: &&str| name.eq_ignore_ascii_case(ignored))
632}
633
634fn push_route_segment(out: &mut String, seg: &str) {
641 out.push('/');
642 let start_len: usize = out.len();
643 push_slugified(out, seg);
644 if out.len() == start_len {
645 for ch in seg.chars() {
646 out.push(ch.to_ascii_lowercase());
647 }
648 }
649}
650
651fn route_and_section_from_rel_path(rel: &Path) -> (String, String) {
661 let mut comps: Peekable<Components<'_>> = rel.components().peekable();
662 let Some(first_comp) = comps.next() else {
663 return (ROUTE_ROOT.to_string(), DEFAULT_SECTION.to_string());
664 };
665 let mut route: String = String::with_capacity(rel.as_os_str().len() + 1);
666 let section: String = if comps.peek().is_some() {
667 let first_cow: Cow<'_, str> = first_comp.as_os_str().to_string_lossy();
668 let sec: String = format_section_label(&first_cow);
669 push_route_segment(&mut route, &first_cow);
670 while let Some(comp) = comps.next() {
671 if comps.peek().is_some() {
672 let seg_cow: Cow<'_, str> = comp.as_os_str().to_string_lossy();
673 push_route_segment(&mut route, &seg_cow);
674 }
675 }
676 sec
677 } else {
678 DEFAULT_SECTION.to_string()
679 };
680 let stem_cow: Cow<'_, str> = rel
681 .file_stem()
682 .map(OsStr::to_string_lossy)
683 .unwrap_or(Cow::Borrowed(""));
684 if !stem_cow.eq_ignore_ascii_case(README_STEM) && !stem_cow.eq_ignore_ascii_case(INDEX_STEM) {
685 push_route_segment(&mut route, &stem_cow);
686 }
687 if route.is_empty() {
688 route.push_str(ROUTE_ROOT);
689 }
690 (route, section)
691}
692
693fn format_section_label(raw: &str) -> String {
703 let mut out: String = String::with_capacity(raw.len());
704 for part in raw.split(['-', '_']) {
705 let trimmed: &str = part.trim();
706 if trimmed.is_empty() {
707 continue;
708 }
709 let mut chars: Chars<'_> = trimmed.chars();
710 if let Some(first) = chars.next() {
711 if !out.is_empty() {
712 out.push(' ');
713 }
714 for up in first.to_uppercase() {
715 out.push(up);
716 }
717 out.push_str(chars.as_str());
718 }
719 }
720 if out.is_empty() {
721 out.push_str(DEFAULT_SECTION);
722 }
723 out
724}
725
726fn title_from_route(route: &str) -> String {
736 let trimmed: &str = route.trim_matches('/');
737 if trimmed.is_empty() {
738 return DEFAULT_DOC_TITLE.to_string();
739 }
740 trimmed
741 .rsplit('/')
742 .next()
743 .map(format_section_label)
744 .unwrap_or_else(|| DEFAULT_DOC_TITLE.to_string())
745}