1use std::collections::{BTreeMap, BTreeSet, HashMap};
5
6use super::{Model, Query};
7use crate::{
8 RepoPath,
9 grammar::KeyScope,
10 markdown::{self, Body, link_headings},
11};
12
13#[derive(Debug, Clone, PartialEq, Eq)]
15pub struct KeyEntry {
16 pub key: String,
18 pub id: String,
22 pub path: RepoPath,
24 pub line: usize,
26 pub heading_slug: Option<String>,
28 pub holds_anchor: bool,
34 pub scope: KeyScope,
36 pub knowledge: usize,
38 pub rule_id: Option<String>,
42}
43
44#[derive(Debug, Clone, Default)]
49pub struct KeyIndex {
50 pub document: HashMap<(RepoPath, String), Vec<KeyEntry>>,
52 pub knowledge: HashMap<(usize, String), Vec<KeyEntry>>,
54 pub repository: HashMap<String, Vec<KeyEntry>>,
56 pub anchors: BTreeMap<RepoPath, BTreeSet<String>>,
60}
61
62impl KeyIndex {
63 pub fn add(&mut self, entry: KeyEntry) {
68 let s = entry.id.clone();
69 let scoped = match &entry.scope {
70 KeyScope::Host(scope) if scope == "knowledge" => Some(
71 self.knowledge
72 .entry((entry.knowledge, s.clone()))
73 .or_default(),
74 ),
75 KeyScope::Host(scope) if scope == "repository" => {
76 Some(self.repository.entry(s.clone()).or_default())
77 }
78 _ => None,
79 };
80 if let Some(entries) = scoped
81 && !entries.iter().any(|e| e.path == entry.path)
82 {
83 entries.push(entry.clone());
84 }
85 self.document
86 .entry((entry.path.clone(), s))
87 .or_default()
88 .push(entry);
89 }
90
91 pub fn add_anchor(&mut self, path: RepoPath, slug: String) {
94 self.anchors.entry(path).or_default().insert(slug);
95 }
96
97 pub fn anchors_of(&self, path: &RepoPath) -> impl Iterator<Item = &str> {
100 self.anchors
101 .get(path)
102 .into_iter()
103 .flatten()
104 .map(String::as_str)
105 }
106
107 pub fn merge(&mut self, other: KeyIndex) {
109 self.extend(other.document.into_values().flatten());
110 for (path, slugs) in other.anchors {
111 self.anchors.entry(path).or_default().extend(slugs);
112 }
113 }
114
115 pub fn of_document<'a>(&'a self, path: &'a RepoPath) -> impl Iterator<Item = &'a KeyEntry> {
117 self.document
118 .iter()
119 .filter(move |((p, _), _)| p == path)
120 .flat_map(|(_, entries)| entries.iter())
121 }
122}
123
124impl Extend<KeyEntry> for KeyIndex {
125 fn extend<I: IntoIterator<Item = KeyEntry>>(&mut self, entries: I) {
126 for entry in entries {
127 self.add(entry);
128 }
129 }
130}
131
132#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
136pub struct Label<'a> {
137 pub store: Option<&'a str>,
139 pub id: Option<&'a str>,
141 pub fragment: Option<&'a str>,
143}
144
145impl<'a> Label<'a> {
146 #[must_use]
148 pub fn with_fragment(self, fragment: Option<&'a str>) -> Self {
149 Label { fragment, ..self }
150 }
151
152 #[must_use]
155 pub fn without_store(self) -> Self {
156 Label {
157 store: None,
158 ..self
159 }
160 }
161}
162
163#[derive(Debug, Clone, PartialEq, Eq)]
165pub struct Resolved {
166 pub knowledge: usize,
168 pub path: RepoPath,
170 pub slug: Option<String>,
173}
174
175#[derive(Debug, Clone, PartialEq, Eq)]
178pub enum Unresolved {
179 NoStore(String),
182 NoDocument,
184 DuplicateId,
186 NoFragment,
188 BareNotFound,
190 BareAmbiguous,
192 BareDocumentScope,
194 KeyForm(String),
197}
198
199impl Unresolved {
200 pub fn message(&self, label: &str) -> String {
202 match self {
203 Unresolved::NoStore(store) => format!(
204 "`[{label}]` refers to the store `{store}`, which is not a knowledge root of this repository"
205 ),
206 Unresolved::NoDocument => format!("`[{label}]` resolves to no document"),
207 Unresolved::DuplicateId => {
208 format!("more than one document has the id in `[{label}]`")
209 }
210 Unresolved::NoFragment => {
211 format!(
212 "`[{label}]` refers to a fragment that is neither a captured key nor a heading"
213 )
214 }
215 Unresolved::BareNotFound => format!(
216 "`[{label}]` refers to a key that no document of its store captures at repository or knowledge scope"
217 ),
218 Unresolved::BareAmbiguous => {
219 format!("`[{label}]` refers to a key that more than one document captures")
220 }
221 Unresolved::BareDocumentScope => {
222 format!("`[{label}]` refers to a key of document scope only")
223 }
224 Unresolved::KeyForm(slug) => {
225 format!("`[{label}]` gives the fragment as text, not as a slug. Use `#{slug}`")
226 }
227 }
228 }
229}
230
231pub fn resolve_in(
243 keys: &KeyIndex,
244 path: &RepoPath,
245 body: &Body,
246 fragment: &str,
247) -> Result<String, Unresolved> {
248 let headings = link_headings(body);
249 let found = |f: &str| {
250 keys.document.contains_key(&(path.clone(), f.to_string()))
251 || keys.anchors.get(path).is_some_and(|a| a.contains(f))
252 || headings.iter().any(|h| h.slug == f)
253 };
254 if found(fragment) {
255 return Ok(fragment.to_string());
256 }
257 match markdown::key_ids(fragment)
258 .into_iter()
259 .find(|s| s != fragment && found(s))
260 {
261 Some(s) => Err(Unresolved::KeyForm(s)),
262 None => Err(Unresolved::NoFragment),
263 }
264}
265
266pub fn resolve(
281 model: &Model,
282 keys: &KeyIndex,
283 knowledge: usize,
284 label: Label<'_>,
285) -> Result<Resolved, Unresolved> {
286 let target = match label.store {
287 None => knowledge,
288 Some(store) => {
289 model
290 .store(knowledge, store)
291 .ok_or_else(|| Unresolved::NoStore(store.to_string()))?
292 .knowledge
293 }
294 };
295 if model.knowledges.get(target).is_none() {
296 return Err(Unresolved::NoDocument);
297 }
298 match (label.id.filter(|i| !i.is_empty()), label.fragment) {
299 (None, None | Some("")) => Err(Unresolved::NoDocument),
301 (Some(id), fragment) => {
302 let doc = match model.ids(target, id).len() {
303 0 => return Err(Unresolved::NoDocument),
304 1 => model.document(target, id).ok_or(Unresolved::NoDocument)?,
305 _ => return Err(Unresolved::DuplicateId),
306 };
307 let Some(fragment) = fragment.filter(|f| !f.is_empty()) else {
309 return Ok(Resolved {
310 knowledge: target,
311 path: doc.path.clone(),
312 slug: None,
313 });
314 };
315 resolve_in(keys, &doc.path, &doc.body, fragment).map(|slug| Resolved {
316 knowledge: target,
317 path: doc.path.clone(),
318 slug: Some(slug),
319 })
320 }
321 (None, Some(fragment)) => {
322 let elsewhere = label.store.is_none();
323 match bare(model, keys, target, fragment, elsewhere) {
324 Err(Unresolved::BareNotFound) => {
325 let first = markdown::key_ids(fragment)
329 .into_iter()
330 .filter(|s| s != fragment)
331 .map(|s| {
332 let found = bare(model, keys, target, &s, elsewhere);
333 (s, found)
334 })
335 .find(|(_, found)| !matches!(found, Err(Unresolved::BareNotFound)));
336 match first {
337 Some((s, Ok(_))) => Err(Unresolved::KeyForm(s)),
338 _ => Err(Unresolved::BareNotFound),
339 }
340 }
341 other => other,
342 }
343 }
344 }
345}
346
347pub fn resolve_slugged(
351 model: &Model,
352 keys: &KeyIndex,
353 knowledge: usize,
354 label: Label<'_>,
355) -> (Result<Resolved, Unresolved>, Option<String>) {
356 match resolve(model, keys, knowledge, label) {
357 Err(Unresolved::KeyForm(s)) => {
358 let resolved = resolve(model, keys, knowledge, label.with_fragment(Some(&s)));
359 (resolved, Some(s))
360 }
361 other => (other, None),
362 }
363}
364
365fn bare(
370 model: &Model,
371 keys: &KeyIndex,
372 knowledge: usize,
373 fragment: &str,
374 elsewhere: bool,
375) -> Result<Resolved, Unresolved> {
376 let found = |one: &KeyEntry| Resolved {
377 knowledge: one.knowledge,
378 path: one.path.clone(),
379 slug: Some(fragment.to_string()),
380 };
381 model.note(Query::KeyRepository(fragment.to_string()));
382 model.note(Query::KeyKnowledge {
383 knowledge,
384 slug: fragment.to_string(),
385 });
386 let repo = keys
387 .repository
388 .get(fragment)
389 .map(Vec::as_slice)
390 .unwrap_or_default();
391 let own: Vec<&KeyEntry> = repo.iter().filter(|e| e.knowledge == knowledge).collect();
392 match own.as_slice() {
393 [one] => return Ok(found(one)),
394 [] => {}
395 _ => return Err(Unresolved::BareAmbiguous),
396 }
397 let local = keys
398 .knowledge
399 .get(&(knowledge, fragment.to_string()))
400 .map(Vec::as_slice)
401 .unwrap_or_default();
402 match local {
403 [one] => Ok(found(one)),
404 [] => {
405 if elsewhere {
406 match repo {
407 [one] => return Ok(found(one)),
408 [] => {}
409 _ => return Err(Unresolved::BareAmbiguous),
410 }
411 }
412 model.note(Query::KeyDocument {
413 knowledge,
414 slug: fragment.to_string(),
415 });
416 let document_only = keys
417 .document
418 .keys()
419 .any(|(p, k)| k == fragment && model.knowledge_of(p) == Some(knowledge));
420 if document_only {
421 Err(Unresolved::BareDocumentScope)
422 } else {
423 Err(Unresolved::BareNotFound)
424 }
425 }
426 _ => Err(Unresolved::BareAmbiguous),
427 }
428}
429
430#[cfg(test)]
431mod tests {
432
433 use super::*;
434
435 fn p(s: &str) -> RepoPath {
436 RepoPath::parse(s).unwrap()
437 }
438
439 fn entry(key: &str, path: &str, scope: KeyScope, slug: Option<&str>) -> KeyEntry {
440 KeyEntry {
441 id: crate::markdown::slug(key),
442 key: key.into(),
443 path: p(path),
444 line: 1,
445 heading_slug: slug.map(str::to_string),
446 holds_anchor: true,
447 scope,
448 knowledge: 0,
449 rule_id: None,
450 }
451 }
452
453 #[test]
454 fn indexes_by_scope() {
455 let mut index = KeyIndex::default();
456 index.add(entry("D", "/a.md", KeyScope::Document, None));
457 index.add(entry(
458 "K",
459 "/a.md",
460 KeyScope::Host("knowledge".into()),
461 Some("k-heading"),
462 ));
463 index.add(entry(
464 "R",
465 "/b.md",
466 KeyScope::Host("repository".into()),
467 None,
468 ));
469 assert_eq!(index.document.len(), 3);
470 assert_eq!(index.knowledge.len(), 1);
471 assert_eq!(index.repository.len(), 1);
472 assert_eq!(index.of_document(&p("/a.md")).count(), 2);
473 assert_eq!(index.of_document(&p("/c.md")).count(), 0);
474 for u in [
475 Unresolved::NoStore("s".into()),
476 Unresolved::NoDocument,
477 Unresolved::DuplicateId,
478 Unresolved::NoFragment,
479 Unresolved::BareNotFound,
480 Unresolved::BareAmbiguous,
481 Unresolved::BareDocumentScope,
482 Unresolved::KeyForm("k".into()),
483 ] {
484 assert!(u.message("sokf:x").contains("[sokf:x]"));
485 }
486 }
487
488 #[test]
490 fn a_kept_anchor_resolves_a_fragment_of_its_document_and_is_no_key() {
491 let mut index = KeyIndex::default();
492 let mut kept = KeyIndex::default();
493 kept.add_anchor(p("/a.md"), "d-5".into());
494 index.merge(kept);
495 assert_eq!(index.anchors_of(&p("/a.md")).collect::<Vec<_>>(), ["d-5"]);
496 assert_eq!(index.of_document(&p("/a.md")).count(), 0);
497 let body = Body::default();
498 assert_eq!(
499 resolve_in(&index, &p("/a.md"), &body, "d-5"),
500 Ok("d-5".into())
501 );
502 assert_eq!(
503 resolve_in(&index, &p("/a.md"), &body, "D-5"),
504 Err(Unresolved::KeyForm("d-5".into()))
505 );
506 assert_eq!(
507 resolve_in(&index, &p("/b.md"), &body, "d-5"),
508 Err(Unresolved::NoFragment)
509 );
510 }
511}
512
513#[cfg(test)]
514mod fragment_tests {
515 use std::collections::BTreeMap;
516
517 use super::*;
518 use crate::{Config, FsLoader, RepoRoot, collect, config::MarkerCheck};
519
520 #[test]
522 fn an_empty_fragment_names_the_whole_document_and_a_bare_one_nothing() {
523 let dir = crate::test_support::fresh_dir("keys-empty");
524 std::fs::create_dir_all(dir.join("knowledge")).unwrap();
525 std::fs::write(
526 dir.join("knowledge/a.md"),
527 "---\ntype: Note\nid: a\n---\n\n# A\n\n## Part\n",
528 )
529 .unwrap();
530 let root = RepoRoot::new(dir.clone());
531 let tree = collect(
532 &root,
533 &Config {
534 roots: vec![RepoPath::parse("/knowledge").unwrap()],
535 registered_count: 0,
536 exclude: vec![],
537 added_exclude: vec![],
538 declined: BTreeMap::default(),
539 markers: MarkerCheck::default(),
540 format: crate::config::FormatConfig::default(),
541 },
542 )
543 .unwrap();
544 let model = crate::model::build(tree, &mut FsLoader::new(&root)).unwrap();
545 let keys = KeyIndex::default();
546 let label = |id, fragment| Label {
547 store: None,
548 id,
549 fragment,
550 };
551 let path = RepoPath::parse("/knowledge/a.md").unwrap();
552 assert_eq!(
553 resolve(&model, &keys, 0, label(Some("a"), Some(""))),
554 Ok(Resolved {
555 knowledge: 0,
556 path: path.clone(),
557 slug: None
558 })
559 );
560 assert_eq!(
561 resolve(&model, &keys, 0, label(Some("a"), Some("part"))),
562 Ok(Resolved {
563 knowledge: 0,
564 path,
565 slug: Some("part".into())
566 })
567 );
568 assert_eq!(
569 resolve(&model, &keys, 0, label(None, Some(""))),
570 Err(Unresolved::NoDocument)
571 );
572 std::fs::remove_dir_all(&dir).unwrap();
573 }
574}