1use 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#[derive(Serialize, JsonSchema)]
15#[schemars(title = "sokf graph")]
16pub struct GraphJson {
17 start: Vec<String>,
21 nodes: Vec<NodeJson>,
23 edges: Vec<EdgeJson>,
26 summary: SummaryJson,
29}
30
31#[derive(Serialize, JsonSchema)]
35#[schemars(rename = "Summary")]
36struct SummaryJson {
37 documents: CountJson,
39 archived: CountJson,
41}
42
43#[derive(Serialize, JsonSchema)]
45#[schemars(rename = "Count")]
46struct CountJson {
47 shown: usize,
49 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#[derive(Serialize, JsonSchema)]
65#[serde(tag = "kind", rename_all = "lowercase")]
66#[schemars(rename = "Node")]
67enum NodeJson {
68 Root {
70 path: String,
72 #[serde(default, skip_serializing_if = "Option::is_none")]
75 #[schemars(with = "String")]
76 name: Option<String>,
77 #[serde(default, skip_serializing_if = "Option::is_none")]
81 #[schemars(with = "String")]
82 scope: Option<String>,
83 #[serde(default, skip_serializing_if = "Option::is_none")]
85 #[schemars(with = "String")]
86 description: Option<String>,
87 },
88 Directory {
91 path: String,
93 },
94 Document {
96 path: String,
98 #[serde(flatten)]
101 #[schemars(schema_with = "document_fields")]
102 fields: Map<String, Value>,
103 },
104 Additional {
106 path: String,
108 #[serde(default, skip_serializing_if = "Option::is_none")]
110 #[schemars(with = "String")]
111 schema: Option<String>,
112 },
113 Asset {
115 path: String,
117 #[serde(default, skip_serializing_if = "Option::is_none")]
119 #[schemars(with = "String")]
120 sidecar: Option<String>,
121 },
122 File {
125 path: String,
127 },
128 Key {
130 path: String,
132 key: String,
134 line: usize,
136 },
137 Missing {
139 target: String,
141 },
142}
143
144#[derive(Serialize, JsonSchema)]
146#[schemars(rename = "Edge")]
147struct EdgeJson {
148 kind: EdgeKindJson,
150 from: String,
152 to: String,
154 rel: String,
156 #[serde(default, skip_serializing_if = "Option::is_none")]
159 #[schemars(with = "String")]
160 note: Option<String>,
161 #[serde(default, skip_serializing_if = "Option::is_none")]
165 #[schemars(with = "String")]
166 region: Option<String>,
167 #[serde(default, skip_serializing_if = "Option::is_none")]
169 #[schemars(with = "usize")]
170 line: Option<usize>,
171 #[serde(default, skip_serializing_if = "Option::is_none")]
174 #[schemars(with = "usize")]
175 regions: Option<usize>,
176 #[serde(default, skip_serializing_if = "Option::is_none")]
179 #[schemars(with = "usize")]
180 markers: Option<usize>,
181 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
183 #[schemars(extend("const" = true))]
184 synthesised: bool,
185}
186
187#[derive(Serialize, JsonSchema)]
189#[serde(rename_all = "lowercase")]
190#[schemars(rename = "EdgeKind")]
191enum EdgeKindJson {
192 Includes,
194 Keys,
196 Links,
198 Marker,
201 Resource,
203 Sources,
205}
206
207fn 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
302pub fn node_json(node: &Node) -> Value {
305 value(NodeJson::from(node))
306}
307
308pub fn edge_json(edge: &Edge) -> Value {
312 value(EdgeJson::from(edge))
313}
314
315pub 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 #[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 #[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 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}