use std::fmt;
use super::{Document, Knowledge, Located, Model};
use crate::{RepoPath, markdown::is_slug};
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct Identity {
pub scope: String,
pub name: String,
}
impl Identity {
pub fn parse(text: &str) -> Option<Self> {
let (scope, name) = text.split_once('/')?;
Identity::new(scope, name)
}
fn new(scope: &str, name: &str) -> Option<Self> {
(is_slug(scope) && is_slug(name)).then(|| Identity {
scope: scope.to_string(),
name: name.to_string(),
})
}
}
impl fmt::Display for Identity {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}/{}", self.scope, self.name)
}
}
impl Knowledge {
pub fn capped(&self) -> bool {
self.manifest.as_ref().is_some_and(super::Manifest::capped)
}
pub fn identity(&self) -> Option<Identity> {
let m = self.manifest.as_ref()?;
Identity::new(m.scope.as_deref()?, m.name.as_deref()?)
}
pub fn former(&self) -> Vec<Identity> {
self.manifest
.iter()
.flat_map(|m| &m.renamed_from)
.filter_map(|(old, _)| Identity::parse(old))
.collect()
}
}
pub(crate) fn matching_in(
knowledges: &[Knowledge],
wanted: impl Fn(&Identity) -> bool,
) -> (Vec<usize>, bool) {
let n = knowledges.len();
let current: Vec<usize> = (0..n)
.filter(|&k| knowledges[k].identity().is_some_and(|i| wanted(&i)))
.collect();
if !current.is_empty() {
return (current, false);
}
let former = (0..n)
.filter(|&k| knowledges[k].former().iter().any(&wanted))
.collect();
(former, true)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct StoreHit {
pub knowledge: usize,
pub former: bool,
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct IdentityRow {
pub knowledge: usize,
pub identity: String,
pub former: String,
}
impl Model {
pub fn identity_rows(&self) -> Vec<IdentityRow> {
self.knowledges
.iter()
.enumerate()
.map(|(k, kn)| IdentityRow {
knowledge: k,
identity: kn.identity().map(|i| i.to_string()).unwrap_or_default(),
former: kn
.former()
.iter()
.map(ToString::to_string)
.collect::<Vec<_>>()
.join("\n"),
})
.collect()
}
pub fn store(&self, citing: usize, written: &str) -> Option<StoreHit> {
self.note(super::Query::Identities);
let wanted = match written.split_once('/') {
Some(_) => Identity::parse(written)?,
None => Identity {
scope: self.knowledges.get(citing)?.identity()?.scope,
name: written.to_string(),
},
};
let (hits, former) = self.matching(|i| *i == wanted);
match hits.as_slice() {
[knowledge] => Some(StoreHit {
knowledge: *knowledge,
former,
}),
_ => None,
}
}
fn matching(&self, wanted: impl Fn(&Identity) -> bool) -> (Vec<usize>, bool) {
matching_in(&self.knowledges, wanted)
}
pub fn stores_named(&self, written: &str) -> Vec<usize> {
let matches = |identity: &Identity| match written.split_once('/') {
Some(_) => identity.to_string() == written,
None => identity.name == written,
};
self.matching(matches).0
}
pub fn store_name(&self, k: usize) -> Option<String> {
let identity = self.knowledges.get(k)?.identity()?;
let shared = self
.knowledges
.iter()
.filter(|o| o.identity().is_some_and(|i| i.name == identity.name))
.count()
> 1;
Some(if shared {
identity.to_string()
} else {
identity.name
})
}
pub fn document_in(
&self,
citing: usize,
store: Option<&str>,
id: &str,
) -> Option<(usize, &Document)> {
let k = match store {
None => citing,
Some(s) => self.store(citing, s)?.knowledge,
};
self.document(k, id).map(|d| (k, d))
}
pub fn id_at(&self, path: &RepoPath) -> Option<(usize, String)> {
match self.by_path(path)? {
Located::Document(k, d) => Some((k, d.id()?.to_string())),
Located::Schema(k, s) => Some((k, s.id())),
_ => None,
}
}
pub fn path_label(
&self,
citing: usize,
path: &RepoPath,
fragment: Option<&str>,
) -> Option<String> {
if let Some((k, id)) = self.id_at(path) {
let fragment = match self.asset_of(path) {
Some(_) => Some(fragment.unwrap_or("")),
None => fragment,
};
return self.canonical_label(citing, k, Some(&id), fragment);
}
let (k, asset) = self.asset_at(path)?;
if fragment.is_some() {
return None;
}
self.note(super::Query::Path(asset.sidecar_path()));
let id = self.knowledges[k].documents[asset.sidecar?].id()?;
self.canonical_label(citing, k, Some(id), None)
}
pub fn prefix(&self, citing: usize, target: usize) -> Option<String> {
if citing == target {
return Some(String::new());
}
self.note(super::Query::Identities);
let from = self.knowledges.get(citing)?.identity()?;
let to = self.knowledges.get(target)?.identity()?;
Some(if from.scope == to.scope {
format!("{}:", to.name)
} else {
format!("{to}:")
})
}
pub fn canonical_label(
&self,
citing: usize,
target: usize,
id: Option<&str>,
fragment: Option<&str>,
) -> Option<String> {
self.canonical_include(citing, target, id.unwrap_or(""), fragment)
.map(|target| format!("sokf:{target}"))
}
pub fn canonical_include(
&self,
citing: usize,
target: usize,
id: &str,
fragment: Option<&str>,
) -> Option<String> {
let prefix = self.prefix(citing, target)?;
Some(format!(
"{prefix}{id}{}",
fragment.map(|f| format!("#{f}")).unwrap_or_default()
))
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::markdown::split_store;
#[test]
fn an_identity_is_two_slugs() {
assert_eq!(
Identity::parse("ncoderz/sokf-spec").map(|i| i.to_string()),
Some("ncoderz/sokf-spec".into())
);
assert_eq!(Identity::parse("sokf-spec"), None);
assert_eq!(Identity::parse("Ncoderz/x"), None);
assert_eq!(Identity::parse("a/b/c"), None);
}
#[test]
fn a_qualified_id_splits_at_its_store() {
assert_eq!(split_store("glossary"), (None, "glossary"));
assert_eq!(
split_store("sokf-spec:glossary"),
(Some("sokf-spec"), "glossary")
);
assert_eq!(split_store("acme/common:"), (Some("acme/common"), ""));
}
}