use std::path::Path;
use super::{Graph, NodeKey, NodeKind};
use crate::{
Error, Model, PathArg, RepoPath, Result,
model::{KeyEntry, KeyIndex, split_store},
};
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Start {
Container(RepoPath),
Node(NodeKey),
Outside(RepoPath),
}
impl Start {
pub fn key(&self) -> NodeKey {
match self {
Start::Container(p) | Start::Outside(p) => NodeKey::Path(p.clone()),
Start::Node(k) => k.clone(),
}
}
pub fn path(&self) -> Option<&RepoPath> {
match self {
Start::Container(p) | Start::Outside(p) => Some(p),
Start::Node(k) => k.path(),
}
}
}
pub fn is_key_reference(arg: &str) -> bool {
let arg = arg.strip_prefix("sokf:").unwrap_or(arg);
arg.split_once('#')
.is_some_and(|(head, _)| split_store(head).1.is_empty())
}
pub fn key_entry(model: &Model, keys: &KeyIndex, arg: &str) -> Option<(KeyEntry, String)> {
let written = arg.split_once('#')?.1;
if written.is_empty() {
return None;
}
let path = match paths_of_reference(model, Some(keys), arg).as_slice() {
[one] => one.clone(),
[] => match document_scoped(model, keys, arg).as_slice() {
[(one, _)] => one.clone(),
_ => return None,
},
_ => return None,
};
[written.to_string(), crate::markdown::slug(written)]
.into_iter()
.find_map(|slug| {
let entry = keys.document.get(&(path.clone(), slug.clone()))?.first()?;
Some((entry.clone(), slug))
})
}
fn document_scoped(model: &Model, keys: &KeyIndex, arg: &str) -> Vec<(RepoPath, String)> {
if !is_key_reference(arg) || !paths_of_reference(model, Some(keys), arg).is_empty() {
return Vec::new();
}
let reference = arg.strip_prefix("sokf:").unwrap_or(arg);
let Some((head, written)) = reference.split_once('#') else {
return Vec::new();
};
let stores = stores_of(model, split_store(head).0);
let slugs = [written.to_string(), crate::markdown::slug(written)];
let mut found: Vec<(RepoPath, String)> = keys
.document
.keys()
.filter(|(p, s)| {
slugs.contains(s) && model.knowledge_of(p).is_some_and(|k| stores.contains(&k))
})
.cloned()
.collect();
found.sort();
found.dedup_by(|a, b| a.0 == b.0);
found
}
fn stores_of(model: &Model, store: Option<&str>) -> Vec<usize> {
match store {
None => (0..model.knowledges.len()).collect(),
Some(s) => model.stores_named(s),
}
}
pub(super) fn note(model: &Model, keys: Option<&KeyIndex>, arg: &str) -> Option<String> {
let [(path, slug)] = document_scoped(model, keys?, arg).try_into().ok()?;
let reference = key_reference(model, &path, &slug)?;
let id = reference.split_once('#')?.0;
Some(format!(
"`{arg}` is unique only within `{id}`, so link it as `{reference}`"
))
}
fn key_reference(model: &Model, path: &RepoPath, slug: &str) -> Option<String> {
let (k, id) = id_of(model, path)?;
let mut elsewhere = false;
for o in 0..model.knowledges.len() {
if model.ids(o, &id).into_iter().any(|p| &p != path) {
if o == k {
return None;
}
elsewhere = true;
}
}
Some(if elsewhere {
format!("{}:{id}#{slug}", model.store_name(k)?)
} else {
format!("{id}#{slug}")
})
}
fn id_of(model: &Model, path: &RepoPath) -> Option<(usize, String)> {
if let Some(found) = model.id_at(path) {
Some(found)
} else {
let k = model.knowledge_of(path)?;
let id = model.fallback.as_ref()?.fields(path)?.id?;
Some((k, id))
}
}
fn paths_of_reference(model: &Model, keys: Option<&KeyIndex>, arg: &str) -> Vec<RepoPath> {
let reference = arg.strip_prefix("sokf:").unwrap_or(arg);
let (head, fragment) = match reference.split_once('#') {
Some((h, f)) => (h, Some(f)),
None => (reference, None),
};
let (store, id) = split_store(head);
let stores = stores_of(model, store);
let mut paths: Vec<RepoPath> =
if id.is_empty() {
let (Some(keys), Some(key)) = (keys, fragment.filter(|f| !f.is_empty())) else {
return Vec::new();
};
[key.to_string(), crate::markdown::slug(key)]
.into_iter()
.flat_map(|key| {
keys.repository
.get(&key)
.into_iter()
.flatten()
.chain(stores.iter().flat_map(|&k| {
keys.knowledge.get(&(k, key.clone())).into_iter().flatten()
}))
.filter(|e| stores.contains(&e.knowledge))
.map(|e| e.path.clone())
.collect::<Vec<_>>()
})
.collect()
} else {
stores.iter().flat_map(|&k| model.ids(k, id)).collect()
};
paths.sort();
paths.dedup();
paths
}
fn qualified(model: &Model, arg: &str, paths: &[RepoPath]) -> String {
let key = is_key_reference(arg)
.then(|| arg.split_once('#').map(|(_, k)| k))
.flatten();
let forms: Vec<String> = paths
.iter()
.filter_map(|p| {
let (k, id) = id_of(model, p)?;
let store = model.store_name(k)?;
Some(match key {
Some(key) => format!("`{store}:#{key}`"),
None => format!("`{store}:{id}`"),
})
})
.collect();
if forms.len() == paths.len() {
format!(". Write {}", forms.join(" or "))
} else {
String::new()
}
}
fn join(paths: &[RepoPath]) -> String {
paths
.iter()
.map(RepoPath::as_str)
.collect::<Vec<_>>()
.join(", ")
}
pub fn resolve_id(model: &Model, keys: Option<&KeyIndex>, id: &str) -> Result<RepoPath> {
match paths_of_reference(model, keys, id).as_slice() {
[] => Err(Error::Locate(format!("`{id}` identifies no document"))),
[one] => Ok(one.clone()),
many => Err(Error::Locate(format!(
"`{id}` identifies more than one document: {}{}",
join(many),
qualified(model, id, many)
))),
}
}
#[expect(
clippy::case_sensitive_file_extension_comparisons,
reason = "a START that ends in a lowercase `.md` is path-shaped, as CLI-7_AC-28 says, so the comparison is case-sensitive on purpose"
)]
pub fn resolve_start(
graph: &mut Graph,
model: &Model,
keys: Option<&KeyIndex>,
cwd: &Path,
arg: &str,
) -> Result<Start> {
let path_shaped = arg.starts_with('.') || arg.ends_with('/') || arg.ends_with(".md");
let ids = if path_shaped {
Vec::new()
} else {
paths_of_reference(model, keys, arg)
};
let path = PathArg(arg).resolve(&model.tree.root, cwd);
match (ids.as_slice(), path) {
([_, ..], Some(p)) => Err(Error::Start(format!(
"`{arg}` is both an id ({}) and a path ({p})",
join(&ids)
))),
([_, _, ..], None) => Err(Error::Start(format!(
"`{arg}` identifies more than one document: {}{}",
join(&ids),
qualified(model, arg, &ids)
))),
([one], None) => Ok(key_start(graph, model, keys, arg, one)),
([], Some(p)) => Ok(path_start(graph, model, p)),
([], None) => {
let scoped = keys.map_or_else(Vec::new, |k| document_scoped(model, k, arg));
match scoped.as_slice() {
[(one, _)] => Ok(key_start(graph, model, keys, arg, one)),
[] => Err(Error::Start(format!(
"`{arg}` is neither an id nor a path in the repository"
))),
many => {
let forms: Vec<String> = many
.iter()
.map(|(p, slug)| match key_reference(model, p, slug) {
Some(r) => format!("`{r}`"),
None => p.to_string(),
})
.collect();
Err(Error::Start(format!(
"`{arg}` is a key of document scope that more than one document captures. Write {}",
capped(&forms)
)))
}
}
}
}
}
const LISTED: usize = 10;
fn capped(forms: &[String]) -> String {
let listed = forms[..forms.len().min(LISTED)].join(" or ");
match forms.len().saturating_sub(LISTED) {
0 => listed,
more => format!("{listed}, and {more} more"),
}
}
fn key_start(
graph: &Graph,
model: &Model,
keys: Option<&KeyIndex>,
arg: &str,
path: &RepoPath,
) -> Start {
Start::Node(
keys.and_then(|k| key_entry(model, k, arg))
.map(|(_, slug)| NodeKey::Key(format!("{path}#{slug}")))
.filter(|k| graph.node(k).is_some())
.unwrap_or_else(|| NodeKey::Path(path.clone())),
)
}
fn path_start(graph: &mut Graph, model: &Model, path: RepoPath) -> Start {
if model.tree.roots.contains(&path) {
return Start::Container(path);
}
if path.to_fs(&model.tree.root).is_dir() {
graph.ensure(path.clone(), NodeKind::Directory);
return if model.knowledge_of(&path).is_some() {
Start::Container(path)
} else {
Start::Outside(path)
};
}
let key = NodeKey::Path(path.clone());
if graph.node(&key).is_none() {
graph.ensure(path, NodeKind::File);
}
Start::Node(key)
}
#[cfg(test)]
mod tests {
use std::path::PathBuf;
use super::*;
use crate::{
graph::build,
test_support::{fresh_dir, model_at, write},
};
fn temp(name: &str) -> PathBuf {
let dir = fresh_dir(&format!("start-{name}"));
for (rel, text) in [
(
"knowledge/manifest.sokf.yaml",
"sokf: \"0.6\"\nname: k\nscope: test\n",
),
(
"knowledge/core/a.md",
"---\ntype: Note\nid: a\nresource: /src/a.rs\n---\n\n# A\n",
),
(
"knowledge/core/b.md",
"---\ntype: Note\nid: dup\n---\n\n# B\n",
),
("knowledge/c.md", "---\ntype: Note\nid: dup\n---\n\n# C\n"),
(
"knowledge/core.md",
"---\ntype: Note\nid: core\n---\n\n# Core\n",
),
(
"other/manifest.sokf.yaml",
"sokf: \"0.6\"\nname: o\nscope: test\n",
),
("other/n.md", "---\ntype: Note\nid: a\n---\n\n# N\n"),
("src/a.rs", ""),
("src/plain.rs", ""),
("docs/x.txt", ""),
] {
write(&dir, rel, text);
}
std::fs::create_dir_all(dir.join("knowledge/empty")).unwrap();
dir
}
fn p(s: &str) -> RepoPath {
RepoPath::parse(s).unwrap()
}
#[test]
fn each_reading_and_each_refusal() {
let dir = temp("reading");
let m = model_at(&dir, &["/knowledge"]);
let mut g = build(&m);
let mut start = |arg: &str, cwd: &Path| resolve_start(&mut g, &m, None, cwd, arg);
assert_eq!(
start("a", &dir).unwrap(),
Start::Node(NodeKey::Path(p("/knowledge/core/a.md")))
);
assert_eq!(
start("knowledge", &dir).unwrap(),
Start::Container(p("/knowledge"))
);
assert_eq!(
start("/knowledge", &dir).unwrap(),
Start::Container(p("/knowledge"))
);
assert_eq!(
start("core/", &dir.join("knowledge")).unwrap(),
Start::Container(p("/knowledge/core"))
);
assert_eq!(
start("./core", &dir.join("knowledge")).unwrap(),
Start::Container(p("/knowledge/core"))
);
assert_eq!(
start("empty", &dir.join("knowledge")).unwrap(),
Start::Container(p("/knowledge/empty"))
);
assert_eq!(
start("core.md", &dir.join("knowledge")).unwrap(),
Start::Node(NodeKey::Path(p("/knowledge/core.md")))
);
assert_eq!(
start("src/a.rs", &dir).unwrap(),
Start::Node(NodeKey::Path(p("/src/a.rs")))
);
assert_eq!(
start("src/plain.rs", &dir).unwrap(),
Start::Node(NodeKey::Path(p("/src/plain.rs")))
);
assert_eq!(start("src", &dir).unwrap(), Start::Outside(p("/src")));
assert_eq!(start(".", &dir).unwrap(), Start::Outside(p("/")));
for (arg, needle) in [
(
"dup",
"identifies more than one document: /knowledge/c.md, /knowledge/core/b.md",
),
(
"core",
"is both an id (/knowledge/core.md) and a path (/knowledge/core)",
),
("nothing", "neither an id nor a path"),
("/knowledge/gone.md", "neither an id nor a path"),
] {
let err = start(arg, &dir.join("knowledge")).unwrap_err();
assert!(matches!(err, Error::Start(_)), "{arg}: {err}");
assert!(err.to_string().contains(needle), "{arg}: {err}");
}
assert_eq!(
g.kind(&NodeKey::Path(p("/knowledge/empty"))),
Some(NodeKind::Directory)
);
assert_eq!(g.kind(&NodeKey::Path(p("/src"))), Some(NodeKind::Directory));
assert_eq!(
g.kind(&NodeKey::Path(p("/src/plain.rs"))),
Some(NodeKind::File)
);
assert_eq!(g.kind(&NodeKey::Path(p("/src/a.rs"))), Some(NodeKind::File));
assert_eq!(Start::Outside(p("/src")).key(), NodeKey::Path(p("/src")));
assert_eq!(Start::Node(NodeKey::Missing("x".into())).path(), None);
std::fs::remove_dir_all(&dir).unwrap();
}
#[test]
fn references_resolve_across_roots_or_refuse() {
let dir = temp("ids");
let m = model_at(&dir, &["/knowledge", "/other"]);
assert_eq!(
resolve_id(&m, None, "core").unwrap(),
p("/knowledge/core.md")
);
let err = resolve_id(&m, None, "a").unwrap_err();
assert!(matches!(err, Error::Locate(_)));
assert_eq!(
err.to_string(),
"locate: `a` identifies more than one document: /knowledge/core/a.md, /other/n.md. Write `k:a` or `o:a`"
);
assert_eq!(
resolve_id(&m, None, "zz").unwrap_err().to_string(),
"locate: `zz` identifies no document"
);
for form in ["o:a", "test/o:a", "sokf:o:a", "o:a#n"] {
assert_eq!(
resolve_id(&m, None, form).unwrap(),
p("/other/n.md"),
"{form}"
);
}
assert!(resolve_id(&m, None, "nope:a").is_err());
assert!(is_key_reference("#k") && is_key_reference("sokf:o:#k"));
assert!(!is_key_reference("o:a#k") && !is_key_reference("a"));
let mut g = build(&m);
let err = resolve_start(&mut g, &m, None, &dir, "a").unwrap_err();
assert!(err.to_string().contains("/other/n.md"), "{err}");
std::fs::remove_dir_all(&dir).unwrap();
}
#[test]
fn a_key_of_document_scope_starts_when_one_document_captures_it() {
use crate::grammar::KeyScope;
let dir = temp("document-scope");
let m = model_at(&dir, &["/knowledge", "/other"]);
let mut keys = KeyIndex::default();
for (key, path, scope) in [
("X-1", "/knowledge/core/a.md", KeyScope::Document),
("Y-1", "/knowledge/core.md", KeyScope::Document),
("Y-1", "/knowledge/core/a.md", KeyScope::Document),
(
"R-1",
"/knowledge/core/a.md",
KeyScope::Host("knowledge".into()),
),
("R-1", "/knowledge/core.md", KeyScope::Document),
] {
keys.add(KeyEntry {
key: key.into(),
path: p(path),
line: 3,
heading_slug: None,
scope,
knowledge: m.knowledge_of(&p(path)).unwrap(),
rule_id: None,
});
}
let mut g = build(&m);
for (path, slug) in [
("/knowledge/core/a.md", "x-1"),
("/knowledge/core/a.md", "y-1"),
("/knowledge/core.md", "y-1"),
] {
g.add_key(&p(path), slug, &slug.to_uppercase(), 3, &[]);
}
let key = |s: &str| Start::Node(NodeKey::Key(s.into()));
let mut start = |arg: &str| resolve_start(&mut g, &m, Some(&keys), &dir, arg);
for arg in ["#x-1", "#X-1", "k:#x-1", "sokf:#x-1"] {
assert_eq!(
start(arg).unwrap(),
key("/knowledge/core/a.md#x-1"),
"{arg}"
);
}
assert_eq!(
note(&m, Some(&keys), "#x-1").as_deref(),
Some("`#x-1` is unique only within `k:a`, so link it as `k:a#x-1`")
);
assert_eq!(start("core#y-1").unwrap(), key("/knowledge/core.md#y-1"));
assert_eq!(
start("core#nothing").unwrap(),
Start::Node(NodeKey::Path(p("/knowledge/core.md")))
);
assert_eq!(
start("#r-1").unwrap(),
Start::Node(NodeKey::Path(p("/knowledge/core/a.md")))
);
assert_eq!(note(&m, Some(&keys), "#r-1"), None);
assert_eq!(note(&m, Some(&keys), "core#y-1"), None);
for (arg, message) in [
(
"#y-1",
"graph: `#y-1` is a key of document scope that more than one document captures. Write `core#y-1` or `k:a#y-1`",
),
(
"o:#y-1",
"graph: `o:#y-1` is neither an id nor a path in the repository",
),
(
"#none",
"graph: `#none` is neither an id nor a path in the repository",
),
] {
let err = start(arg).unwrap_err();
assert!(matches!(err, Error::Start(_)), "{arg}: {err}");
assert_eq!(err.to_string(), message);
}
std::fs::remove_dir_all(&dir).unwrap();
}
#[test]
fn the_error_lists_ten_references_and_counts_the_rest() {
let forms = |n: usize| (1..=n).map(|i| format!("`n{i}#y-1`")).collect::<Vec<_>>();
let ten = (1..=10)
.map(|i| format!("`n{i}#y-1`"))
.collect::<Vec<_>>()
.join(" or ");
assert_eq!(capped(&forms(2)), "`n1#y-1` or `n2#y-1`");
assert_eq!(capped(&forms(10)), ten);
assert_eq!(capped(&forms(11)), format!("{ten}, and 1 more"));
assert_eq!(capped(&forms(103)), format!("{ten}, and 93 more"));
}
#[test]
fn a_word_shaped_as_a_path_is_read_only_as_a_path() {
let dir = temp("path-shaped");
for (rel, id) in [
("knowledge/core.md.md", "core.md"),
("knowledge/e.md", "core/"),
("knowledge/f.md", ".hidden"),
] {
std::fs::write(
dir.join(rel),
format!("---\ntype: Note\nid: \"{id}\"\n---\n\n# X\n"),
)
.unwrap();
}
std::fs::create_dir_all(dir.join(".hidden")).unwrap();
let m = model_at(&dir, &["/knowledge"]);
let mut g = build(&m);
let mut start = |arg: &str, cwd: &Path| resolve_start(&mut g, &m, None, cwd, arg);
let knowledge = dir.join("knowledge");
assert_eq!(
start("core.md", &knowledge).unwrap(),
Start::Node(NodeKey::Path(p("/knowledge/core.md")))
);
assert_eq!(
start("core/", &knowledge).unwrap(),
Start::Container(p("/knowledge/core"))
);
assert_eq!(
start(".hidden", &dir).unwrap(),
Start::Outside(p("/.hidden"))
);
let _ = std::fs::remove_dir_all(&dir);
}
}