Skip to main content

sokf_core/api/
graph.rs

1//! This module runs the `sokf graph` command (CLI-7).
2
3use std::{collections::BTreeSet, path::PathBuf, rc::Rc};
4
5use crate::{
6    Cache, CacheMode, Model, RepoPath, RepoRoot, Result, config,
7    graph::{self, EdgeKind, Graph, GraphQuery, GraphResult, Hydrator, NodeKey, RawEdge},
8    model::{KeyIndex, ParseMode, parse_source},
9    source,
10};
11
12/// `GraphOptions` holds the options of `sokf graph`.
13#[derive(Debug, Clone)]
14pub struct GraphOptions {
15    /// `query` is the query that `graph` runs on the graph.
16    pub query: GraphQuery,
17    /// `cwd` is the current directory, from which each `START` path resolves.
18    pub cwd: PathBuf,
19    /// `cache` is the cache mode. It is `Off` when the command has `--no-cache`.
20    pub cache: CacheMode,
21}
22
23/// `graph` builds the graph and runs the query on it. With the cache on, it
24/// first checks the documents that changed since the last check, as `validate`
25/// does, so that the store is current before `graph` reads its edges and keys.
26/// The graph has a node for each document in the repository, and `graph` reads
27/// from the store only the edges near each `START`. `graph` reads a document's
28/// fields from its file only when the query first visits the document's node.
29/// With `--no-cache`, `graph` reads every document and every edge. The cache is
30/// the only file that `graph` writes.
31// sokf-implements: CLI-9_AC-3
32// sokf-implements: CACHE-1_AC-27
33// sokf-implements: CACHE-1_AC-22
34// sokf-implements: CACHE-1_AC-38
35// sokf-implements: CACHE-1_AC-44
36// sokf-implements: CACHE-1_AC-45
37// sokf-implements: CLI-7_AC-16
38// sokf-implements: CLI-7_AC-17
39// sokf-implements: CLI-7_AC-63
40pub fn graph(root: &RepoRoot, opts: &GraphOptions) -> Result<(Graph, GraphResult)> {
41    let config = config::load_config(root)?;
42    let cache = Cache::open(root, opts.cache);
43    // A `START` that is a key, or an id with a fragment that can name a key,
44    // needs the keys that the schemas define. An id alone doesn't, so `graph`
45    // loads keys only when one of the `START` arguments has a fragment.
46    let keyed = opts.query.start.iter().any(|s| has_fragment(s));
47    // With no `START` and no layout edges, `graph` needs no edge, so it reads
48    // none (CLI-7_AC-1). Otherwise, with `--no-cache`, it builds every edge,
49    // and resolves every marker with every key.
50    let every_edge = !cache.is_on() && (!opts.query.start.is_empty() || opts.query.layout_edges);
51    let (mut model, keys, all_keys): (Model, Option<KeyIndex>, Option<KeyIndex>) = if keyed {
52        let slugs = super::locate::key_slugs(&opts.query.start, has_fragment);
53        let (model, keys) = super::load_keys_for(root, &config, &cache, &slugs)?;
54        (model, Some(keys), None)
55    } else if every_edge {
56        let (model, keys) = super::load_with_keys(root, &config, &cache)?;
57        (model, None, Some(keys))
58    } else {
59        (super::load_for_lookup(root, &config, &cache)?, None, None)
60    };
61    model.marker_check = config.markers;
62    let markers = match keys.as_ref().or(all_keys.as_ref()) {
63        Some(every) if every_edge => super::markers::marker_edges(&model, every, root),
64        _ => Vec::new(),
65    };
66    let mut graph = if cache.is_on() {
67        graph::build_from(&model, Vec::new(), Some(hydrator(root)))
68    } else if every_edge {
69        let mut graph = graph::build(&model);
70        graph.add_edges(markers.clone());
71        graph
72    } else {
73        graph::build_from(&model, Vec::new(), None)
74    };
75    graph.set_archived(model.archived_documents());
76    if let Some(keys) = &keys {
77        for arg in &opts.query.start {
78            if let Some((entry, slug)) = graph::key_entry(&model, keys, arg) {
79                let citing = citing(&model, keys, &cache, &entry.path, &slug);
80                graph.add_key(&entry.path, &slug, &entry.key, entry.line, &citing);
81                graph.add_edges(key_markers(&cache, &markers, &entry.path, &slug));
82            }
83        }
84    }
85    if cache.is_on() {
86        let starts = graph::starts(&mut graph, &model, keys.as_ref(), &opts.cwd, &opts.query)?;
87        let edges = graph::edges_near(&graph, &starts, &opts.query, &cache);
88        graph.add_edges(edges);
89    }
90    let result = graph::run(&mut graph, &model, keys.as_ref(), &opts.cwd, &opts.query)?;
91    Ok((graph, result))
92}
93
94/// `has_fragment` reports whether `arg` is a reference with a fragment that
95/// is not empty, `#key` or `<id>#<fragment>`, whose fragment can name a key.
96fn has_fragment(arg: &str) -> bool {
97    arg.split_once('#').is_some_and(|(_, f)| !f.is_empty())
98}
99
100/// `hydrator` returns the `Hydrator` that reads a document node's fields from
101/// its file when the graph first visits the node (CACHE-1_AC-22).
102fn hydrator(root: &RepoRoot) -> Hydrator {
103    let repo = root.clone();
104    Hydrator(Rc::new(move |path: &RepoPath| {
105        let src = source::load(&repo, path).ok()?;
106        let parsed = parse_source(&src, ParseMode::Document);
107        Some(graph::frontmatter_json(&crate::Document::new(src, parsed)))
108    }))
109}
110
111/// `key_markers` returns an edge to the key `slug` of the document at `path`
112/// from the file of each marker that cites the key, with the marker's line.
113/// With the cache on, it takes the markers from the citations that the check
114/// stores. With `--no-cache`, it takes them from `markers`, the edges of every
115/// marker that the run read.
116// sokf-implements: CLI-7_AC-94
117fn key_markers(cache: &Cache, markers: &[RawEdge], path: &RepoPath, slug: &str) -> Vec<RawEdge> {
118    let key = NodeKey::Key(format!("{path}#{slug}"));
119    let edge = |from: RepoPath, rel: String, line: Option<usize>| RawEdge {
120        from,
121        kind: EdgeKind::Marker,
122        written: key.as_str().to_string(),
123        to: key.clone(),
124        rel,
125        region: None,
126        line,
127        note: None,
128    };
129    if cache.is_on() {
130        cache
131            .stored_citations_of(path, &BTreeSet::new())
132            .into_iter()
133            .filter(|c| c.slug.as_deref() == Some(slug))
134            .filter_map(|c| Some(edge(c.source, c.rel?, Some(c.line))))
135            .collect()
136    } else {
137        markers
138            .iter()
139            .filter(|m| m.to.path() == Some(path) && m.region.as_deref() == Some(slug))
140            .map(|m| edge(m.from.clone(), m.rel.clone(), m.line))
141            .collect()
142    }
143}
144
145/// `citing` returns the paths of the documents that cite the key `slug` of the
146/// document at `path`. With the cache on, it takes them from the citations that
147/// the check stores. With `--no-cache`, it resolves each link in the body of
148/// every document that the run loads. `citing` leaves the document at `path`
149/// out of the result (CLI-7_AC-74).
150// sokf-implements: CLI-7_AC-74
151fn citing(
152    model: &Model,
153    keys: &KeyIndex,
154    cache: &Cache,
155    path: &RepoPath,
156    slug: &str,
157) -> Vec<RepoPath> {
158    let mut out: BTreeSet<RepoPath> = BTreeSet::new();
159    if cache.is_on() {
160        for c in cache.stored_citations_of(path, &BTreeSet::new()) {
161            if c.rel.is_none() && c.slug.as_deref() == Some(slug) {
162                out.insert(c.source);
163            }
164        }
165    } else {
166        for (k, doc) in model.documents() {
167            if doc.type_name().is_none() {
168                continue;
169            }
170            for link in &doc.body.links {
171                let Some(label) = crate::model::keys::Label::of(&link.target) else {
172                    continue;
173                };
174                if let Ok(r) = crate::model::keys::resolve(model, keys, k, label)
175                    && &r.path == path
176                    && r.slug.as_deref() == Some(slug)
177                {
178                    out.insert(doc.path.clone());
179                }
180            }
181        }
182    }
183    out.remove(path);
184    out.into_iter().collect()
185}