use super::*;
#[must_use]
pub fn parse_markdown_page(route: &str, default_section: &str, raw: &str) -> DocPage {
let (frontmatter, body): (DocFrontmatter, &str) = split_frontmatter(raw);
parse_markdown_page_with_frontmatter(route, default_section, frontmatter, body)
}
fn parse_markdown_page_with_frontmatter(
route: &str,
default_section: &str,
frontmatter: DocFrontmatter,
body: &str,
) -> DocPage {
let mut blocks: Vec<DocBlock> = Vec::with_capacity((body.len() / 160).clamp(8, 256));
let mut toc: Vec<DocTocItem> = Vec::with_capacity((body.len() / 512).clamp(4, 32));
let mut seen_slugs: BTreeMap<String, usize> = BTreeMap::new();
let mut active_heading: Option<(u8, Option<CowStr<'_>>)> = None;
let mut first_h1_title: Option<String> = None;
let mut in_paragraph: bool = false;
let mut list_stack: Vec<String> = Vec::new();
let mut blockquote_depth: usize = 0;
let mut in_table: bool = false;
let mut in_table_head: bool = false;
let mut in_table_cell: bool = false;
let mut table_headers: Vec<String> = Vec::new();
let mut table_rows: Vec<Vec<String>> = Vec::new();
let mut current_row: Vec<String> = Vec::new();
let mut active_code_lang: Option<String> = None;
let mut active_image_src: Option<String> = None;
let mut image_alt_buf: String = String::new();
let mut buffer: String = String::with_capacity(256);
let parser: Parser<'_> = Parser::new_ext(body, Options::all());
for event in parser {
match event {
Event::Start(Tag::Heading { level, id, .. }) => {
active_heading = Some((heading_level_num(level), id));
buffer.clear();
}
Event::End(TagEnd::Heading(_)) => {
if let Some((level, custom_id)) = active_heading.take() {
let text: String = buffer.trim().to_string();
if !text.is_empty() {
if level == 1 && first_h1_title.is_none() {
first_h1_title = Some(text.clone());
}
let raw_slug: String = custom_id
.as_deref()
.map(slugify)
.filter(|s: &String| !s.is_empty())
.unwrap_or_else(|| slugify(&text));
let slug: String = deduplicate_slug(raw_slug, &mut seen_slugs);
if (2..=4).contains(&level) {
toc.push(DocTocItem::new(level, slug.clone(), text.clone()));
}
blocks.push(DocBlock::Heading { level, slug, text });
}
}
buffer.clear();
}
Event::Start(Tag::BlockQuote(_)) => {
blockquote_depth += 1;
}
Event::End(TagEnd::BlockQuote(_)) => {
blockquote_depth = blockquote_depth.saturating_sub(1);
}
Event::Start(Tag::Table(_)) => {
in_table = true;
table_headers.clear();
table_rows.clear();
}
Event::End(TagEnd::Table) => {
if in_table {
in_table = false;
let headers: Vec<String> = take(&mut table_headers);
let rows: Vec<Vec<String>> = take(&mut table_rows);
if !headers.is_empty() || !rows.is_empty() {
blocks.push(DocBlock::Table { headers, rows });
}
}
}
Event::Start(Tag::TableHead) => {
in_table_head = true;
current_row.clear();
}
Event::End(TagEnd::TableHead) => {
in_table_head = false;
table_headers = take(&mut current_row);
}
Event::Start(Tag::TableRow) => {
current_row.clear();
}
Event::End(TagEnd::TableRow) => {
if !in_table_head {
table_rows.push(take(&mut current_row));
}
}
Event::Start(Tag::TableCell) => {
in_table_cell = true;
buffer.clear();
}
Event::End(TagEnd::TableCell) => {
if in_table_cell {
in_table_cell = false;
current_row.push(buffer.trim().to_string());
}
buffer.clear();
}
Event::Start(Tag::Paragraph) => {
if list_stack.is_empty() {
in_paragraph = true;
buffer.clear();
}
}
Event::End(TagEnd::Paragraph) => {
if in_paragraph {
in_paragraph = false;
let text: String = buffer.trim().to_string();
if !text.is_empty() {
if blockquote_depth > 0 {
blocks.push(DocBlock::BlockQuote(text));
} else {
blocks.push(DocBlock::Paragraph(text));
}
}
buffer.clear();
} else if let Some(top) = list_stack.last_mut()
&& !top.is_empty()
{
top.push(' ');
}
}
Event::Start(Tag::Item) => {
if let Some(parent_text) = list_stack.last_mut() {
let trimmed: String = parent_text.trim().to_string();
if !trimmed.is_empty() {
blocks.push(DocBlock::ListItem(trimmed));
parent_text.clear();
}
}
list_stack.push(String::new());
}
Event::End(TagEnd::Item) => {
if let Some(item_buf) = list_stack.pop() {
let text: String = item_buf.trim().to_string();
if !text.is_empty() {
blocks.push(DocBlock::ListItem(text));
}
}
}
Event::Start(Tag::CodeBlock(kind)) => {
let lang: String = match kind {
CodeBlockKind::Fenced(tag) => {
let trimmed: &str = tag.split_whitespace().next().unwrap_or("");
if trimmed.is_empty() {
DEFAULT_CODE_LANG.to_string()
} else {
trimmed.to_string()
}
}
CodeBlockKind::Indented => DEFAULT_CODE_LANG.to_string(),
};
active_code_lang = Some(lang);
buffer.clear();
}
Event::End(TagEnd::CodeBlock) => {
if let Some(language) = active_code_lang.take() {
let code: String = buffer.trim_end().to_string();
blocks.push(DocBlock::Code { language, code });
}
buffer.clear();
}
Event::Start(Tag::Image { dest_url, .. }) => {
active_image_src = Some(dest_url.into_string());
image_alt_buf.clear();
}
Event::End(TagEnd::Image) => {
if let Some(src) = active_image_src.take() {
let alt: String = image_alt_buf.trim().to_string();
image_alt_buf.clear();
if !src.is_empty() {
blocks.push(DocBlock::Image { alt, src });
}
}
}
Event::TaskListMarker(checked) => {
let marker: &str = if checked { "[x] " } else { "[ ] " };
if let Some(top) = list_stack.last_mut() {
top.push_str(marker);
} else {
buffer.push_str(marker);
}
}
Event::Rule => {
blocks.push(DocBlock::HorizontalRule);
}
Event::Text(text) | Event::Code(text) => {
if active_image_src.is_some() {
image_alt_buf.push_str(&text);
} else if !list_stack.is_empty()
&& active_code_lang.is_none()
&& active_heading.is_none()
&& !in_table_cell
{
if let Some(top) = list_stack.last_mut() {
top.push_str(&text);
}
} else {
buffer.push_str(&text);
}
}
Event::SoftBreak | Event::HardBreak => {
let sep: char = if active_code_lang.is_some() {
'\n'
} else {
' '
};
if active_image_src.is_some() {
image_alt_buf.push(sep);
} else if !list_stack.is_empty()
&& active_code_lang.is_none()
&& active_heading.is_none()
&& !in_table_cell
{
if let Some(top) = list_stack.last_mut() {
top.push(sep);
}
} else {
buffer.push(sep);
}
}
_ => {}
}
}
let DocFrontmatter {
title: fm_title,
order: fm_order,
tagline: fm_tagline,
description: fm_description,
section: fm_section,
updated: fm_updated,
date: fm_date,
category: fm_categories,
index: fm_index,
expanded: fm_expanded,
dir: fm_dir,
password: fm_password,
home: fm_home,
hero_text: fm_hero_text,
actions: fm_actions,
stats: fm_stats,
features: fm_features,
sidebar: fm_sidebar,
..
} = frontmatter;
if toc.is_empty() {
for b in blocks.iter() {
if let DocBlock::Heading { level, slug, text } = b
&& *level == 1
{
toc.push(DocTocItem::new(*level, slug.clone(), text.clone()));
}
}
}
let fallback_title: String = first_h1_title
.or_else(|| {
toc.first()
.map(|item: &DocTocItem| item.get_title().clone())
})
.unwrap_or_else(|| title_from_route(route));
let title: String = fm_title.unwrap_or(fallback_title);
if toc
.first()
.is_some_and(|item: &DocTocItem| item.get_title().trim().eq_ignore_ascii_case(title.trim()))
{
let _: DocTocItem = toc.remove(0);
}
let dir_order: Option<i32> = fm_dir.as_ref().and_then(DocDirFrontmatter::get_order);
let dir_text: Option<String> = fm_dir
.as_ref()
.and_then(|d: &DocDirFrontmatter| d.try_get_text().clone())
.filter(|s: &String| !s.trim().is_empty());
let dir_collapsible: Option<bool> =
fm_dir.as_ref().and_then(DocDirFrontmatter::get_collapsible);
let default_order: i32 = if route == ROUTE_ROOT || fm_home {
-1000
} else {
100
};
let order: i32 = fm_order.or(dir_order).unwrap_or(default_order);
let section: String = fm_section.unwrap_or_else(|| default_section.to_string());
let summary: String = fm_tagline.or(fm_description).unwrap_or_else(|| {
blocks
.iter()
.find_map(|b: &DocBlock| match b {
DocBlock::Paragraph(p) | DocBlock::BlockQuote(p) => Some(p.clone()),
_ => None,
})
.unwrap_or_default()
});
let resolved_updated: Option<String> = fm_updated.or_else(|| fm_date.clone());
let mut page: DocPage = DocPage::new(
route.to_string(),
title,
order,
section,
summary,
blocks,
toc,
);
page.set_markdown_body(body.to_string());
page.set_updated(resolved_updated);
page.set_home_meta(fm_home, fm_hero_text, fm_actions, fm_stats, fm_features);
page.set_hide_sidebar(fm_sidebar == Some(false));
page.set_dir_meta(
fm_index == Some(false),
fm_expanded,
dir_order,
dir_text,
dir_collapsible,
);
page.set_page_meta(
fm_password.filter(|pw: &String| !pw.trim().is_empty()),
fm_date,
fm_categories,
);
page
}
#[must_use]
pub fn unique_locales(locales: &[DocLocaleConfig]) -> Vec<DocLocaleConfig> {
let mut seen: BTreeSet<String> = BTreeSet::new();
let mut out: Vec<DocLocaleConfig> = Vec::with_capacity(locales.len());
for loc in locales.iter() {
let key: String = loc.get_dir().trim().to_ascii_lowercase();
if key.is_empty() {
continue;
}
if seen.insert(key) {
out.push(loc.clone());
}
}
out
}
#[must_use]
pub fn load_site_config(src_dir: &Path) -> Option<DocSiteConfig> {
let mut candidates: Vec<PathBuf> = vec![src_dir.join(README_FILENAME)];
if let Some(parent) = src_dir.parent() {
candidates.push(parent.join(README_FILENAME));
}
let mut fallback: Option<DocSiteConfig> = None;
for candidate in candidates.into_iter() {
if !candidate.is_file() {
continue;
}
let Ok(raw) = fs::read_to_string(&candidate) else {
continue;
};
let (fm, _): (DocFrontmatter, &str) = split_frontmatter(&raw);
let has_locales: bool = !fm.locales.is_empty();
let has_site: bool = fm.site.is_some();
if has_locales {
return Some(DocSiteConfig {
site: fm.site.unwrap_or_default(),
locales: fm.locales,
});
}
if has_site && fallback.is_none() {
fallback = Some(DocSiteConfig {
site: fm.site.unwrap_or_default(),
locales: Vec::new(),
});
}
}
fallback
}
pub fn load_locale_site(
src_dir: &Path,
cfg: &DocSiteConfig,
locale: &DocLocaleConfig,
exclude_dir: Option<&Path>,
) -> io::Result<DocSite> {
let locale_dir_name: &str = locale.get_dir().trim();
let content_dir: PathBuf = if locale_dir_name.is_empty() {
src_dir.to_path_buf()
} else {
let joined: PathBuf = src_dir.join(locale_dir_name);
if joined.is_dir() {
joined
} else {
src_dir.to_path_buf()
}
};
let title_override: Option<&str> = locale
.try_get_title()
.as_deref()
.or_else(|| cfg.get_site().try_get_title().as_deref());
let mut site: DocSite = load_doc_site_excluding(&content_dir, title_override, exclude_dir)?;
if let Some(desc) = locale
.try_get_description()
.as_deref()
.or_else(|| cfg.get_site().try_get_description().as_deref())
&& !desc.trim().is_empty()
{
site.tagline = desc.trim().to_string();
}
site.apply_locale_metadata(cfg, Some(locale));
Ok(site)
}
pub fn load_doc_site(root_dir: &Path) -> io::Result<DocSite> {
load_doc_site_with_options(root_dir, None)
}
pub fn load_doc_site_with_options(
root_dir: &Path,
title_override: Option<&str>,
) -> io::Result<DocSite> {
load_doc_site_excluding(root_dir, title_override, None)
}
pub(crate) fn load_doc_site_excluding(
root_dir: &Path,
title_override: Option<&str>,
exclude_dir: Option<&Path>,
) -> io::Result<DocSite> {
if !root_dir.exists() {
return Err(Error::new(
ErrorKind::NotFound,
root_dir.display().to_string(),
));
}
let canonical_exclude: Option<PathBuf> =
exclude_dir.map(|p: &Path| fs::canonicalize(p).unwrap_or_else(|_| p.to_path_buf()));
let mut files: Vec<PathBuf> = Vec::new();
collect_markdown_files(root_dir, canonical_exclude.as_deref(), &mut files)?;
files.sort();
let mut pages: Vec<DocPage> = Vec::with_capacity(files.len());
let mut seen_routes: BTreeSet<String> = BTreeSet::new();
let mut detected_site_cfg: Option<DocSiteConfig> = None;
let mut root_sidebar_ranks: HashMap<String, i32> = HashMap::new();
let mut dir_sidebar_ranks: HashMap<(String, String), i32> = HashMap::new();
let mut detected_title: Option<String> = None;
let mut detected_tagline: Option<String> = None;
for file_path in files.into_iter() {
let raw: String = fs::read_to_string(&file_path)?;
let rel: &Path = file_path.strip_prefix(root_dir).unwrap_or(&file_path);
let (mut route, section): (String, String) = route_and_section_from_rel_path(rel);
let (mut frontmatter, body): (DocFrontmatter, &str) = split_frontmatter(&raw);
if !frontmatter.sidebar_order.is_empty() {
let parent_rel: String = rel
.parent()
.map(|p: &Path| {
p.iter()
.map(|seg: &OsStr| slugify(&seg.to_string_lossy()))
.collect::<Vec<String>>()
.join("/")
})
.unwrap_or_default();
for (rank_idx, entry_name) in frontmatter.sidebar_order.iter().enumerate() {
let key: String = slugify(entry_name);
if key.is_empty() {
continue;
}
let rank_val: i32 = (rank_idx as i32) * 10 - 500;
if parent_rel.is_empty() {
let _: Option<i32> = root_sidebar_ranks.insert(key, rank_val);
} else {
let _: Option<i32> =
dir_sidebar_ranks.insert((parent_rel.clone(), key), rank_val);
}
}
}
if route == ROUTE_ROOT {
let fm_locales: Vec<DocLocaleConfig> = take(&mut frontmatter.locales);
if let Some(site_cfg) = frontmatter.site.take() {
if detected_title.is_none() {
detected_title = site_cfg.try_get_title().clone();
}
if detected_tagline.is_none() {
detected_tagline = site_cfg.try_get_description().clone();
}
detected_site_cfg = Some(DocSiteConfig {
site: site_cfg,
locales: fm_locales,
});
} else if !fm_locales.is_empty() {
detected_site_cfg = Some(DocSiteConfig {
site: DocSiteFrontmatter::default(),
locales: fm_locales,
});
}
}
if seen_routes.contains(&route) {
let stem: String = file_path
.file_stem()
.map(|s: &OsStr| slugify(&s.to_string_lossy()))
.filter(|s: &String| !s.is_empty())
.unwrap_or_else(|| FALLBACK_SLUG_PREFIX.to_string());
let base_route: String = if route == ROUTE_ROOT {
format!("/{stem}")
} else {
format!("{route}-{stem}")
};
route = base_route.clone();
let mut suffix: usize = 2;
while seen_routes.contains(&route) {
route = format!("{base_route}-{suffix}");
suffix += 1;
}
}
let _: bool = seen_routes.insert(route.clone());
let rel_normalized: String = rel
.components()
.map(|c: path::Component<'_>| c.as_os_str().to_string_lossy().into_owned())
.collect::<Vec<String>>()
.join("/");
let stem_is_index: bool = rel
.file_stem()
.and_then(OsStr::to_str)
.is_some_and(|s: &str| {
s.eq_ignore_ascii_case(README_STEM) || s.eq_ignore_ascii_case(INDEX_STEM)
});
let mut parsed_page: DocPage =
parse_markdown_page_with_frontmatter(&route, §ion, frontmatter, body);
parsed_page.set_source_meta(rel_normalized, stem_is_index);
pages.push(parsed_page);
}
let mut dir_passwords: HashMap<String, String> = HashMap::new();
for page in pages.iter() {
if page.get_is_dir_index()
&& let Some(pw) = page.try_get_password().as_deref()
&& !pw.trim().is_empty()
{
let dir_key: String = page.directory_path();
if !dir_key.is_empty() {
let _: Option<String> = dir_passwords.insert(dir_key, pw.trim().to_string());
}
}
}
if !dir_passwords.is_empty() {
for page in pages.iter_mut() {
if page.try_get_password().is_some() {
continue;
}
let dir_key: String = page.directory_path();
let mut cur: &str = dir_key.as_str();
while !cur.is_empty() {
if let Some(pw) = dir_passwords.get(cur) {
page.set_inherited_password(pw.clone());
break;
}
match cur.rsplit_once('/') {
Some((parent, _)) => cur = parent,
None => break,
}
}
}
}
if !root_sidebar_ranks.is_empty() || !dir_sidebar_ranks.is_empty() {
for page in pages.iter_mut() {
if page.get_route() == ROUTE_ROOT || page.get_order() != 100 {
continue;
}
let computed_order: Option<i32> = {
let trimmed: &str = page.get_route().trim_matches('/');
let mut segs: Vec<&str> = trimmed.split('/').collect();
let mut found: Option<i32> = None;
if let Some(last) = segs.pop() {
let parent_key: String = segs.join("/");
if !parent_key.is_empty()
&& let Some(&rank) = dir_sidebar_ranks.get(&(parent_key, last.to_string()))
{
found = Some(rank);
}
}
if found.is_none()
&& let Some(first_seg) = trimmed.split('/').next()
&& let Some(&rank) = root_sidebar_ranks.get(first_seg)
{
let is_group_index: bool = !trimmed.contains('/');
found = Some(if is_group_index { rank } else { rank + 1 });
}
found
};
if let Some(new_order) = computed_order {
page.order = new_order;
}
}
}
pages.sort_by(|a: &DocPage, b: &DocPage| {
let a_root_rank: i32 = a
.get_route()
.trim_matches('/')
.split('/')
.next()
.and_then(|seg: &str| root_sidebar_ranks.get(seg).copied())
.unwrap_or(i32::MAX);
let b_root_rank: i32 = b
.get_route()
.trim_matches('/')
.split('/')
.next()
.and_then(|seg: &str| root_sidebar_ranks.get(seg).copied())
.unwrap_or(i32::MAX);
if a.get_route() == ROUTE_ROOT && b.get_route() != ROUTE_ROOT {
return Ordering::Less;
}
if b.get_route() == ROUTE_ROOT && a.get_route() != ROUTE_ROOT {
return Ordering::Greater;
}
a_root_rank
.cmp(&b_root_rank)
.then_with(|| {
section_sort_rank(a.get_section()).cmp(§ion_sort_rank(b.get_section()))
})
.then_with(|| a.get_section().cmp(b.get_section()))
.then_with(|| a.get_order().cmp(&b.get_order()))
.then_with(|| a.get_route().cmp(b.get_route()))
});
let fallback_site_title: String = root_dir
.file_name()
.map(|s: &OsStr| s.to_string_lossy().into_owned())
.filter(|raw: &String| {
raw.len() > 2
&& !raw.eq_ignore_ascii_case(GENERIC_DOCS_DIR)
&& !raw.eq_ignore_ascii_case(GENERIC_SRC_DIR)
&& raw != "."
&& raw != ".."
})
.map(|raw: String| format_section_label(&raw))
.unwrap_or_else(|| DOCS_SITE_TITLE.to_string());
let site_title: String = title_override
.map(str::to_string)
.or(detected_title)
.unwrap_or(fallback_site_title);
let site_tagline: String = detected_tagline.unwrap_or_else(|| DOCS_SITE_TAGLINE.to_string());
let mut site: DocSite = DocSite::new(site_title, site_tagline, pages);
if let Some(cfg) = detected_site_cfg.as_ref() {
site.apply_locale_metadata(cfg, None);
} else {
site.release_marker = EUV_DOCS_RELEASE_MARKER.to_string();
}
Ok(site)
}
pub(crate) fn section_sort_rank(section: &str) -> u8 {
if section.eq_ignore_ascii_case(DEFAULT_SECTION) {
0
} else if section.eq_ignore_ascii_case(GUIDE_SECTION) {
1
} else {
2
}
}
fn split_frontmatter(raw: &str) -> (DocFrontmatter, &str) {
let trimmed: &str = raw.trim_start_matches('\u{feff}');
let Some(rest) = trimmed.strip_prefix(FRONTMATTER_DELIMITER) else {
return (DocFrontmatter::default(), trimmed);
};
let rest: &str = rest
.strip_prefix("\r\n")
.or_else(|| rest.strip_prefix('\n'))
.unwrap_or(rest);
let mut offset: usize = 0;
for line in rest.split_inclusive('\n') {
let clean: &str = line.trim_end_matches(['\r', '\n']);
if clean.trim() == FRONTMATTER_DELIMITER {
let yaml_slice: &str = &rest[..offset];
let body_slice: &str = &rest[(offset + line.len())..];
let parsed: DocFrontmatter = from_str::<DocFrontmatter>(yaml_slice)
.unwrap_or_else(|_| parse_frontmatter_fallback(yaml_slice));
return (parsed, body_slice);
}
offset += line.len();
}
(DocFrontmatter::default(), trimmed)
}
fn parse_frontmatter_fallback(yaml_slice: &str) -> DocFrontmatter {
let mut fm: DocFrontmatter = DocFrontmatter::default();
let Ok(Value::Object(map)) = from_str::<Value>(yaml_slice) else {
return fm;
};
if let Some(s) = map.get("title").and_then(Value::as_str) {
fm.title = Some(s.to_string());
}
if let Some(n) = map.get("order").and_then(Value::as_i64) {
fm.order = Some(n as i32);
}
if let Some(s) = map.get("tagline").and_then(Value::as_str) {
fm.tagline = Some(s.to_string());
}
if let Some(s) = map.get("description").and_then(Value::as_str) {
fm.description = Some(s.to_string());
}
if let Some(s) = map.get("section").and_then(Value::as_str) {
fm.section = Some(s.to_string());
}
if let Some(s) = map.get("updated").and_then(Value::as_str) {
fm.updated = Some(s.to_string());
}
if let Some(s) = map.get("date").and_then(Value::as_str) {
fm.date = Some(s.to_string());
}
if let Some(b) = map.get("index").and_then(Value::as_bool) {
fm.index = Some(b);
}
if let Some(b) = map.get("expanded").and_then(Value::as_bool) {
fm.expanded = Some(b);
}
if let Some(b) = map.get("home").and_then(Value::as_bool) {
fm.home = b;
}
if let Some(b) = map.get("sidebar").and_then(Value::as_bool) {
fm.sidebar = Some(b);
}
if let Some(pw) = map.get("password") {
let pw_str: Option<String> = match pw {
Value::String(s) => Some(s.clone()),
Value::Number(n) => Some(n.to_string()),
_ => None,
};
fm.password = pw_str;
}
if let Some(cat) = map.get("category") {
match cat {
Value::String(s) => fm.category.push(s.clone()),
Value::Array(arr) => {
for item in arr.iter() {
if let Some(s) = item.as_str() {
fm.category.push(s.to_string());
}
}
}
_ => {}
}
}
if let Some(Value::Object(dir_map)) = map.get("dir") {
let mut dir_fm: DocDirFrontmatter = DocDirFrontmatter::default();
if let Some(n) = dir_map.get("order").and_then(Value::as_i64) {
dir_fm.order = Some(n as i32);
}
if let Some(s) = dir_map.get("text").and_then(Value::as_str) {
dir_fm.text = Some(s.to_string());
}
if let Some(b) = dir_map.get("link").and_then(Value::as_bool) {
dir_fm.link = Some(b);
}
if let Some(b) = dir_map.get("collapsible").and_then(Value::as_bool) {
dir_fm.collapsible = Some(b);
}
fm.dir = Some(dir_fm);
}
fm
}
pub(crate) fn heading_level_num(level: HeadingLevel) -> u8 {
match level {
HeadingLevel::H1 => 1,
HeadingLevel::H2 => 2,
HeadingLevel::H3 => 3,
HeadingLevel::H4 => 4,
HeadingLevel::H5 => 5,
HeadingLevel::H6 => 6,
}
}
fn push_slugified(out: &mut String, input: &str) {
let start_len: usize = out.len();
let mut prev_dash: bool = false;
for ch in input.chars() {
if ch.is_ascii_alphanumeric() {
out.push(ch.to_ascii_lowercase());
prev_dash = false;
} else if ch.is_alphanumeric() {
for lower in ch.to_lowercase() {
out.push(lower);
}
prev_dash = false;
} else if !prev_dash && out.len() > start_len {
out.push('-');
prev_dash = true;
}
}
while out.len() > start_len && out.ends_with('-') {
let _: Option<char> = out.pop();
}
}
pub(crate) fn slugify(input: &str) -> String {
let mut out: String = String::with_capacity(input.len());
push_slugified(&mut out, input);
out
}
pub(crate) fn deduplicate_slug(raw_slug: String, seen: &mut BTreeMap<String, usize>) -> String {
let base: String = if raw_slug.is_empty() {
FALLBACK_SLUG_PREFIX.to_string()
} else {
raw_slug
};
if let Some(count) = seen.get_mut(&base) {
*count += 1;
return format!("{base}-{}", *count);
}
let _: Option<usize> = seen.insert(base.clone(), 1);
base
}
fn collect_markdown_files(
dir: &Path,
exclude_dir: Option<&Path>,
out: &mut Vec<PathBuf>,
) -> io::Result<()> {
for entry in fs::read_dir(dir)? {
let entry_val: DirEntry = entry?;
let path: PathBuf = entry_val.path();
let is_dir: bool = match entry_val.file_type() {
Ok(ft) if ft.is_dir() => true,
Ok(ft) if ft.is_file() => false,
_ => path.is_dir(),
};
if is_dir {
let file_name: OsString = entry_val.file_name();
let name: Cow<'_, str> = file_name.to_string_lossy();
if should_skip_dir(&name) {
continue;
}
if let Some(excluded) = exclude_dir {
let candidate: PathBuf = fs::canonicalize(&path).unwrap_or_else(|_| path.clone());
if candidate == excluded || candidate.starts_with(excluded) {
continue;
}
}
collect_markdown_files(&path, exclude_dir, out)?;
} else if path
.extension()
.and_then(|s: &OsStr| s.to_str())
.is_some_and(|ext: &str| ext.eq_ignore_ascii_case(MARKDOWN_EXT))
{
out.push(path);
}
}
Ok(())
}
pub(crate) fn should_skip_dir(name: &str) -> bool {
name.starts_with('.')
|| IGNORED_SCAN_DIRS
.iter()
.any(|ignored: &&str| name.eq_ignore_ascii_case(ignored))
}
fn push_route_segment(out: &mut String, seg: &str) {
out.push('/');
let start_len: usize = out.len();
push_slugified(out, seg);
if out.len() == start_len {
for ch in seg.chars() {
out.push(ch.to_ascii_lowercase());
}
}
}
fn route_and_section_from_rel_path(rel: &Path) -> (String, String) {
let mut comps: Peekable<Components<'_>> = rel.components().peekable();
let Some(first_comp) = comps.next() else {
return (ROUTE_ROOT.to_string(), DEFAULT_SECTION.to_string());
};
let mut route: String = String::with_capacity(rel.as_os_str().len() + 1);
let section: String = if comps.peek().is_some() {
let first_cow: Cow<'_, str> = first_comp.as_os_str().to_string_lossy();
let sec: String = format_section_label(&first_cow);
push_route_segment(&mut route, &first_cow);
while let Some(comp) = comps.next() {
if comps.peek().is_some() {
let seg_cow: Cow<'_, str> = comp.as_os_str().to_string_lossy();
push_route_segment(&mut route, &seg_cow);
}
}
sec
} else {
DEFAULT_SECTION.to_string()
};
let stem_cow: Cow<'_, str> = rel
.file_stem()
.map(OsStr::to_string_lossy)
.unwrap_or(Cow::Borrowed(""));
if !stem_cow.eq_ignore_ascii_case(README_STEM) && !stem_cow.eq_ignore_ascii_case(INDEX_STEM) {
push_route_segment(&mut route, &stem_cow);
}
if route.is_empty() {
route.push_str(ROUTE_ROOT);
}
(route, section)
}
fn format_section_label(raw: &str) -> String {
let mut out: String = String::with_capacity(raw.len());
for part in raw.split(['-', '_']) {
let trimmed: &str = part.trim();
if trimmed.is_empty() {
continue;
}
let mut chars: Chars<'_> = trimmed.chars();
if let Some(first) = chars.next() {
if !out.is_empty() {
out.push(' ');
}
for up in first.to_uppercase() {
out.push(up);
}
out.push_str(chars.as_str());
}
}
if out.is_empty() {
out.push_str(DEFAULT_SECTION);
}
out
}
fn title_from_route(route: &str) -> String {
let trimmed: &str = route.trim_matches('/');
if trimmed.is_empty() {
return DEFAULT_DOC_TITLE.to_string();
}
trimmed
.rsplit('/')
.next()
.map(format_section_label)
.unwrap_or_else(|| DEFAULT_DOC_TITLE.to_string())
}