Skip to main content

sokf_core/graph/
json.rs

1//! This module defines the JSON form of `sokf graph` (CLI-7_AC-12) as wire types, and the
2//! `output_schema` module generates the published schema from them. The predicates of `-l`, `--edge`, and `--to`
3//! (CLI-7_AC-43) read the same objects, so a predicate reads exactly what the tool prints.
4
5use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema};
6use serde::Serialize;
7use serde_json::{Map, Value};
8
9use super::{Edge, EdgeKind, Graph, GraphResult, Node, NodeKind};
10
11/// The graph of `sokf graph --json`: the starts (the document ids, paths, and keys given on
12/// the command line), then every node and edge that the text form prints, and every inverse
13/// of each printed edge (CLI_P-8).
14#[derive(Serialize, JsonSchema)]
15#[schemars(title = "sokf graph")]
16pub struct GraphJson {
17    /// Each resolved start as a path, in the order given: a key is the path of its document,
18    /// then `#` and the slug of the key. When no start is given, the list holds the knowledge
19    /// roots.
20    start: Vec<String>,
21    /// The nodes, ordered by path. The missing nodes follow, ordered by target.
22    nodes: Vec<NodeJson>,
23    /// The edges, ordered by `from`, then kind, then `to`, then `rel`, then `region`, then
24    /// `note`.
25    edges: Vec<EdgeJson>,
26    /// The counts that the last line of the text form shows: what the graph printed and
27    /// what it left out.
28    summary: SummaryJson,
29}
30
31/// The summary counts what the graph printed and what the same view prints with `--all`,
32/// `--archived`, and no filter, as the last line of the text form does (CLI-7_AC-78).
33// sokf-implements: CLI-7_AC-78
34#[derive(Serialize, JsonSchema)]
35#[schemars(rename = "Summary")]
36struct SummaryJson {
37    /// The document nodes.
38    documents: CountJson,
39    /// The archived documents.
40    archived: CountJson,
41}
42
43/// What the graph printed, out of what the whole view holds.
44#[derive(Serialize, JsonSchema)]
45#[schemars(rename = "Count")]
46struct CountJson {
47    /// What the graph printed.
48    shown: usize,
49    /// What the view prints with `--all`, `--archived`, and no filter.
50    total: usize,
51}
52
53impl From<super::Count> for CountJson {
54    fn from(c: super::Count) -> Self {
55        CountJson {
56            shown: c.shown,
57            total: c.total,
58        }
59    }
60}
61
62/// One node. Its parent is the parent of its path.
63// sokf-implements: CLI-7_AC-62
64#[derive(Serialize, JsonSchema)]
65#[serde(tag = "kind", rename_all = "lowercase")]
66#[schemars(rename = "Node")]
67enum NodeJson {
68    /// A knowledge root.
69    Root {
70        /// The path of the root, starting with `/` at the repository root.
71        path: String,
72        /// The `name` of the manifest. It is absent when the manifest is absent or does
73        /// not parse.
74        #[serde(default, skip_serializing_if = "Option::is_none")]
75        #[schemars(with = "String")]
76        name: Option<String>,
77        /// The `scope` of the manifest: the owner of the store. The identity of the store is
78        /// `SCOPE/NAME`, where `SCOPE` is the scope and `NAME` is the name. Absent when the
79        /// manifest has none.
80        #[serde(default, skip_serializing_if = "Option::is_none")]
81        #[schemars(with = "String")]
82        scope: Option<String>,
83        /// The `description` of the manifest, when it has one.
84        #[serde(default, skip_serializing_if = "Option::is_none")]
85        #[schemars(with = "String")]
86        description: Option<String>,
87    },
88    /// A directory in a root, with a document, an additional file, or an asset somewhere
89    /// beneath it. A directory that a start points to is a directory node too.
90    Directory {
91        /// The directory.
92        path: String,
93    },
94    /// A document, including a schema.
95    Document {
96        /// The document.
97        path: String,
98        /// The frontmatter as read, without `links` and with its keys in the order written,
99        /// followed by `status`, and by `broken` and `reason` when the document is broken.
100        #[serde(flatten)]
101        #[schemars(schema_with = "document_fields")]
102        fields: Map<String, Value>,
103    },
104    /// An additional file.
105    Additional {
106        /// The file.
107        path: String,
108        /// The `id` of the schema that governs the file.
109        #[serde(default, skip_serializing_if = "Option::is_none")]
110        #[schemars(with = "String")]
111        schema: Option<String>,
112    },
113    /// An asset.
114    Asset {
115        /// The asset.
116        path: String,
117        /// The `id` of the sidecar of the asset.
118        #[serde(default, skip_serializing_if = "Option::is_none")]
119        #[schemars(with = "String")]
120        sidecar: Option<String>,
121    },
122    /// A repository file or directory as the target of an edge. A repository file that a
123    /// start points to is a file node too.
124    File {
125        /// The file or the directory.
126        path: String,
127    },
128    /// A key that a start identifies.
129    Key {
130        /// The document that defines the key, then `#` and the slug of the key.
131        path: String,
132        /// The key as it is written in its document.
133        key: String,
134        /// The line of the document where the key is defined.
135        line: usize,
136    },
137    /// A target that resolves to nothing.
138    Missing {
139        /// The text that named the target.
140        target: String,
141    },
142}
143
144/// One edge.
145#[derive(Serialize, JsonSchema)]
146#[schemars(rename = "Edge")]
147struct EdgeJson {
148    /// The kind of the edge.
149    kind: EdgeKindJson,
150    /// The path of the source node, or the `target` of a missing node.
151    from: String,
152    /// The path of the target node, or the `target` of a missing node.
153    to: String,
154    /// The relationship, from the source to the target.
155    rel: String,
156    /// The `note` of a `links` entry. An inverse edge, which the tool makes from a declared
157    /// one, never has a note.
158    #[serde(default, skip_serializing_if = "Option::is_none")]
159    #[schemars(with = "String")]
160    note: Option<String>,
161    /// The region of an include, when the marker names one, or the slug of the fragment that
162    /// a code marker cites. It is absent from a folded include or marker edge, the one edge
163    /// that replaces all the includes or markers of one file.
164    #[serde(default, skip_serializing_if = "Option::is_none")]
165    #[schemars(with = "String")]
166    region: Option<String>,
167    /// The line of a code marker in its file. It is absent from a folded marker edge.
168    #[serde(default, skip_serializing_if = "Option::is_none")]
169    #[schemars(with = "usize")]
170    line: Option<usize>,
171    /// The number of regions that a folded include replaces. Absent unless the include is
172    /// folded.
173    #[serde(default, skip_serializing_if = "Option::is_none")]
174    #[schemars(with = "usize")]
175    regions: Option<usize>,
176    /// The number of markers that a folded marker edge replaces. Absent unless the marker edge
177    /// is folded.
178    #[serde(default, skip_serializing_if = "Option::is_none")]
179    #[schemars(with = "usize")]
180    markers: Option<usize>,
181    /// True when the tool made the edge as the inverse of a declared one. It is absent otherwise.
182    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
183    #[schemars(extend("const" = true))]
184    synthesised: bool,
185}
186
187/// The kinds of edge.
188#[derive(Serialize, JsonSchema)]
189#[serde(rename_all = "lowercase")]
190#[schemars(rename = "EdgeKind")]
191enum EdgeKindJson {
192    /// An include marker.
193    Includes,
194    /// A key and its document, or a document that cites the key.
195    Keys,
196    /// A `links` entry, or a body link that no entry declares.
197    Links,
198    /// A code marker in a file outside the knowledge roots, and the document or the key that
199    /// it cites.
200    Marker,
201    /// A `resource` that is a `/` path.
202    Resource,
203    /// A `sources[].resource` that is a `/` path.
204    Sources,
205}
206
207// `document_fields` describes the keys that a document node always or often carries, and any
208// other frontmatter key can follow them. The tool prints the frontmatter as read. The graph
209// is permissive: it takes a document whatever values its frontmatter holds. So a key of the
210// frontmatter can hold any value. The schema constrains only the keys that the tool writes.
211fn document_fields(_: &mut SchemaGenerator) -> Schema {
212    json_schema!({
213        "type": "object",
214        "properties": {
215            "type": { "description": "The `type` of the frontmatter, as read." },
216            "id": { "description": "The `id` of the frontmatter, as read. It is absent when the document has none." },
217            "title": { "description": "The `title` of the frontmatter, as read." },
218            "status": { "description": "The `status` of the frontmatter, as read. It is `stable` when the frontmatter has none." },
219            "broken": { "description": "True when the frontmatter does not parse or has no `id`.", "const": true },
220            "reason": {
221                "description": "Why the document is broken.",
222                "enum": ["frontmatter does not parse", "no id"]
223            }
224        },
225        "required": ["status"]
226    })
227}
228
229fn text(fields: &Map<String, Value>, key: &str) -> Option<String> {
230    fields.get(key).and_then(Value::as_str).map(str::to_string)
231}
232
233impl From<&Node> for NodeJson {
234    fn from(node: &Node) -> Self {
235        let path = || node.key.as_str().to_string();
236        match node.kind {
237            NodeKind::Root => NodeJson::Root {
238                path: path(),
239                name: text(&node.fields, "name"),
240                scope: text(&node.fields, "scope"),
241                description: text(&node.fields, "description"),
242            },
243            NodeKind::Directory => NodeJson::Directory { path: path() },
244            NodeKind::Document => NodeJson::Document {
245                path: path(),
246                fields: node.fields.clone(),
247            },
248            NodeKind::Additional => NodeJson::Additional {
249                path: path(),
250                schema: text(&node.fields, "schema"),
251            },
252            NodeKind::Asset => NodeJson::Asset {
253                path: path(),
254                sidecar: text(&node.fields, "sidecar"),
255            },
256            NodeKind::File => NodeJson::File { path: path() },
257            NodeKind::Key => NodeJson::Key {
258                path: path(),
259                key: text(&node.fields, "key").unwrap_or_default(),
260                line: node
261                    .fields
262                    .get("line")
263                    .and_then(Value::as_u64)
264                    .and_then(|n| usize::try_from(n).ok())
265                    .unwrap_or_default(),
266            },
267            NodeKind::Missing => NodeJson::Missing {
268                target: node.key.as_str().to_string(),
269            },
270        }
271    }
272}
273
274impl From<&Edge> for EdgeJson {
275    fn from(edge: &Edge) -> Self {
276        EdgeJson {
277            kind: match edge.kind {
278                EdgeKind::Includes => EdgeKindJson::Includes,
279                EdgeKind::Keys => EdgeKindJson::Keys,
280                EdgeKind::Links => EdgeKindJson::Links,
281                EdgeKind::Marker => EdgeKindJson::Marker,
282                EdgeKind::Resource => EdgeKindJson::Resource,
283                EdgeKind::Sources => EdgeKindJson::Sources,
284            },
285            from: edge.from.as_str().to_string(),
286            to: edge.to.as_str().to_string(),
287            rel: edge.rel.clone(),
288            note: edge.note.clone(),
289            region: edge.region.clone(),
290            line: edge.line,
291            regions: None,
292            markers: None,
293            synthesised: edge.synthesised,
294        }
295    }
296}
297
298fn value(v: impl Serialize) -> Value {
299    serde_json::to_value(v).expect("a wire type could not be serialised to JSON")
300}
301
302/// `node_json` returns the node object: `kind`, then `path` or `target`, then the fields.
303// sokf-implements: CLI-7_AC-49
304pub fn node_json(node: &Node) -> Value {
305    value(NodeJson::from(node))
306}
307
308/// `edge_json` returns the edge object: `kind`, `from`, `to`, and `rel`, then `note`,
309/// `region`, `line`, `regions`, or `markers`, then `synthesised` when it is true.
310// sokf-implements: CLI-7_AC-50
311pub fn edge_json(edge: &Edge) -> Value {
312    value(EdgeJson::from(edge))
313}
314
315/// `bounded` returns the `{start, nodes, edges, summary}` object of a result, in which a
316/// folded include carries the number of its regions and no region, and a folded marker edge
317/// carries the number of its markers, and no region and no line.
318// sokf-implements: CLI-7_AC-12
319// sokf-implements: CLI-7_AC-13
320// sokf-implements: CLI-7_AC-80
321// sokf-implements: CLI-7_AC-96
322pub fn bounded(graph: &Graph, result: &GraphResult) -> Value {
323    value(GraphJson {
324        start: result
325            .start
326            .iter()
327            .map(|k| k.as_str().to_string())
328            .collect(),
329        nodes: result
330            .nodes
331            .iter()
332            .filter_map(|k| graph.node(k))
333            .map(NodeJson::from)
334            .collect(),
335        edges: result
336            .edges
337            .iter()
338            .map(|&i| {
339                let mut edge = EdgeJson::from(&graph.edges[i]);
340                if let Some(&n) = result.folded.get(&i) {
341                    edge.region = None;
342                    if graph.edges[i].kind == EdgeKind::Marker {
343                        edge.line = None;
344                        edge.markers = Some(n);
345                    } else {
346                        edge.regions = Some(n);
347                    }
348                }
349                edge
350            })
351            .collect(),
352        summary: SummaryJson {
353            documents: result.summary.documents.into(),
354            archived: result.summary.archived.into(),
355        },
356    })
357}
358
359#[cfg(test)]
360mod tests {
361    use std::collections::BTreeMap;
362
363    use serde_json::json;
364
365    use super::*;
366    use crate::{
367        RepoPath,
368        graph::{EdgeKind, NodeKey, NodeKind},
369    };
370
371    fn key(s: &str) -> NodeKey {
372        NodeKey::Path(RepoPath::parse(s).unwrap())
373    }
374
375    // sokf-tests: CLI-7_AC-49
376    // sokf-tests: CLI-7_AC-50
377    #[test]
378    fn node_and_edge_objects_have_the_key_order_and_omit_absent_keys() {
379        let mut fields = Map::new();
380        fields.insert("type".into(), json!("Subsystem"));
381        fields.insert("id".into(), json!("planner"));
382        fields.insert("status".into(), json!("stable"));
383        let doc = Node {
384            key: key("/knowledge/core/planner.md"),
385            kind: NodeKind::Document,
386            fields,
387        };
388        assert_eq!(
389            serde_json::to_string(&node_json(&doc)).unwrap(),
390            r#"{"kind":"document","path":"/knowledge/core/planner.md","type":"Subsystem","id":"planner","status":"stable"}"#
391        );
392        let missing = Node {
393            key: NodeKey::Missing("planer".into()),
394            kind: NodeKind::Missing,
395            fields: Map::new(),
396        };
397        assert_eq!(
398            serde_json::to_string(&node_json(&missing)).unwrap(),
399            r#"{"kind":"missing","target":"planer"}"#
400        );
401        let declared = Edge {
402            from: key("/a.md"),
403            kind: EdgeKind::Links,
404            to: key("/b.md"),
405            rel: "depends-on".into(),
406            region: None,
407            line: None,
408            synthesised: false,
409            note: Some("n".into()),
410        };
411        assert_eq!(
412            serde_json::to_string(&edge_json(&declared)).unwrap(),
413            r#"{"kind":"links","from":"/a.md","to":"/b.md","rel":"depends-on","note":"n"}"#
414        );
415        let synthesised = Edge {
416            from: key("/src/main.rs"),
417            kind: EdgeKind::Includes,
418            to: key("/a.md"),
419            rel: "included-by".into(),
420            region: Some("cli".into()),
421            line: None,
422            synthesised: true,
423            note: None,
424        };
425        assert_eq!(
426            serde_json::to_string(&edge_json(&synthesised)).unwrap(),
427            r#"{"kind":"includes","from":"/src/main.rs","to":"/a.md","rel":"included-by","region":"cli","synthesised":true}"#
428        );
429    }
430
431    // sokf-tests: CLI-7_AC-78
432    // sokf-tests: CLI-7_AC-80
433    #[test]
434    fn bounded_has_start_nodes_edges_and_summary() {
435        let mut nodes = std::collections::BTreeMap::new();
436        for k in ["/a.md", "/b.md"] {
437            nodes.insert(
438                key(k),
439                Node {
440                    key: key(k),
441                    kind: NodeKind::Document,
442                    fields: Map::new(),
443                },
444            );
445        }
446        let graph = Graph::new(
447            nodes,
448            vec![Edge {
449                from: key("/a.md"),
450                kind: EdgeKind::Links,
451                to: key("/b.md"),
452                rel: "relates-to".into(),
453                region: None,
454                line: None,
455                synthesised: false,
456                note: None,
457            }],
458        );
459        let result = GraphResult {
460            start: vec![key("/a.md")],
461            rows: vec![],
462            nodes: vec![key("/a.md"), key("/b.md"), key("/gone.md")],
463            edges: vec![0],
464            folded: BTreeMap::default(),
465            summary: crate::graph::Summary {
466                documents: crate::graph::Count { shown: 2, total: 5 },
467                archived: crate::graph::Count { shown: 0, total: 3 },
468            },
469            projection: None,
470            notes: Vec::new(),
471        };
472        assert_eq!(
473            bounded(&graph, &result),
474            json!({
475                "start": ["/a.md"],
476                "nodes": [{"kind": "document", "path": "/a.md"}, {"kind": "document", "path": "/b.md"}],
477                "edges": [{"kind": "links", "from": "/a.md", "to": "/b.md", "rel": "relates-to"}],
478                "summary": {
479                    "documents": {"shown": 2, "total": 5},
480                    "archived": {"shown": 0, "total": 3}
481                }
482            })
483        );
484        // A folded include carries the count of its regions and no region.
485        let folded = GraphResult {
486            folded: [(0, 3)].into_iter().collect(),
487            ..result
488        };
489        assert_eq!(
490            bounded(&graph, &folded)["edges"][0],
491            json!({"kind": "links", "from": "/a.md", "to": "/b.md", "rel": "relates-to", "regions": 3})
492        );
493    }
494}