use std::path::Path;
use super::{Graph, NodeKey, NodeKind};
use crate::{
Error, FileKind, Model, PathArg, RepoPath, Result,
grammar::KeyScope,
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, slug) = match paths_of_reference(model, Some(keys), arg).as_slice() {
[one] => (one.clone(), None),
[] => match document_scoped(model, keys, arg).as_slice() {
[(one, slug)] => (one.clone(), Some(slug.clone())),
_ => return None,
},
_ => return None,
};
let wide = slug.is_none() && is_key_reference(arg);
slug.into_iter()
.chain(std::iter::once(written.to_string()))
.chain(crate::markdown::key_ids(written))
.find_map(|slug| {
let entry = keys
.document
.get(&(path.clone(), slug.clone()))?
.iter()
.find(|e| !wide || !matches!(e.scope, KeyScope::Document))?;
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);
std::iter::once(written.to_string())
.chain(crate::markdown::key_ids(written))
.map(|slug| {
let mut found: Vec<(RepoPath, String)> = keys
.document
.keys()
.filter(|(p, s)| {
*s == slug && model.knowledge_of(p).is_some_and(|k| stores.contains(&k))
})
.cloned()
.collect();
found.sort();
found
})
.find(|found| !found.is_empty())
.unwrap_or_default()
}
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();
};
std::iter::once(key.to_string())
.chain(crate::markdown::key_ids(key))
.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<_>>()
})
.find(|paths| !paths.is_empty())
.unwrap_or_default()
} 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)
))),
}
}
enum Reading {
Id(RepoPath),
Path(RepoPath),
}
#[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"
)]
fn read(
model: &Model,
keys: Option<&KeyIndex>,
cwd: &Path,
arg: &str,
) -> std::result::Result<Reading, String> {
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(format!(
"`{arg}` is both an id ({}) and a path ({p})",
join(&ids)
)),
([_, _, ..], None) => Err(format!(
"`{arg}` identifies more than one document: {}{}",
join(&ids),
qualified(model, arg, &ids)
)),
([one], None) => Ok(Reading::Id(one.clone())),
([], Some(p)) => Ok(Reading::Path(p)),
([], None) => {
let scoped = keys.map_or_else(Vec::new, |k| document_scoped(model, k, arg));
match scoped.as_slice() {
[(one, _)] => Ok(Reading::Id(one.clone())),
[] => Err(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(format!(
"`{arg}` is a key of document scope that more than one document captures. Write {}",
capped(&forms)
))
}
}
}
}
}
pub fn resolve_start(
graph: &mut Graph,
model: &Model,
keys: Option<&KeyIndex>,
cwd: &Path,
arg: &str,
) -> Result<Start> {
match read(model, keys, cwd, arg).map_err(Error::Start)? {
Reading::Id(one) => Ok(key_start(graph, model, keys, arg, &one)),
Reading::Path(p) => Ok(path_start(graph, model, p)),
}
}
pub fn resolve_document(
model: &Model,
keys: Option<&KeyIndex>,
cwd: &Path,
arg: &str,
) -> Result<RepoPath> {
match read(model, keys, cwd, arg).map_err(Error::Guide)? {
Reading::Id(path) => Ok(path),
Reading::Path(path) => match model.tree.file(&path).map(|f| f.kind) {
Some(FileKind::Document | FileKind::Schema) => Ok(path),
_ => Err(Error::Guide(format!(
"`{arg}` names {path}, which is no document of a knowledge store"
))),
},
}
}
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;