Skip to main content

sokf_core/graph/
start.rs

1//! This module reads the arguments that a user gives the graph commands,
2//! `guide`, and `locate`: `resolve_start` reads the `START` of a graph command
3//! (CLI-7), `resolve_document` reads the document that `guide` takes (CLI-17)
4//! in the same way, and `resolve_id` reads the id that `locate` takes (CLI-8).
5
6use std::path::Path;
7
8use super::{Graph, NodeKey, NodeKind};
9use crate::{
10    Error, FileKind, Model, PathArg, RepoPath, Result,
11    grammar::KeyScope,
12    model::{KeyEntry, KeyIndex, split_store},
13};
14
15/// `Start` is what a `START` resolves to.
16#[derive(Debug, Clone, PartialEq, Eq)]
17pub enum Start {
18    /// A knowledge root, or a directory in one, whose layout the command
19    /// prints.
20    Container(RepoPath),
21    /// A document, an additional file, or a repository file, for which the
22    /// command prints one row.
23    Node(NodeKey),
24    /// A directory outside every knowledge store, for which the command
25    /// prints the roots and the files under it.
26    Outside(RepoPath),
27}
28
29impl Start {
30    /// `key` returns the key of the start's graph node.
31    pub fn key(&self) -> NodeKey {
32        match self {
33            Start::Container(p) | Start::Outside(p) => NodeKey::Path(p.clone()),
34            Start::Node(k) => k.clone(),
35        }
36    }
37
38    /// `path` returns the start as a path, for the `start` field of the
39    /// JSON output, or `None` for a node that has no path.
40    pub fn path(&self) -> Option<&RepoPath> {
41        match self {
42            Start::Container(p) | Start::Outside(p) => Some(p),
43            Start::Node(k) => k.path(),
44        }
45    }
46}
47
48/// `is_key_reference` reports whether `arg` is a reference to a key alone,
49/// `#key` or `<store>:#key`, which the caller can resolve only with the
50/// index of captured keys.
51pub fn is_key_reference(arg: &str) -> bool {
52    let arg = arg.strip_prefix("sokf:").unwrap_or(arg);
53    arg.split_once('#')
54        .is_some_and(|(head, _)| split_store(head).1.is_empty())
55}
56
57/// `key_entry` returns the key that a reference identifies, with the key's
58/// slug. A reference to a key alone identifies the key when exactly one
59/// document captures it (CLI-7_AC-74), at repository or knowledge scope or,
60/// failing those, at document scope (CLI-7_AC-98). A reference
61/// `<id>#<key>` identifies the key when the document with that id captures
62/// it (CLI-7_AC-97).
63pub fn key_entry(model: &Model, keys: &KeyIndex, arg: &str) -> Option<(KeyEntry, String)> {
64    let written = arg.split_once('#')?.1;
65    if written.is_empty() {
66        return None;
67    }
68    let (path, slug) = match paths_of_reference(model, Some(keys), arg).as_slice() {
69        [one] => (one.clone(), None),
70        [] => match document_scoped(model, keys, arg).as_slice() {
71            [(one, slug)] => (one.clone(), Some(slug.clone())),
72            _ => return None,
73        },
74        _ => return None,
75    };
76    // A key alone that names a key of repository or knowledge scope names
77    // it by the first id that such a key has, as `paths_of_reference` found
78    // the document, so a key of document scope under an earlier id of the
79    // same document is not the one it names.
80    let wide = slug.is_none() && is_key_reference(arg);
81    slug.into_iter()
82        .chain(std::iter::once(written.to_string()))
83        .chain(crate::markdown::key_ids(written))
84        .find_map(|slug| {
85            let entry = keys
86                .document
87                .get(&(path.clone(), slug.clone()))?
88                .iter()
89                .find(|e| !wide || !matches!(e.scope, KeyScope::Document))?;
90            Some((entry.clone(), slug))
91        })
92}
93
94/// `document_scoped` returns each document that captures the key of `arg`,
95/// with the key's slug, in the order of the documents' paths, when `arg` is
96/// a reference to a key alone that matches no key of repository or knowledge
97/// scope (CLI-7_AC-98 to CLI-7_AC-100). The documents lie in the stores
98/// that the reference gives, or in every store when it gives none.
99fn document_scoped(model: &Model, keys: &KeyIndex, arg: &str) -> Vec<(RepoPath, String)> {
100    if !is_key_reference(arg) || !paths_of_reference(model, Some(keys), arg).is_empty() {
101        return Vec::new();
102    }
103    let reference = arg.strip_prefix("sokf:").unwrap_or(arg);
104    let Some((head, written)) = reference.split_once('#') else {
105        return Vec::new();
106    };
107    let stores = stores_of(model, split_store(head).0);
108    // The lookup tries the key as written and then each id that it can
109    // name, and keeps the documents of the first that some document has.
110    std::iter::once(written.to_string())
111        .chain(crate::markdown::key_ids(written))
112        .map(|slug| {
113            let mut found: Vec<(RepoPath, String)> = keys
114                .document
115                .keys()
116                .filter(|(p, s)| {
117                    *s == slug && model.knowledge_of(p).is_some_and(|k| stores.contains(&k))
118                })
119                .cloned()
120                .collect();
121            found.sort();
122            found
123        })
124        .find(|found| !found.is_empty())
125        .unwrap_or_default()
126}
127
128/// `stores_of` returns the stores that a reference searches: each store of
129/// the name it gives, or every store when it gives none.
130fn stores_of(model: &Model, store: Option<&str>) -> Vec<usize> {
131    match store {
132        None => (0..model.knowledges.len()).collect(),
133        Some(s) => model.stores_named(s),
134    }
135}
136
137/// `note` returns the note that `graph` prints for `arg`, when `arg` is a
138/// reference to a key alone that one document captures at document scope
139/// only. The note gives the reference that names the key in a link
140/// (CLI-7_AC-98).
141pub(super) fn note(model: &Model, keys: Option<&KeyIndex>, arg: &str) -> Option<String> {
142    let [(path, slug)] = document_scoped(model, keys?, arg).try_into().ok()?;
143    let reference = key_reference(model, &path, &slug)?;
144    let id = reference.split_once('#')?.0;
145    Some(format!(
146        "`{arg}` is unique only within `{id}`, so link it as `{reference}`"
147    ))
148}
149
150/// `key_reference` returns the reference `<id>#<slug>` to the key `slug` of
151/// the document at `path`. The id has its store before it when another
152/// store has a document with the same id. `key_reference` returns `None`
153/// when another document of the same store has the id, because no reference
154/// then names the document.
155fn key_reference(model: &Model, path: &RepoPath, slug: &str) -> Option<String> {
156    let (k, id) = id_of(model, path)?;
157    let mut elsewhere = false;
158    for o in 0..model.knowledges.len() {
159        if model.ids(o, &id).into_iter().any(|p| &p != path) {
160            if o == k {
161                return None;
162            }
163            elsewhere = true;
164        }
165    }
166    Some(if elsewhere {
167        format!("{}:{id}#{slug}", model.store_name(k)?)
168    } else {
169        format!("{id}#{slug}")
170    })
171}
172
173/// `id_of` returns the store and the id of the document at `path`.
174fn id_of(model: &Model, path: &RepoPath) -> Option<(usize, String)> {
175    if let Some(found) = model.id_at(path) {
176        Some(found)
177    } else {
178        // The run does not hold this document, so the id comes from the
179        // store's row.
180        let k = model.knowledge_of(path)?;
181        let id = model.fallback.as_ref()?.fields(path)?.id?;
182        Some((k, id))
183    }
184}
185
186/// `paths_of_reference` returns the paths of every document and schema that
187/// a reference identifies, when it is written outside every store, such as
188/// on the command line. The reference
189/// `[sokf:][<store>:]<id>[#<fragment>]` identifies the document with that
190/// id, whatever its fragment. The reference `[sokf:][<store>:]#<key>`
191/// identifies the document that captures the key, when only one document
192/// captures it (CLI-7_AC-29 to CLI-7_AC-32). A reference with no store
193/// searches every root.
194fn paths_of_reference(model: &Model, keys: Option<&KeyIndex>, arg: &str) -> Vec<RepoPath> {
195    // sokf-implements: CLI-7_AC-60
196    let reference = arg.strip_prefix("sokf:").unwrap_or(arg);
197    let (head, fragment) = match reference.split_once('#') {
198        Some((h, f)) => (h, Some(f)),
199        None => (reference, None),
200    };
201    let (store, id) = split_store(head);
202    let stores = stores_of(model, store);
203    let mut paths: Vec<RepoPath> =
204        if id.is_empty() {
205            let (Some(keys), Some(key)) = (keys, fragment.filter(|f| !f.is_empty())) else {
206                return Vec::new();
207            };
208            // The index holds each key under its id, so the lookup tries the
209            // key as written and then each id that it can name, and stops at
210            // the first that some key has.
211            std::iter::once(key.to_string())
212                .chain(crate::markdown::key_ids(key))
213                .map(|key| {
214                    keys.repository
215                        .get(&key)
216                        .into_iter()
217                        .flatten()
218                        .chain(stores.iter().flat_map(|&k| {
219                            keys.knowledge.get(&(k, key.clone())).into_iter().flatten()
220                        }))
221                        .filter(|e| stores.contains(&e.knowledge))
222                        .map(|e| e.path.clone())
223                        .collect::<Vec<_>>()
224                })
225                .find(|paths| !paths.is_empty())
226                .unwrap_or_default()
227        } else {
228            // The lookup searches the run's documents and the store's rows
229            // (CACHE-1_AC-21).
230            stores.iter().flat_map(|&k| model.ids(k, id)).collect()
231        };
232    paths.sort();
233    paths.dedup();
234    paths
235}
236
237/// `qualified` returns the qualified form of `arg` for each document in
238/// `paths`, as advice for an ambiguous reference. Each form starts with the
239/// store's name, or with its whole identity when another root shares that
240/// name. The document's id follows, or `#key` for a reference to a key
241/// alone. `qualified` returns an empty string when it cannot qualify every
242/// document.
243fn qualified(model: &Model, arg: &str, paths: &[RepoPath]) -> String {
244    let key = is_key_reference(arg)
245        .then(|| arg.split_once('#').map(|(_, k)| k))
246        .flatten();
247    let forms: Vec<String> = paths
248        .iter()
249        .filter_map(|p| {
250            let (k, id) = id_of(model, p)?;
251            let store = model.store_name(k)?;
252            Some(match key {
253                Some(key) => format!("`{store}:#{key}`"),
254                None => format!("`{store}:{id}`"),
255            })
256        })
257        .collect();
258    if forms.len() == paths.len() {
259        format!(". Write {}", forms.join(" or "))
260    } else {
261        String::new()
262    }
263}
264
265fn join(paths: &[RepoPath]) -> String {
266    paths
267        .iter()
268        .map(RepoPath::as_str)
269        .collect::<Vec<_>>()
270        .join(", ")
271}
272
273/// `resolve_id` returns the one document that a reference identifies across
274/// every root, or refuses a reference that identifies no document or more
275/// than one (CLI-8_AC-9).
276// sokf-implements: CLI-8_AC-9
277// sokf-implements: CLI-8_AC-10
278// sokf-implements: CLI-8_AC-11
279// sokf-implements: CLI-8_AC-6
280// sokf-implements: FORMAT-2_AC-1
281pub fn resolve_id(model: &Model, keys: Option<&KeyIndex>, id: &str) -> Result<RepoPath> {
282    match paths_of_reference(model, keys, id).as_slice() {
283        [] => Err(Error::Locate(format!("`{id}` identifies no document"))),
284        [one] => Ok(one.clone()),
285        many => Err(Error::Locate(format!(
286            "`{id}` identifies more than one document: {}{}",
287            join(many),
288            qualified(model, id, many)
289        ))),
290    }
291}
292
293/// `Reading` is what an argument names when the tool reads it both as an id
294/// and as a path, and exactly one reading resolves.
295enum Reading {
296    /// The document or schema that the argument identifies as an id, or as a
297    /// reference to a key that the document captures.
298    Id(RepoPath),
299    /// The file or directory that the argument names as a path.
300    Path(RepoPath),
301}
302
303/// `read` reads `arg` both as an `id` and as a path, and refuses it unless
304/// exactly one reading resolves (CLI-7_AC-19, CLI-7_AC-20). The message of
305/// a refusal says why, for the command to name.
306// sokf-implements: CLI-7_AC-29
307// sokf-implements: CLI-7_AC-30
308// sokf-implements: CLI-7_AC-31
309// sokf-implements: CLI-7_AC-32
310// sokf-implements: CLI-7_AC-33
311// sokf-implements: CLI-1_AC-7
312// sokf-implements: CLI-1_AC-8
313// sokf-implements: CLI-7_AC-4
314// sokf-implements: CLI-7_AC-19
315// sokf-implements: CLI-7_AC-20
316#[expect(
317    clippy::case_sensitive_file_extension_comparisons,
318    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"
319)]
320fn read(
321    model: &Model,
322    keys: Option<&KeyIndex>,
323    cwd: &Path,
324    arg: &str,
325) -> std::result::Result<Reading, String> {
326    // The function reads a word shaped as a path only as a path, even when
327    // a document has that word as its id.
328    // sokf-implements: CLI-7_AC-28
329    let path_shaped = arg.starts_with('.') || arg.ends_with('/') || arg.ends_with(".md");
330    let ids = if path_shaped {
331        Vec::new()
332    } else {
333        paths_of_reference(model, keys, arg)
334    };
335    let path = PathArg(arg).resolve(&model.tree.root, cwd);
336    match (ids.as_slice(), path) {
337        ([_, ..], Some(p)) => Err(format!(
338            "`{arg}` is both an id ({}) and a path ({p})",
339            join(&ids)
340        )),
341        ([_, _, ..], None) => Err(format!(
342            "`{arg}` identifies more than one document: {}{}",
343            join(&ids),
344            qualified(model, arg, &ids)
345        )),
346        ([one], None) => Ok(Reading::Id(one.clone())),
347        ([], Some(p)) => Ok(Reading::Path(p)),
348        ([], None) => {
349            // A key that no document captures at repository or knowledge
350            // scope can still be a key of document scope.
351            let scoped = keys.map_or_else(Vec::new, |k| document_scoped(model, k, arg));
352            match scoped.as_slice() {
353                // sokf-implements: CLI-7_AC-98
354                [(one, _)] => Ok(Reading::Id(one.clone())),
355                // sokf-implements: CLI-7_AC-100
356                [] => Err(format!(
357                    "`{arg}` is neither an id nor a path in the repository"
358                )),
359                // sokf-implements: CLI-7_AC-99
360                many => {
361                    let forms: Vec<String> = many
362                        .iter()
363                        .map(|(p, slug)| match key_reference(model, p, slug) {
364                            Some(r) => format!("`{r}`"),
365                            None => p.to_string(),
366                        })
367                        .collect();
368                    Err(format!(
369                        "`{arg}` is a key of document scope that more than one document captures. Write {}",
370                        capped(&forms)
371                    ))
372                }
373            }
374        }
375    }
376}
377
378/// `resolve_start` reads `arg` as `read` does. When the start is a directory
379/// or a repository file, the function adds it to the graph as a node.
380pub fn resolve_start(
381    graph: &mut Graph,
382    model: &Model,
383    keys: Option<&KeyIndex>,
384    cwd: &Path,
385    arg: &str,
386) -> Result<Start> {
387    match read(model, keys, cwd, arg).map_err(Error::Start)? {
388        // For a reference to a key alone, and for `<id>#<key>` when the
389        // document captures the key, the start is the key's node when the
390        // graph has one.
391        // sokf-implements: CLI-7_AC-32
392        // sokf-implements: CLI-7_AC-97
393        Reading::Id(one) => Ok(key_start(graph, model, keys, arg, &one)),
394        Reading::Path(p) => Ok(path_start(graph, model, p)),
395    }
396}
397
398/// `resolve_document` reads `arg` as `resolve_start` reads a `START`, and
399/// returns the document or schema that it names. It refuses an argument
400/// that names no document of a knowledge store, such as a directory, an
401/// asset, or an additional file.
402// sokf-implements: CLI-17_AC-1
403// sokf-implements: CLI-17_AC-2
404// sokf-implements: CLI-17_AC-3
405pub fn resolve_document(
406    model: &Model,
407    keys: Option<&KeyIndex>,
408    cwd: &Path,
409    arg: &str,
410) -> Result<RepoPath> {
411    match read(model, keys, cwd, arg).map_err(Error::Guide)? {
412        Reading::Id(path) => Ok(path),
413        Reading::Path(path) => match model.tree.file(&path).map(|f| f.kind) {
414            Some(FileKind::Document | FileKind::Schema) => Ok(path),
415            _ => Err(Error::Guide(format!(
416                "`{arg}` names {path}, which is no document of a knowledge store"
417            ))),
418        },
419    }
420}
421
422/// `LISTED` is the number of references that the error for a key of
423/// document scope lists before it counts the rest (CLI-7_AC-99).
424const LISTED: usize = 10;
425
426/// `capped` joins the first `LISTED` of `forms` with "or", in their order,
427/// and follows them with "and N more" when `forms` holds more.
428// sokf-implements: CLI-7_AC-99
429fn capped(forms: &[String]) -> String {
430    let listed = forms[..forms.len().min(LISTED)].join(" or ");
431    match forms.len().saturating_sub(LISTED) {
432        0 => listed,
433        more => format!("{listed}, and {more} more"),
434    }
435}
436
437/// `key_start` returns the start of `arg` in the document at `path`: the
438/// node of the key that `arg` names, when the graph has one, and the
439/// document otherwise.
440fn key_start(
441    graph: &Graph,
442    model: &Model,
443    keys: Option<&KeyIndex>,
444    arg: &str,
445    path: &RepoPath,
446) -> Start {
447    Start::Node(
448        keys.and_then(|k| key_entry(model, k, arg))
449            .map(|(_, slug)| NodeKey::Key(format!("{path}#{slug}")))
450            .filter(|k| graph.node(k).is_some())
451            .unwrap_or_else(|| NodeKey::Path(path.clone())),
452    )
453}
454
455/// `path_start` reads a path as a start. It tries each reading in order: a
456/// root, a directory, a node that the graph has, and then a repository
457/// file.
458fn path_start(graph: &mut Graph, model: &Model, path: RepoPath) -> Start {
459    if model.tree.roots.contains(&path) {
460        return Start::Container(path);
461    }
462    if path.to_fs(&model.tree.root).is_dir() {
463        graph.ensure(path.clone(), NodeKind::Directory);
464        return if model.knowledge_of(&path).is_some() {
465            Start::Container(path)
466        } else {
467            Start::Outside(path)
468        };
469    }
470    let key = NodeKey::Path(path.clone());
471    if graph.node(&key).is_none() {
472        graph.ensure(path, NodeKind::File);
473    }
474    Start::Node(key)
475}
476
477#[cfg(test)]
478mod tests;