Skip to main content

docsrs_cli/render/
schema_md.rs

1//! Human Markdown rendering for the embedded JSON Schemas (`schema --format markdown`).
2
3use crate::error::{AppError, AppResult, ErrorDetail, InternalOp};
4
5/// Render a human-readable markdown document for an embedded JSON Schema.
6///
7/// Includes title, description, required fields, a property table, and the
8/// raw JSON Schema fenced for agents that still want the machine schema.
9///
10/// # Errors
11///
12/// Returns [`crate::error::ErrorKind::Internal`] when pretty-printing the embedded schema fails
13/// (should not happen for valid `serde_json::Value` trees).
14pub fn render_schema_markdown(cmd: &str, schema: &serde_json::Value) -> AppResult<String> {
15    // Schema markdown is small but non-trivial; avoid repeated small reallocs.
16    let mut out = String::with_capacity(1024);
17    let title = schema.get("title").and_then(|v| v.as_str()).unwrap_or(cmd);
18    out.push_str(&format!("# Schema: `{cmd}`\n\n"));
19    out.push_str(&format!("**Title:** {title}\n\n"));
20    if let Some(desc) = schema.get("description").and_then(|v| v.as_str()) {
21        out.push_str(&format!("{desc}\n\n"));
22    }
23    if let Some(req) = schema.get("required").and_then(|v| v.as_array()) {
24        out.push_str("## Required fields\n\n");
25        for r in req {
26            if let Some(name) = r.as_str() {
27                out.push_str(&format!("- `{name}`\n"));
28            }
29        }
30        out.push('\n');
31    }
32    out.push_str("## Properties\n\n");
33    out.push_str("| property | type | required | description |\n");
34    out.push_str("| --- | --- | --- | --- |\n");
35    let required: std::collections::HashSet<&str> = schema
36        .get("required")
37        .and_then(|v| v.as_array())
38        .map(|a| a.iter().filter_map(|x| x.as_str()).collect())
39        .unwrap_or_default();
40    if let Some(props) = schema.get("properties").and_then(|v| v.as_object()) {
41        for (name, prop) in props {
42            let ty = schema_type_label(prop);
43            let is_req = if required.contains(name.as_str()) {
44                "yes"
45            } else {
46                "no"
47            };
48            let desc = prop
49                .get("description")
50                .and_then(|v| v.as_str())
51                .unwrap_or("")
52                .replace('|', "\\|");
53            out.push_str(&format!("| `{name}` | {ty} | {is_req} | {desc} |\n"));
54        }
55    } else {
56        out.push_str("| _(none)_ | | | |\n");
57    }
58    out.push_str("\n## JSON Schema\n\n");
59    out.push_str("```json\n");
60    let pretty = serde_json::to_string_pretty(schema).map_err(|e| {
61        AppError::of_with_source(
62            ErrorDetail::Internal {
63                op: InternalOp::JsonPrettyPrint,
64            },
65            e,
66        )
67    })?;
68    out.push_str(&pretty);
69    out.push_str("\n```\n");
70    Ok(out)
71}
72
73fn schema_type_label(prop: &serde_json::Value) -> String {
74    if let Some(t) = prop.get("type") {
75        if let Some(s) = t.as_str() {
76            return s.to_string();
77        }
78        if let Some(arr) = t.as_array() {
79            let parts: Vec<&str> = arr.iter().filter_map(|v| v.as_str()).collect();
80            if !parts.is_empty() {
81                return parts.join(" | ");
82            }
83        }
84    }
85    if prop.get("properties").is_some() {
86        return "object".into();
87    }
88    if prop.get("items").is_some() {
89        return "array".into();
90    }
91    "any".into()
92}
93
94#[cfg(test)]
95mod tests {
96    use super::*;
97
98    #[test]
99    fn type_label_covers_scalar_union_and_containers() {
100        assert_eq!(
101            schema_type_label(&serde_json::json!({"type": "string"})),
102            "string"
103        );
104        assert_eq!(
105            schema_type_label(&serde_json::json!({"type": ["string", "null"]})),
106            "string | null"
107        );
108        assert_eq!(
109            schema_type_label(&serde_json::json!({"properties": {}})),
110            "object"
111        );
112        assert_eq!(
113            schema_type_label(&serde_json::json!({"items": {}})),
114            "array"
115        );
116        assert_eq!(schema_type_label(&serde_json::json!({})), "any");
117    }
118
119    #[test]
120    fn markdown_lists_required_and_properties() {
121        let schema = serde_json::json!({
122            "title": "demo",
123            "description": "a demo schema",
124            "required": ["a"],
125            "properties": {
126                "a": {"type": "string", "description": "pipe | escaped"},
127                "b": {"type": "integer"}
128            }
129        });
130        let md = render_schema_markdown("demo", &schema).expect("render");
131        assert!(md.contains("# Schema: `demo`"));
132        assert!(md.contains("**Title:** demo"));
133        assert!(md.contains("| `a` | string | yes |"));
134        assert!(md.contains("| `b` | integer | no |"));
135        assert!(md.contains("pipe \\| escaped"), "table pipes are escaped");
136        assert!(md.contains("```json"));
137    }
138
139    #[test]
140    fn markdown_without_properties_emits_placeholder_row() {
141        let md = render_schema_markdown("empty", &serde_json::json!({})).expect("render");
142        assert!(md.contains("_(none)_"));
143    }
144}