use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema};
use serde::Serialize;
use serde_json::{Map, Value};
use super::{Edge, EdgeKind, Graph, GraphResult, Node, NodeKind};
#[derive(Serialize, JsonSchema)]
#[schemars(title = "sokf graph")]
pub struct GraphJson {
start: Vec<String>,
nodes: Vec<NodeJson>,
edges: Vec<EdgeJson>,
summary: SummaryJson,
}
#[derive(Serialize, JsonSchema)]
#[schemars(rename = "Summary")]
struct SummaryJson {
documents: CountJson,
archived: CountJson,
}
#[derive(Serialize, JsonSchema)]
#[schemars(rename = "Count")]
struct CountJson {
shown: usize,
total: usize,
}
impl From<super::Count> for CountJson {
fn from(c: super::Count) -> Self {
CountJson {
shown: c.shown,
total: c.total,
}
}
}
#[derive(Serialize, JsonSchema)]
#[serde(tag = "kind", rename_all = "lowercase")]
#[schemars(rename = "Node")]
enum NodeJson {
Root {
path: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[schemars(with = "String")]
name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[schemars(with = "String")]
scope: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[schemars(with = "String")]
description: Option<String>,
},
Directory {
path: String,
},
Document {
path: String,
#[serde(flatten)]
#[schemars(schema_with = "document_fields")]
fields: Map<String, Value>,
},
Additional {
path: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[schemars(with = "String")]
schema: Option<String>,
},
Asset {
path: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[schemars(with = "String")]
sidecar: Option<String>,
},
File {
path: String,
},
Key {
path: String,
key: String,
line: usize,
},
Missing {
target: String,
},
}
#[derive(Serialize, JsonSchema)]
#[schemars(rename = "Edge")]
struct EdgeJson {
kind: EdgeKindJson,
from: String,
to: String,
rel: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[schemars(with = "String")]
note: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[schemars(with = "String")]
region: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[schemars(with = "usize")]
line: Option<usize>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[schemars(with = "usize")]
regions: Option<usize>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[schemars(with = "usize")]
markers: Option<usize>,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
#[schemars(extend("const" = true))]
synthesised: bool,
}
#[derive(Serialize, JsonSchema)]
#[serde(rename_all = "lowercase")]
#[schemars(rename = "EdgeKind")]
enum EdgeKindJson {
Includes,
Keys,
Links,
Marker,
Resource,
Sources,
}
fn document_fields(_: &mut SchemaGenerator) -> Schema {
json_schema!({
"type": "object",
"properties": {
"type": { "description": "The `type` of the frontmatter, as read." },
"id": { "description": "The `id` of the frontmatter, as read. It is absent when the document has none." },
"title": { "description": "The `title` of the frontmatter, as read." },
"status": { "description": "The `status` of the frontmatter, as read. It is `stable` when the frontmatter has none." },
"broken": { "description": "True when the frontmatter does not parse or has no `id`.", "const": true },
"reason": {
"description": "Why the document is broken.",
"enum": ["frontmatter does not parse", "no id"]
}
},
"required": ["status"]
})
}
fn text(fields: &Map<String, Value>, key: &str) -> Option<String> {
fields.get(key).and_then(Value::as_str).map(str::to_string)
}
impl From<&Node> for NodeJson {
fn from(node: &Node) -> Self {
let path = || node.key.as_str().to_string();
match node.kind {
NodeKind::Root => NodeJson::Root {
path: path(),
name: text(&node.fields, "name"),
scope: text(&node.fields, "scope"),
description: text(&node.fields, "description"),
},
NodeKind::Directory => NodeJson::Directory { path: path() },
NodeKind::Document => NodeJson::Document {
path: path(),
fields: node.fields.clone(),
},
NodeKind::Additional => NodeJson::Additional {
path: path(),
schema: text(&node.fields, "schema"),
},
NodeKind::Asset => NodeJson::Asset {
path: path(),
sidecar: text(&node.fields, "sidecar"),
},
NodeKind::File => NodeJson::File { path: path() },
NodeKind::Key => NodeJson::Key {
path: path(),
key: text(&node.fields, "key").unwrap_or_default(),
line: node
.fields
.get("line")
.and_then(Value::as_u64)
.and_then(|n| usize::try_from(n).ok())
.unwrap_or_default(),
},
NodeKind::Missing => NodeJson::Missing {
target: node.key.as_str().to_string(),
},
}
}
}
impl From<&Edge> for EdgeJson {
fn from(edge: &Edge) -> Self {
EdgeJson {
kind: match edge.kind {
EdgeKind::Includes => EdgeKindJson::Includes,
EdgeKind::Keys => EdgeKindJson::Keys,
EdgeKind::Links => EdgeKindJson::Links,
EdgeKind::Marker => EdgeKindJson::Marker,
EdgeKind::Resource => EdgeKindJson::Resource,
EdgeKind::Sources => EdgeKindJson::Sources,
},
from: edge.from.as_str().to_string(),
to: edge.to.as_str().to_string(),
rel: edge.rel.clone(),
note: edge.note.clone(),
region: edge.region.clone(),
line: edge.line,
regions: None,
markers: None,
synthesised: edge.synthesised,
}
}
}
fn value(v: impl Serialize) -> Value {
serde_json::to_value(v).expect("a wire type could not be serialised to JSON")
}
pub fn node_json(node: &Node) -> Value {
value(NodeJson::from(node))
}
pub fn edge_json(edge: &Edge) -> Value {
value(EdgeJson::from(edge))
}
pub fn bounded(graph: &Graph, result: &GraphResult) -> Value {
value(GraphJson {
start: result
.start
.iter()
.map(|k| k.as_str().to_string())
.collect(),
nodes: result
.nodes
.iter()
.filter_map(|k| graph.node(k))
.map(NodeJson::from)
.collect(),
edges: result
.edges
.iter()
.map(|&i| {
let mut edge = EdgeJson::from(&graph.edges[i]);
if let Some(&n) = result.folded.get(&i) {
edge.region = None;
if graph.edges[i].kind == EdgeKind::Marker {
edge.line = None;
edge.markers = Some(n);
} else {
edge.regions = Some(n);
}
}
edge
})
.collect(),
summary: SummaryJson {
documents: result.summary.documents.into(),
archived: result.summary.archived.into(),
},
})
}
#[cfg(test)]
mod tests {
use std::collections::BTreeMap;
use serde_json::json;
use super::*;
use crate::{
RepoPath,
graph::{EdgeKind, NodeKey, NodeKind},
};
fn key(s: &str) -> NodeKey {
NodeKey::Path(RepoPath::parse(s).unwrap())
}
#[test]
fn node_and_edge_objects_have_the_key_order_and_omit_absent_keys() {
let mut fields = Map::new();
fields.insert("type".into(), json!("Subsystem"));
fields.insert("id".into(), json!("planner"));
fields.insert("status".into(), json!("stable"));
let doc = Node {
key: key("/knowledge/core/planner.md"),
kind: NodeKind::Document,
fields,
};
assert_eq!(
serde_json::to_string(&node_json(&doc)).unwrap(),
r#"{"kind":"document","path":"/knowledge/core/planner.md","type":"Subsystem","id":"planner","status":"stable"}"#
);
let missing = Node {
key: NodeKey::Missing("planer".into()),
kind: NodeKind::Missing,
fields: Map::new(),
};
assert_eq!(
serde_json::to_string(&node_json(&missing)).unwrap(),
r#"{"kind":"missing","target":"planer"}"#
);
let declared = Edge {
from: key("/a.md"),
kind: EdgeKind::Links,
to: key("/b.md"),
rel: "depends-on".into(),
region: None,
line: None,
synthesised: false,
note: Some("n".into()),
};
assert_eq!(
serde_json::to_string(&edge_json(&declared)).unwrap(),
r#"{"kind":"links","from":"/a.md","to":"/b.md","rel":"depends-on","note":"n"}"#
);
let synthesised = Edge {
from: key("/src/main.rs"),
kind: EdgeKind::Includes,
to: key("/a.md"),
rel: "included-by".into(),
region: Some("cli".into()),
line: None,
synthesised: true,
note: None,
};
assert_eq!(
serde_json::to_string(&edge_json(&synthesised)).unwrap(),
r#"{"kind":"includes","from":"/src/main.rs","to":"/a.md","rel":"included-by","region":"cli","synthesised":true}"#
);
}
#[test]
fn bounded_has_start_nodes_edges_and_summary() {
let mut nodes = std::collections::BTreeMap::new();
for k in ["/a.md", "/b.md"] {
nodes.insert(
key(k),
Node {
key: key(k),
kind: NodeKind::Document,
fields: Map::new(),
},
);
}
let graph = Graph::new(
nodes,
vec![Edge {
from: key("/a.md"),
kind: EdgeKind::Links,
to: key("/b.md"),
rel: "relates-to".into(),
region: None,
line: None,
synthesised: false,
note: None,
}],
);
let result = GraphResult {
start: vec![key("/a.md")],
rows: vec![],
nodes: vec![key("/a.md"), key("/b.md"), key("/gone.md")],
edges: vec![0],
folded: BTreeMap::default(),
summary: crate::graph::Summary {
documents: crate::graph::Count { shown: 2, total: 5 },
archived: crate::graph::Count { shown: 0, total: 3 },
},
projection: None,
notes: Vec::new(),
};
assert_eq!(
bounded(&graph, &result),
json!({
"start": ["/a.md"],
"nodes": [{"kind": "document", "path": "/a.md"}, {"kind": "document", "path": "/b.md"}],
"edges": [{"kind": "links", "from": "/a.md", "to": "/b.md", "rel": "relates-to"}],
"summary": {
"documents": {"shown": 2, "total": 5},
"archived": {"shown": 0, "total": 3}
}
})
);
let folded = GraphResult {
folded: [(0, 3)].into_iter().collect(),
..result
};
assert_eq!(
bounded(&graph, &folded)["edges"][0],
json!({"kind": "links", "from": "/a.md", "to": "/b.md", "rel": "relates-to", "regions": 3})
);
}
}