sokf_core/model/stores.rs
1//! This module defines the identities of stores and the qualified ids that
2//! refer to them (`SOKF_FORMAT_10`, `SOKF_FORMAT_64`). The identity of a store is
3//! `<scope>/<name>`. To refer to another store, a document puts that store's
4//! identity in front of the id it would use inside that store. Within one
5//! scope, the name of the store is enough.
6
7use std::fmt;
8
9use super::{Document, Knowledge, Located, Model};
10use crate::{RepoPath, markdown::is_slug};
11
12/// `Identity` is the identity of a store, `<scope>/<name>` (`SOKF_FORMAT_10`).
13#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
14pub struct Identity {
15 /// `scope` identifies the owner of the store.
16 pub scope: String,
17 /// `name` is the name of the store within its scope.
18 pub name: String,
19}
20
21impl Identity {
22 /// `parse` reads `<scope>/<name>`, and returns `None` unless both parts
23 /// are slugs.
24 pub fn parse(text: &str) -> Option<Self> {
25 let (scope, name) = text.split_once('/')?;
26 Identity::new(scope, name)
27 }
28
29 /// `new` returns the identity `scope/name`, or `None` unless both parts
30 /// are slugs.
31 fn new(scope: &str, name: &str) -> Option<Self> {
32 (is_slug(scope) && is_slug(name)).then(|| Identity {
33 scope: scope.to_string(),
34 name: name.to_string(),
35 })
36 }
37}
38
39impl fmt::Display for Identity {
40 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
41 write!(f, "{}/{}", self.scope, self.name)
42 }
43}
44
45impl Knowledge {
46 /// `capped` returns whether the store's manifest caps the scope of its
47 /// keys at the store, with `unique: knowledge` (`SOKF_FORMAT_208`).
48 pub fn capped(&self) -> bool {
49 self.manifest.as_ref().is_some_and(super::Manifest::capped)
50 }
51
52 /// `identity` returns the identity of the store, when its manifest
53 /// declares a `scope` and a `name` that are both slugs.
54 pub fn identity(&self) -> Option<Identity> {
55 let m = self.manifest.as_ref()?;
56 Identity::new(m.scope.as_deref()?, m.name.as_deref()?)
57 }
58
59 /// `former` returns the former identities of the store, which its
60 /// manifest lists in `renamed-from`. It skips an entry that is not a
61 /// valid identity.
62 pub fn former(&self) -> Vec<Identity> {
63 self.manifest
64 .iter()
65 .flat_map(|m| &m.renamed_from)
66 .filter_map(|(old, _)| Identity::parse(old))
67 .collect()
68 }
69}
70
71/// `matching_in` returns the stores of `knowledges` whose current identity
72/// `wanted` accepts, or, when none has one, those whose former identity it
73/// accepts, and whether the match is of a former identity.
74pub(crate) fn matching_in(
75 knowledges: &[Knowledge],
76 wanted: impl Fn(&Identity) -> bool,
77) -> (Vec<usize>, bool) {
78 let n = knowledges.len();
79 let current: Vec<usize> = (0..n)
80 .filter(|&k| knowledges[k].identity().is_some_and(|i| wanted(&i)))
81 .collect();
82 if !current.is_empty() {
83 return (current, false);
84 }
85 let former = (0..n)
86 .filter(|&k| knowledges[k].former().iter().any(&wanted))
87 .collect();
88 (former, true)
89}
90
91/// `StoreHit` is the store that a qualified id refers to.
92#[derive(Debug, Clone, Copy, PartialEq, Eq)]
93pub struct StoreHit {
94 /// `knowledge` is the index of the knowledge store.
95 pub knowledge: usize,
96 /// `former` is true when the id uses a former identity of the store
97 /// (`renamed-from`).
98 pub former: bool,
99}
100
101/// `IdentityRow` holds the current and former identities of one store as
102/// text, in the form that the cache keeps (CACHE-1_AC-16).
103#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
104pub struct IdentityRow {
105 /// `knowledge` is the index of the knowledge store.
106 pub knowledge: usize,
107 /// `identity` is the identity, `scope/name`, or an empty string when the
108 /// manifest declares none.
109 pub identity: String,
110 /// `former` holds the former identities, one `scope/name` on each line.
111 pub former: String,
112}
113
114impl Model {
115 /// `identity_rows` returns the current and former identities of every
116 /// store, in the form that the cache compares (CACHE-1_AC-16).
117 pub fn identity_rows(&self) -> Vec<IdentityRow> {
118 self.knowledges
119 .iter()
120 .enumerate()
121 .map(|(k, kn)| IdentityRow {
122 knowledge: k,
123 identity: kn.identity().map(|i| i.to_string()).unwrap_or_default(),
124 former: kn
125 .former()
126 .iter()
127 .map(ToString::to_string)
128 .collect::<Vec<_>>()
129 .join("\n"),
130 })
131 .collect()
132 }
133
134 /// `store` finds the store that `written` refers to from a document of
135 /// store `citing` (`SOKF_FORMAT_64`). It looks up a `name` among the
136 /// stores in the scope of the citing store, and a `scope/name` among
137 /// every store. It matches the current identities first, then the
138 /// former ones. When two stores share an identity, `store` returns
139 /// `None`, because validation reports that clash on their manifests.
140 ///
141 /// `store` records a single dependency on the identities of all stores
142 /// (CACHE-1_AC-16), not one for each store it reads. A finer dependency
143 /// would save little, for two reasons. Renaming a store changes every
144 /// qualified id that refers to the store, and few documents need `store`.
145 // sokf-implements: SOKF_FORMAT_64
146 // sokf-implements: CACHE-1_AC-16
147 // sokf-implements: CONF-2_AC-3
148 pub fn store(&self, citing: usize, written: &str) -> Option<StoreHit> {
149 self.note(super::Query::Identities);
150 let wanted = match written.split_once('/') {
151 Some(_) => Identity::parse(written)?,
152 None => Identity {
153 scope: self.knowledges.get(citing)?.identity()?.scope,
154 name: written.to_string(),
155 },
156 };
157 let (hits, former) = self.matching(|i| *i == wanted);
158 match hits.as_slice() {
159 [knowledge] => Some(StoreHit {
160 knowledge: *knowledge,
161 former,
162 }),
163 _ => None,
164 }
165 }
166
167 /// `matching` returns the stores whose current identity `wanted`
168 /// accepts. When there are none, it returns the stores with a former
169 /// identity that `wanted` accepts, and says so with `true`.
170 fn matching(&self, wanted: impl Fn(&Identity) -> bool) -> (Vec<usize>, bool) {
171 matching_in(&self.knowledges, wanted)
172 }
173
174 /// `stores_named` returns the stores that `written` names on the command
175 /// line, where no citing store gives a scope. It matches a `scope/name`
176 /// against the whole identity and a `name` against the name of every
177 /// store. It matches the current identities first, then the former ones.
178 // sokf-implements: CLI-7_AC-64
179 pub fn stores_named(&self, written: &str) -> Vec<usize> {
180 let matches = |identity: &Identity| match written.split_once('/') {
181 Some(_) => identity.to_string() == written,
182 None => identity.name == written,
183 };
184 self.matching(matches).0
185 }
186
187 /// `store_name` returns the shortest name of store `k` on the command
188 /// line: its `name`, or its whole identity when another store shares
189 /// that name. It returns `None` when the store has no identity.
190 pub fn store_name(&self, k: usize) -> Option<String> {
191 let identity = self.knowledges.get(k)?.identity()?;
192 let shared = self
193 .knowledges
194 .iter()
195 .filter(|o| o.identity().is_some_and(|i| i.name == identity.name))
196 .count()
197 > 1;
198 Some(if shared {
199 identity.to_string()
200 } else {
201 identity.name
202 })
203 }
204
205 /// `document_in` finds the document that `id` refers to in `store`.
206 /// `store` is a store prefix as a document of store `citing` wrote it. It
207 /// returns the document with the index of the knowledge store that
208 /// holds it. When `store` is `None`, it looks in `citing`.
209 pub fn document_in(
210 &self,
211 citing: usize,
212 store: Option<&str>,
213 id: &str,
214 ) -> Option<(usize, &Document)> {
215 let k = match store {
216 None => citing,
217 Some(s) => self.store(citing, s)?.knowledge,
218 };
219 self.document(k, id).map(|d| (k, d))
220 }
221
222 /// `id_at` returns the id of the document or schema at `path`, in any
223 /// store, with the index of its knowledge store.
224 pub fn id_at(&self, path: &RepoPath) -> Option<(usize, String)> {
225 match self.by_path(path)? {
226 Located::Document(k, d) => Some((k, d.id()?.to_string())),
227 Located::Schema(k, s) => Some((k, s.id())),
228 _ => None,
229 }
230 }
231
232 /// `path_label` returns the canonical `sokf:` label that a document in
233 /// store `citing` should use for a link to `path` with `fragment`
234 /// (`SOKF_FORMAT_65`). The label depends on the file at `path`:
235 ///
236 /// - For a document, the label is its id with the fragment.
237 /// - For a sidecar, the label is its id with the fragment, and with an
238 /// empty fragment when the link has none, because the path refers to
239 /// the sidecar file and not to the asset.
240 /// - For an asset, the label is the id of its sidecar, which refers to
241 /// the asset.
242 ///
243 /// `path_label` returns `None` for any other file, and for an asset
244 /// path with a fragment.
245 pub fn path_label(
246 &self,
247 citing: usize,
248 path: &RepoPath,
249 fragment: Option<&str>,
250 ) -> Option<String> {
251 if let Some((k, id)) = self.id_at(path) {
252 let fragment = match self.asset_of(path) {
253 Some(_) => Some(fragment.unwrap_or("")),
254 None => fragment,
255 };
256 return self.canonical_label(citing, k, Some(&id), fragment);
257 }
258 let (k, asset) = self.asset_at(path)?;
259 if fragment.is_some() {
260 return None;
261 }
262 self.note(super::Query::Path(asset.sidecar_path()));
263 let id = self.knowledges[k].documents[asset.sidecar?].id()?;
264 self.canonical_label(citing, k, Some(id), None)
265 }
266
267 /// `prefix` returns the store prefix that a document in store `citing`
268 /// should put before an id in store `target`. It is the shortest
269 /// unambiguous prefix (`SOKF_FORMAT_65`). The prefix is empty within one store,
270 /// `name:` within one scope, and `scope/name:` otherwise. `prefix`
271 /// returns `None` when the two stores differ and either has no
272 /// identity.
273 pub fn prefix(&self, citing: usize, target: usize) -> Option<String> {
274 if citing == target {
275 return Some(String::new());
276 }
277 self.note(super::Query::Identities);
278 let from = self.knowledges.get(citing)?.identity()?;
279 let to = self.knowledges.get(target)?.identity()?;
280 Some(if from.scope == to.scope {
281 format!("{}:", to.name)
282 } else {
283 format!("{to}:")
284 })
285 }
286
287 /// `canonical_label` returns the canonical `sokf:` label that a document
288 /// in store `citing` should use for `id` and `fragment` in store `target`
289 /// (`SOKF_FORMAT_65`).
290 pub fn canonical_label(
291 &self,
292 citing: usize,
293 target: usize,
294 id: Option<&str>,
295 fragment: Option<&str>,
296 ) -> Option<String> {
297 self.canonical_include(citing, target, id.unwrap_or(""), fragment)
298 .map(|target| format!("sokf:{target}"))
299 }
300
301 /// `canonical_include` returns the canonical target that an include
302 /// marker in store `citing` should use for `id` and `fragment` in store
303 /// `target` (`SOKF_FORMAT_65`).
304 pub fn canonical_include(
305 &self,
306 citing: usize,
307 target: usize,
308 id: &str,
309 fragment: Option<&str>,
310 ) -> Option<String> {
311 let prefix = self.prefix(citing, target)?;
312 Some(format!(
313 "{prefix}{id}{}",
314 fragment.map(|f| format!("#{f}")).unwrap_or_default()
315 ))
316 }
317}
318
319#[cfg(test)]
320mod tests {
321 use super::*;
322 use crate::markdown::split_store;
323
324 #[test]
325 fn an_identity_is_two_slugs() {
326 assert_eq!(
327 Identity::parse("ncoderz/sokf-spec").map(|i| i.to_string()),
328 Some("ncoderz/sokf-spec".into())
329 );
330 assert_eq!(Identity::parse("sokf-spec"), None);
331 assert_eq!(Identity::parse("Ncoderz/x"), None);
332 assert_eq!(Identity::parse("a/b/c"), None);
333 }
334
335 #[test]
336 fn a_qualified_id_splits_at_its_store() {
337 assert_eq!(split_store("glossary"), (None, "glossary"));
338 assert_eq!(
339 split_store("sokf-spec:glossary"),
340 (Some("sokf-spec"), "glossary")
341 );
342 assert_eq!(split_store("acme/common:"), (Some("acme/common"), ""));
343 }
344}