use std::collections::BTreeSet;
use crate::{
Model,
markdown::{self, is_slug},
model::{
Query,
keys::{self, KeyIndex, Label, Resolved, Unresolved},
},
};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Reference<'a> {
Key(&'a str),
Label(Label<'a>),
}
impl<'a> Reference<'a> {
pub fn parse(target: &'a str) -> Self {
if target.contains(['#', ':']) {
Reference::Label(Label::parse(target))
} else if is_slug(target) {
Reference::Label(Label {
store: None,
id: Some(target),
fragment: None,
})
} else {
Reference::Key(target)
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Unresolvable {
pub message: String,
pub criterion: &'static str,
}
impl Unresolvable {
fn new(message: impl Into<String>, criterion: &'static str) -> Self {
Unresolvable {
message: message.into(),
criterion,
}
}
}
pub fn resolve(model: &Model, keys: &KeyIndex, target: &str) -> Result<Resolved, Unresolvable> {
match Reference::parse(target) {
Reference::Key(key) => bare_key(model, keys, key),
Reference::Label(label) => {
let stores = match label.store {
Some(store) => vec![store_named(model, store)?],
None => (0..model.knowledges.len())
.filter(|&k| !model.knowledges[k].capped())
.collect(),
};
match label.id {
Some(id) if !id.is_empty() => by_id(model, keys, &stores, label),
_ => by_fragment(model, keys, &stores, label),
}
}
}
}
pub fn names_broken_store(model: &Model, target: &str) -> bool {
match Reference::parse(target) {
Reference::Label(Label {
store: Some(store), ..
}) => store_named(model, store).is_ok_and(|k| model.broken(k).is_some()),
_ => false,
}
}
fn bare_key(model: &Model, keys: &KeyIndex, key: &str) -> Result<Resolved, Unresolvable> {
let ids = markdown::key_ids(key);
let entries = |s: &String| {
model.note(Query::KeyRepository(s.clone()));
keys.repository
.get(s)
.map(Vec::as_slice)
.unwrap_or_default()
};
let s = ids
.iter()
.find(|s| !entries(s).is_empty())
.unwrap_or(&ids[0])
.clone();
match entries(&s) {
[one] => Ok(Resolved {
knowledge: one.knowledge,
path: one.path.clone(),
slug: Some(s),
}),
[] => Err(Unresolvable::new(
format!(
"refers to no key with the slug `{s}` that a schema declares unique in the repository"
),
"SOKF_FORMAT_147",
)),
_ => Err(Unresolvable::new(
format!("refers to the key `{s}`, which more than one document captures"),
"SOKF_FORMAT_145",
)),
}
}
fn store_named(model: &Model, store: &str) -> Result<usize, Unresolvable> {
let hits: BTreeSet<usize> = (0..model.knowledges.len())
.filter_map(|k| model.store(k, store).map(|h| h.knowledge))
.collect();
let mut hits = hits.into_iter();
match (hits.next(), hits.next()) {
(Some(k), None) => Ok(k),
(None, _) => Err(Unresolvable::new(
format!(
"refers to the store `{store}`, which is not a knowledge store in this repository"
),
"SOKF_FORMAT_145",
)),
(Some(_), Some(_)) => Err(Unresolvable::new(
format!(
"refers to the store `{store}`, which exists in more than one scope. Write it as `SCOPE/{store}`, where `SCOPE` is the scope of the store"
),
"SOKF_FORMAT_145",
)),
}
}
fn by_id(
model: &Model,
keys: &KeyIndex,
stores: &[usize],
label: Label<'_>,
) -> Result<Resolved, Unresolvable> {
let id = label.id.unwrap_or_default();
let holding: Vec<usize> = stores
.iter()
.copied()
.filter(|&k| !model.ids(k, id).is_empty())
.collect();
let k = match holding.as_slice() {
[k] => *k,
[] => {
return Err(Unresolvable::new(
format!("refers to the id `{id}`, which no document carries"),
"SOKF_FORMAT_145",
));
}
many => {
let names: Vec<String> = many.iter().map(|&k| store_name(model, k)).collect();
return Err(Unresolvable::new(
format!(
"refers to the id `{id}`, which more than one store holds ({}). Put the store's name and a colon before the id, as in `STORE:{id}`, where `STORE` is the name of the store",
names.join(" and ")
),
"SOKF_FORMAT_149",
));
}
};
in_store(model, keys, k, label.without_store())
}
fn by_fragment(
model: &Model,
keys: &KeyIndex,
stores: &[usize],
label: Label<'_>,
) -> Result<Resolved, Unresolvable> {
let mut found: Vec<Resolved> = Vec::new();
let mut first_error = None;
let mut other_store = false;
for &k in stores {
match in_store(model, keys, k, label.without_store()) {
Ok(r) if r.knowledge != k => other_store = true,
Ok(r) => {
if !found.contains(&r) {
found.push(r);
}
}
Err(e) => {
first_error.get_or_insert(e);
}
}
}
match found.len() {
1 => Ok(found.remove(0)),
0 if other_store => Err(Unresolvable::new(
"refers to a key that only another store captures. A marker that names a store reaches only the keys of that store, so name the store that captures the key",
"SOKF_FORMAT_145",
)),
0 => Err(first_error.unwrap_or_else(|| {
Unresolvable::new("refers to no document and no key", "SOKF_FORMAT_145")
})),
_ => Err(Unresolvable::new(
format!(
"refers to the key `{key}`, which more than one store captures. Put the store's name and a colon before the `#`, as in `STORE:#{key}`, where `STORE` is the name of the store",
key = label.fragment.unwrap_or_default()
),
"SOKF_FORMAT_145",
)),
}
}
fn in_store(
model: &Model,
keys: &KeyIndex,
k: usize,
label: Label<'_>,
) -> Result<Resolved, Unresolvable> {
keys::resolve_slugged(model, keys, k, label)
.0
.map_err(|u| Unresolvable::new(reason(&u), "SOKF_FORMAT_145"))
}
fn reason(u: &Unresolved) -> String {
match u {
Unresolved::NoStore(store) => {
format!("refers to the store `{store}`, which is not a knowledge store in this repository")
}
Unresolved::NoDocument => "resolves to no document".to_string(),
Unresolved::DuplicateId => {
"refers to an id that more than one document of its store carries".to_string()
}
Unresolved::NoFragment | Unresolved::KeyForm(_) => {
"refers to a fragment that is neither a captured key nor a heading".to_string()
}
Unresolved::BareNotFound => {
"refers to no key that a schema declares unique in the store or in the repository"
.to_string()
}
Unresolved::BareAmbiguous => "refers to a key that more than one document captures".to_string(),
Unresolved::BareDocumentScope => {
"refers to a key that is unique only within its own document, so a marker must identify the document too"
.to_string()
}
}
}
fn store_name(model: &Model, k: usize) -> String {
let knowledge = &model.knowledges[k];
knowledge.identity().map_or_else(
|| format!("the store at `{}`", knowledge.root),
|i| format!("`{}`", i.name),
)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_reference_is_read_by_its_spelling() {
let label = |store, id, fragment| {
Reference::Label(Label {
store,
id,
fragment,
})
};
assert_eq!(Reference::parse("CLI-1_AC-2"), Reference::Key("CLI-1_AC-2"));
assert_eq!(
Reference::parse("SOKF_FORMAT_96"),
Reference::Key("SOKF_FORMAT_96")
);
assert_eq!(
Reference::parse("design-cache"),
label(None, Some("design-cache"), None)
);
assert_eq!(
Reference::parse("contract-cli#CLI-1_AC-2"),
label(None, Some("contract-cli"), Some("CLI-1_AC-2"))
);
assert_eq!(
Reference::parse("sokf-spec:#sokf_format_96"),
label(Some("sokf-spec"), None, Some("sokf_format_96"))
);
assert_eq!(
Reference::parse("acme/common:glossary"),
label(Some("acme/common"), Some("glossary"), None)
);
assert_eq!(Reference::parse("cli_p-5"), Reference::Key("cli_p-5"));
}
}