use crate::{RepoPath, include::DefinitionEntry};
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum IndexEntry {
Document {
title: String,
id: String,
path: RepoPath,
description: Option<String>,
},
File {
name: String,
},
Directory {
name: String,
},
}
pub fn render(heading: &str, entries: &[IndexEntry]) -> String {
let mut out = format!("# {heading}\n");
if entries.is_empty() {
return out;
}
out.push('\n');
let mut definitions = Vec::new();
for entry in entries {
match entry {
IndexEntry::Document {
title,
id,
path,
description,
} => {
out.push_str(&format!("- [{}][sokf:{id}]", one_line(title)));
if let Some(d) = description {
out.push_str(" - ");
out.push_str(&one_line(d));
}
out.push('\n');
definitions.push(DefinitionEntry {
label: format!("sokf:{id}"),
path: path.clone(),
slug: None,
});
}
IndexEntry::File { name } => out.push_str(&format!("- [{name}]({name}.md)\n")),
IndexEntry::Directory { name } => {
out.push_str(&format!("- [{name}/]({name}/index.md)\n"));
}
}
}
definitions.sort();
definitions.dedup();
if !definitions.is_empty() {
out.push('\n');
out.push_str(&crate::include::render_definitions(&definitions));
}
out
}
fn one_line(text: &str) -> String {
text.lines().collect::<Vec<_>>().join(" ")
}
#[cfg(test)]
mod tests {
use super::*;
fn p(s: &str) -> RepoPath {
RepoPath::parse(s).unwrap()
}
fn doc(title: &str, id: &str, path: &str, description: Option<&str>) -> IndexEntry {
IndexEntry::Document {
title: title.into(),
id: id.into(),
path: p(path),
description: description.map(str::to_string),
}
}
#[test]
fn renders_the_example_of_spec_9() {
let entries = vec![
doc(
"Executor",
"executor",
"/knowledge/core/executor.md",
Some("Applies planned actions."),
),
doc(
"Planner",
"planner",
"/knowledge/core/planner.md",
Some("Pure planning stage. No filesystem writes."),
),
IndexEntry::Directory {
name: "plugins".into(),
},
];
assert_eq!(
render("core", &entries),
"# core\n\n\
- [Executor][sokf:executor] - Applies planned actions.\n\
- [Planner][sokf:planner] - Pure planning stage. No filesystem writes.\n\
- [plugins/](plugins/index.md)\n\n\
<!-- sokf:links -->\n\n\
[sokf:executor]: /knowledge/core/executor.md\n\
[sokf:planner]: /knowledge/core/planner.md\n"
);
}
#[test]
fn each_entry_form_and_the_empty_cases() {
assert_eq!(render("schemas", &[]), "# schemas\n");
let entries = vec![
IndexEntry::Directory {
name: "core".into(),
},
IndexEntry::File {
name: "core".into(),
},
];
assert_eq!(
render("k", &entries),
"# k\n\n- [core/](core/index.md)\n- [core](core.md)\n"
);
let entries = vec![
doc("Zed\nTwo", "zed", "/k/zed.md", None),
doc("A", "a", "/k/a.md", Some("line one\nline two\n")),
];
assert_eq!(
render("k", &entries),
"# k\n\n- [Zed Two][sokf:zed]\n- [A][sokf:a] - line one line two\n\n\
<!-- sokf:links -->\n\n[sokf:a]: /k/a.md\n[sokf:zed]: /k/zed.md\n"
);
}
}