sokf_core/graph/traverse.rs
1//! This module runs one `GraphQuery` over the graph. It returns a tree of
2//! rows, and the nodes and edges that the tree mentions. The query's depth,
3//! limit, and filters decide which nodes and edges the tree holds (CLI-7).
4
5use std::{
6 collections::{BTreeMap, BTreeSet, HashMap},
7 path::Path,
8};
9
10use serde_json::Value;
11
12use super::{Graph, NodeKey, NodeKind, Start, json, resolve_start, start::note};
13use crate::{Expr, Model, RepoPath, Result, model::KeyIndex};
14
15/// `LIMIT` is the number of entries of one group that print without
16/// `--all` (CLI-7_AC-69). A group is the entries of a directory or the edges
17/// of one relationship of a node.
18pub const LIMIT: usize = 20;
19
20/// `GraphQuery` holds the bounds of `sokf graph`, one field for each bound.
21#[derive(Debug, Clone)]
22pub struct GraphQuery {
23 /// The starts that `START...` gives. When it is empty, the query starts
24 /// at every knowledge root.
25 pub start: Vec<String>,
26 /// The number of hops that `--depth` follows from a start that is a
27 /// document, a file, or a key.
28 pub depth: usize,
29 /// Whether `--depth` was given. When it was, each line of a layout
30 /// prints its edges to `depth` hops, as a document start does
31 /// (CLI-7_AC-65).
32 pub layout_edges: bool,
33 /// The `-l` selectors. A document matches when any one of them is true.
34 pub selector: Vec<Expr>,
35 /// The `--edge` selectors. An edge matches when any one of them is true.
36 pub edge: Vec<Expr>,
37 /// The `--to` selectors. A target matches when any one of them is true.
38 pub to: Vec<Expr>,
39 /// The expression of `--query`, which projects the JSON form of the
40 /// result.
41 pub query: Option<Expr>,
42 /// `all` is whether `--all` was given. When it was, the result prints
43 /// every entry past the limit and every region of a folded include.
44 pub all: bool,
45 /// `archived` is whether `--archived` was given. When it was, the result
46 /// prints the archived documents and their edges.
47 pub archived: bool,
48}
49
50impl Default for GraphQuery {
51 fn default() -> Self {
52 GraphQuery {
53 start: Vec::new(),
54 depth: 1,
55 layout_edges: false,
56 selector: Vec::new(),
57 edge: Vec::new(),
58 to: Vec::new(),
59 query: None,
60 all: false,
61 archived: false,
62 }
63 }
64}
65
66/// `Row` is a node that the tree prints with the lines under it. A row is
67/// a start or a node of a layout.
68#[derive(Debug, Clone, PartialEq, Eq)]
69pub struct Row {
70 /// The node.
71 pub node: NodeKey,
72 /// Whether the node is a row elsewhere in the tree, in which case this
73 /// row prints as one line marked `(*)`.
74 pub elsewhere: bool,
75 /// The layout under a container, or the edges under a row.
76 pub entries: Vec<Entry>,
77}
78
79/// `Entry` is one line under a row.
80#[derive(Debug, Clone, PartialEq, Eq)]
81pub enum Entry {
82 /// A node of a container's layout.
83 Layout(Row),
84 /// An edge of a row or an expanded node.
85 Edge {
86 /// The edge's index in the graph.
87 edge: usize,
88 /// The edge's target.
89 target: NodeKey,
90 /// The target's edges, when the target expands at this entry.
91 expanded: Vec<Entry>,
92 /// Whether the target's edges print elsewhere, in which case the
93 /// line is marked `(*)`.
94 elsewhere: bool,
95 /// The number of regions of a folded include, or of markers of a
96 /// folded marker edge, or 0 when the edge is not folded (CLI-7_AC-70,
97 /// CLI-7_AC-91).
98 folded: usize,
99 /// Whether the edge belongs to a directory that holds the row's
100 /// file, not to the row itself (CLI-7_AC-72).
101 via: bool,
102 },
103 /// The number of entries of a group past the limit, where the group is
104 /// a directory or one relationship (CLI-7_AC-69).
105 More {
106 /// The relationship of the group, or `None` when the group is a
107 /// directory.
108 rel: Option<String>,
109 /// The entries left out.
110 count: usize,
111 },
112}
113
114/// `Summary` counts what a view printed, and what the same view prints
115/// with `--all`, `--archived`, and no filter (CLI-7_AC-77).
116#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
117pub struct Summary {
118 /// The documents printed, out of the documents of the whole view.
119 pub documents: Count,
120 /// The archived documents printed, out of the archived documents of
121 /// the whole view.
122 pub archived: Count,
123}
124
125/// `Count` is the number of items that printed, out of a total.
126#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
127pub struct Count {
128 /// The number that printed.
129 pub shown: usize,
130 /// The number that the whole view holds.
131 pub total: usize,
132}
133
134impl Summary {
135 /// `line` returns the last line of the text form: `<a> / <b> docs`,
136 /// followed by ` (<c> / <d> archived)` when the view reaches an archived
137 /// document (CLI-7_AC-77).
138 pub fn line(&self) -> String {
139 let docs = format!("{} / {} docs", self.documents.shown, self.documents.total);
140 if self.archived.total > 0 {
141 format!(
142 "{docs} ({} / {} archived)",
143 self.archived.shown, self.archived.total
144 )
145 } else {
146 docs
147 }
148 }
149}
150
151/// `GraphResult` is the result of one query.
152#[derive(Debug, Clone, PartialEq, Eq)]
153pub struct GraphResult {
154 /// The node of each start, in the order given.
155 pub start: Vec<NodeKey>,
156 /// One tree for each start. It is empty when a `query` is given.
157 pub rows: Vec<Row>,
158 /// Every node the tree mentions, in node order.
159 pub nodes: Vec<NodeKey>,
160 /// Every edge the tree mentions and the inverse of each, in edge order.
161 pub edges: Vec<usize>,
162 /// The number of regions of each folded include, or of markers of each
163 /// folded marker edge, and of its inverse, keyed by edge.
164 pub folded: BTreeMap<usize, usize>,
165 /// The counts of the last line of the text form.
166 pub summary: Summary,
167 /// The `query` result, when one was given.
168 pub projection: Option<Value>,
169 /// The notes about the starts, in the order of the starts, which the
170 /// command prints to standard error (CLI-7_AC-98).
171 pub notes: Vec<String>,
172}
173
174/// `starts` returns the starts of `query` in the order given, or each
175/// knowledge root when `query` gives none. It adds to `graph` each
176/// directory or file that a start refers to.
177// sokf-implements: CLI-7_AC-3
178pub(crate) fn starts(
179 graph: &mut Graph,
180 model: &Model,
181 keys: Option<&KeyIndex>,
182 cwd: &Path,
183 query: &GraphQuery,
184) -> Result<Vec<Start>> {
185 if query.start.is_empty() {
186 return Ok(model
187 .tree
188 .roots
189 .iter()
190 .map(|r| Start::Container(r.clone()))
191 .collect());
192 }
193 query
194 .start
195 .iter()
196 .map(|arg| resolve_start(graph, model, keys, cwd, arg))
197 .collect()
198}
199
200/// `run` runs `query` over `graph`. It adds to `graph` each directory or
201/// file that a start refers to.
202// sokf-implements: CLI-7_AC-34
203// sokf-implements: CLI-7_AC-35
204// sokf-implements: CLI-7_AC-87
205// sokf-implements: CLI-7_AC-38
206// sokf-implements: CLI-7_AC-46
207// sokf-implements: CLI-7_AC-47
208// sokf-implements: CLI-7_AC-79
209pub fn run(
210 graph: &mut Graph,
211 model: &Model,
212 keys: Option<&KeyIndex>,
213 cwd: &Path,
214 query: &GraphQuery,
215) -> Result<GraphResult> {
216 let starts = starts(graph, model, keys, cwd, query)?;
217 // A node that a start refers to prints even when it is archived. So does
218 // the defining document of each key that a start refers to.
219 let named: BTreeSet<NodeKey> = starts
220 .iter()
221 .filter(|s| matches!(s, Start::Node(_)))
222 .map(Start::key)
223 .flat_map(|k| {
224 let document = match &k {
225 NodeKey::Key(text) => text
226 .split_once('#')
227 .and_then(|(p, _)| RepoPath::parse(p))
228 .map(NodeKey::Path),
229 _ => None,
230 };
231 std::iter::once(k).chain(document)
232 })
233 .collect();
234 let (rows, m) = tree(graph, &starts, &named, query);
235 // The whole view has no limit and no fold, does not hide archived
236 // documents, and applies no filter.
237 let whole_query = GraphQuery {
238 selector: Vec::new(),
239 edge: Vec::new(),
240 to: Vec::new(),
241 query: None,
242 all: true,
243 archived: true,
244 ..query.clone()
245 };
246 let whole = if query.all && query.archived && !filtered(query) {
247 None
248 } else {
249 Some(tree(graph, &starts, &named, &whole_query).1)
250 };
251 let whole = whole.as_ref().unwrap_or(&m);
252 // `run` hydrates each node that the result prints. Hydrating a node loads
253 // its fields (CACHE-1_AC-22).
254 for key in &m.nodes {
255 graph.hydrate(key);
256 }
257 // The total counts each node that either view reaches. A node expands
258 // only at the first edge that reaches it. It then follows its own edges
259 // for the hops that remain after that edge. The whole view expands a node
260 // at its first edge. This run's view applies its filters and its limit,
261 // which can drop that edge. When they do, this run's view expands the node
262 // at a different edge, where more hops can remain. This run's view can
263 // then reach nodes that the whole view does not reach.
264 let union: BTreeSet<&NodeKey> = m.nodes.iter().chain(&whole.nodes).collect();
265 let documents = |nodes: &mut dyn Iterator<Item = &NodeKey>| {
266 nodes
267 .filter(|k| graph.kind(k) == Some(NodeKind::Document))
268 .count()
269 };
270 let archived = |nodes: &mut dyn Iterator<Item = &NodeKey>| {
271 nodes
272 .filter(|k| graph.kind(k) == Some(NodeKind::Document) && graph.is_archived(k))
273 .count()
274 };
275 let summary = Summary {
276 documents: Count {
277 shown: documents(&mut m.nodes.iter()),
278 total: documents(&mut union.iter().copied()),
279 },
280 archived: Count {
281 shown: archived(&mut m.nodes.iter()),
282 total: archived(&mut union.iter().copied()),
283 },
284 };
285 let mut result = GraphResult {
286 start: starts.iter().map(Start::key).collect(),
287 rows,
288 nodes: m.nodes.into_iter().collect(),
289 edges: m.edges.into_iter().collect(),
290 folded: m.folded,
291 summary,
292 projection: None,
293 notes: query
294 .start
295 .iter()
296 .filter_map(|arg| note(model, keys, arg))
297 .collect(),
298 };
299 if let Some(q) = &query.query {
300 // sokf-implements: CLI-7_AC-22
301 result.projection = Some(q.eval(&json::bounded(graph, &result))?);
302 result.rows.clear();
303 }
304 Ok(result)
305}
306
307/// `filtered` returns whether a query filters, that is, whether it gives a
308/// selector, an `--edge`, or a `--to`.
309fn filtered(query: &GraphQuery) -> bool {
310 !(query.selector.is_empty() && query.edge.is_empty() && query.to.is_empty())
311}
312
313/// `tree` builds the tree of `starts`. It lays out each start, adds the
314/// edges under each row, and then marks each line whose node prints
315/// elsewhere. It returns the rows of the tree, and the nodes, edges, and
316/// folded counts that those rows mention.
317fn tree(
318 graph: &mut Graph,
319 starts: &[Start],
320 named: &BTreeSet<NodeKey>,
321 query: &GraphQuery,
322) -> (Vec<Row>, Mentions) {
323 let mut t = Traversal::new(graph, query, named.clone());
324 let mut rows: Vec<Row> = Vec::new();
325 for start in starts {
326 let row = match start {
327 Start::Container(p) => Row {
328 node: NodeKey::Path(p.clone()),
329 elsewhere: false,
330 entries: t.layout(p),
331 },
332 Start::Outside(p) => {
333 // The directory is a row: its own edges, and those of the
334 // directories that hold it, print before the nodes under it.
335 let node = NodeKey::Path(p.clone());
336 t.rows.insert(node.clone());
337 Row {
338 node,
339 elsewhere: false,
340 entries: t.outside(p),
341 }
342 }
343 // sokf-implements: CLI-7_AC-37
344 Start::Node(k) => t.row(k.clone()),
345 };
346 // With a selector, `tree` drops a container start that holds no
347 // matching node. It keeps every other start, even one with no
348 // entries yet. The reason is that `fill` adds the edges of a node start
349 // and of a directory outside every knowledge root after this loop.
350 let container = matches!(start, Start::Container(_));
351 if container && !query.selector.is_empty() && row.entries.is_empty() {
352 continue;
353 }
354 rows.push(row);
355 }
356 for row in &mut rows {
357 t.fill(row, true);
358 }
359 let mut seen = BTreeSet::new();
360 for row in &mut rows {
361 t.settle(&mut row.entries, 1, &mut seen);
362 }
363 let mut m = Mentions::default();
364 for row in &rows {
365 t.mention(row, &mut m);
366 }
367 (rows, m)
368}
369
370/// `Mentions` holds the nodes, edges, and folded counts that the tree
371/// mentions.
372#[derive(Default)]
373struct Mentions {
374 nodes: BTreeSet<NodeKey>,
375 edges: BTreeSet<usize>,
376 folded: BTreeMap<usize, usize>,
377}
378
379struct Traversal<'a> {
380 graph: &'a mut Graph,
381 query: &'a GraphQuery,
382 rows: BTreeSet<NodeKey>,
383 expanded: BTreeSet<NodeKey>,
384 json: HashMap<NodeKey, Value>,
385 /// The nodes that the starts refer to, and the defining document of each
386 /// key among them. These nodes print even when they are archived.
387 named: BTreeSet<NodeKey>,
388 /// The number of times that a document was left out because it is
389 /// archived.
390 hidden: usize,
391 /// The nodes under each directory, in key order. The first layout
392 /// builds this map in one pass over the nodes.
393 children: Option<HashMap<NodeKey, Vec<(NodeKey, NodeKind)>>>,
394}
395
396impl<'a> Traversal<'a> {
397 fn new(graph: &'a mut Graph, query: &'a GraphQuery, named: BTreeSet<NodeKey>) -> Self {
398 Traversal {
399 graph,
400 query,
401 rows: BTreeSet::new(),
402 expanded: BTreeSet::new(),
403 json: HashMap::new(),
404 named,
405 hidden: 0,
406 children: None,
407 }
408 }
409
410 /// `node_json` returns the JSON form of a node, which it builds once.
411 /// A predicate reads the node's fields, so `node_json` hydrates the
412 /// node first (CACHE-1_AC-22).
413 fn node_json(&mut self, key: &NodeKey) -> &Value {
414 if !self.json.contains_key(key) {
415 self.graph.hydrate(key);
416 let value = self.graph.node(key).map_or(Value::Null, json::node_json);
417 self.json.insert(key.clone(), value);
418 }
419 &self.json[key]
420 }
421
422 /// `document_matches` returns whether some expression of `exprs`, the
423 /// selector or `--to`, is true of the node, which must be a document.
424 /// When there is no expression, every node matches.
425 // sokf-implements: CLI-7_AC-8
426 // sokf-implements: CLI-7_AC-45
427 // sokf-implements: CLI-7_AC-86
428 fn document_matches(&mut self, key: &NodeKey, exprs: &[Expr]) -> bool {
429 if exprs.is_empty() {
430 return true;
431 }
432 if self.graph.kind(key) != Some(NodeKind::Document) {
433 return false;
434 }
435 let value = self.node_json(key);
436 exprs.iter().any(|e| e.truthy(value))
437 }
438
439 /// `hides` returns whether `key` is an archived document that this run
440 /// leaves out, and counts it when it is. The archive rule applies before
441 /// the filters (CLI-7_AC-67, CLI-7_AC-68).
442 // sokf-implements: CLI-7_AC-67
443 // sokf-implements: CLI-7_AC-68
444 // sokf-implements: CLI-7_AC-82
445 fn hides(&mut self, key: &NodeKey) -> bool {
446 let hidden =
447 !self.query.archived && self.graph.is_archived(key) && !self.named.contains(key);
448 if hidden {
449 self.hidden += 1;
450 }
451 hidden
452 }
453
454 /// `row` claims `key` as a row, or marks it as a row elsewhere when
455 /// another row has claimed it.
456 fn row(&mut self, key: NodeKey) -> Row {
457 let elsewhere = !self.rows.insert(key.clone());
458 Row {
459 node: key,
460 elsewhere,
461 entries: Vec::new(),
462 }
463 }
464
465 /// `fill` adds the edges under every start that is a row. A line of a
466 /// layout gets no edges unless `--depth` was given.
467 // sokf-implements: CLI-7_AC-2
468 fn fill(&mut self, row: &mut Row, start: bool) {
469 if row.elsewhere {
470 return;
471 }
472 let mut entries = if self.rows.contains(&row.node)
473 && (start || self.query.layout_edges)
474 && self.query.depth >= 1
475 {
476 self.hops(&row.node, 1)
477 } else {
478 Vec::new()
479 };
480 for entry in &mut row.entries {
481 if let Entry::Layout(inner) = entry {
482 self.fill(inner, false);
483 }
484 }
485 entries.append(&mut row.entries);
486 row.entries = entries;
487 }
488
489 /// `hops` returns the edges of `node` at `hop`, and expands each target
490 /// at its first appearance below `depth`. First it drops each edge to
491 /// an archived document that this run leaves out. Then it drops each
492 /// edge that a filter rejects. Next, `mirror` drops each untyped mention
493 /// that a typed link repeats. Then `fold` merges into one edge the
494 /// includes of regions of the same file, and the markers of one file
495 /// under a document. Last, the limit leaves out the
496 /// edges past `LIMIT`. `node` can be a row that is a file, or a directory
497 /// outside every knowledge root. In that case, `hops` also adds the edges
498 /// from each directory above `node` to the document that describes that
499 /// directory.
500 // sokf-implements: CLI-7_AC-9
501 // sokf-implements: CLI-7_AC-10
502 // sokf-implements: CLI-7_AC-48
503 fn hops(&mut self, node: &NodeKey, hop: usize) -> Vec<Entry> {
504 let mut candidates: Vec<(usize, bool)> = self
505 .graph
506 .edge_indices_from(node)
507 .iter()
508 .map(|&i| (i, false))
509 .collect();
510 // A key's document comes first, then the documents that cite it.
511 if self.graph.kind(node) == Some(NodeKind::Key) {
512 candidates.sort_by_key(|&(i, _)| self.graph.edges[i].rel != "defined-in");
513 }
514 if hop == 1 && self.graph.kind(node).is_some_and(NodeKind::shows_via) {
515 candidates.extend(self.ancestors(node));
516 }
517 let query = self.query;
518 let mut kept = Vec::new();
519 for (i, via) in candidates {
520 let to = self.graph.edges[i].to.clone();
521 if self.hides(&to) {
522 continue;
523 }
524 if !query.edge.is_empty() {
525 let value = json::edge_json(&self.graph.edges[i]);
526 if !query.edge.iter().any(|e| e.truthy(&value)) {
527 continue;
528 }
529 }
530 if !self.document_matches(&to, &query.to) {
531 continue;
532 }
533 kept.push((i, via));
534 }
535 let groups = self.fold(self.mirror(kept));
536 let mut out = Vec::new();
537 let mut per_rel: HashMap<String, usize> = HashMap::new();
538 let mut past: Vec<(String, usize)> = Vec::new();
539 for (i, via, members) in groups {
540 let rel = self.graph.edges[i].rel.clone();
541 let n = per_rel.entry(rel.clone()).or_insert(0);
542 *n += 1;
543 // sokf-implements: CLI-7_AC-69
544 if !self.query.all && *n > LIMIT {
545 match past.iter_mut().find(|(r, _)| *r == rel) {
546 Some((_, count)) => *count += 1,
547 None => past.push((rel, 1)),
548 }
549 continue;
550 }
551 let target = self.graph.edges[i].to.clone();
552 let expanded =
553 if !via && self.expands(&target, hop) && self.expanded.insert(target.clone()) {
554 self.hops(&target, hop + 1)
555 } else {
556 Vec::new()
557 };
558 out.push(Entry::Edge {
559 edge: i,
560 target,
561 expanded,
562 elsewhere: false,
563 folded: members,
564 via,
565 });
566 }
567 for (rel, count) in past {
568 out.push(Entry::More {
569 rel: Some(rel),
570 count,
571 });
572 }
573 out
574 }
575
576 /// `expands` returns whether a target reached at `hop` can expand: the
577 /// hop is below the depth, and the target is neither a row nor a missing
578 /// node.
579 // sokf-implements: CLI-7_AC-6
580 // sokf-implements: CLI-7_AC-39
581 // sokf-implements: CLI-7_AC-40
582 fn expands(&self, target: &NodeKey, hop: usize) -> bool {
583 hop < self.query.depth
584 && !self.rows.contains(target)
585 && self.graph.kind(target) != Some(NodeKind::Missing)
586 }
587
588 /// `settle` is the second pass over the tree, after the first pass, in
589 /// which `fill` adds the edges under each row. `settle` sets `elsewhere` on each edge whose
590 /// target is a row or expands at another entry. `settle` walks the
591 /// entries in the same order as the first pass, and tests each target
592 /// with the same rule. So the first entry where a target can expand is
593 /// the entry where the first pass expanded it. `settle` records that
594 /// target in `seen` and leaves that entry unmarked.
595 fn settle(&self, entries: &mut [Entry], hop: usize, seen: &mut BTreeSet<NodeKey>) {
596 for entry in entries {
597 match entry {
598 Entry::Layout(row) => self.settle(&mut row.entries, 1, seen),
599 Entry::Edge {
600 target,
601 expanded,
602 elsewhere,
603 via,
604 ..
605 } => {
606 let expanded_here =
607 !*via && self.expands(target, hop) && seen.insert(target.clone());
608 *elsewhere = !expanded_here
609 && (self.rows.contains(target) || self.expanded.contains(target));
610 self.settle(expanded, hop + 1, seen);
611 }
612 Entry::More { .. } => {}
613 }
614 }
615 }
616
617 /// `mention` collects every node and edge that the tree mentions, and
618 /// the inverse of each edge.
619 fn mention(&self, row: &Row, m: &mut Mentions) {
620 m.nodes.insert(row.node.clone());
621 self.mention_entries(&row.entries, m);
622 }
623
624 fn mention_entries(&self, entries: &[Entry], m: &mut Mentions) {
625 for entry in entries {
626 match entry {
627 Entry::Layout(row) => self.mention(row, m),
628 Entry::Edge {
629 edge,
630 target,
631 expanded,
632 folded,
633 via,
634 ..
635 } => {
636 let e = &self.graph.edges[*edge];
637 m.nodes.insert(target.clone());
638 if *via {
639 m.nodes.insert(e.from.clone());
640 }
641 m.edges.insert(*edge);
642 // sokf-implements: CLI-7_AC-56
643 let inverses: Vec<usize> = self.graph.inverse_indices(e).collect();
644 if *folded > 0 {
645 m.folded.insert(*edge, *folded);
646 for &i in &inverses {
647 m.folded.insert(i, *folded);
648 }
649 }
650 m.edges.extend(inverses);
651 self.mention_entries(expanded, m);
652 }
653 Entry::More { .. } => {}
654 }
655 }
656 }
657}
658
659mod layout;
660mod select;
661
662#[cfg(test)]
663mod tests;