Skip to main content

docsrs_cli/
render.rs

1//! Markdown and JSON rendering with output truncation.
2
3use serde::Serialize;
4
5use crate::config::{Config, SCHEMA_VERSION};
6use crate::crates_io::SearchCratesData;
7use crate::docs_rs::{GetItemData, ReadmeData, SearchInCrateData};
8use crate::error::{AppError, ErrorKind};
9
10/// JSON success envelope for agents (`schema_version`, `ok`, `command`, `data`, `duration_ms`).
11///
12/// Typed wire shape — serializes directly without an intermediate `serde_json::Value`.
13/// Optional fields use omit-on-`None` (`skip_serializing_if`), not JSON `null`.
14#[derive(Debug, Serialize)]
15pub struct SuccessEnvelope<'a, T: Serialize> {
16    /// Envelope schema version.
17    pub schema_version: u32,
18    /// Always `true` for success envelopes.
19    pub ok: bool,
20    /// Command name that produced this payload.
21    pub command: &'a str,
22    /// Command-specific typed data payload.
23    pub data: T,
24    /// Wall-clock duration of the command in milliseconds.
25    pub duration_ms: u64,
26    /// Final source URL when the command fetched remote content.
27    #[serde(skip_serializing_if = "Option::is_none")]
28    pub source_url: Option<&'a str>,
29}
30
31/// JSON dry-run success envelope with planned URL and params.
32///
33/// `P` is a typed per-command params struct (`Serialize`). No intermediate
34/// `serde_json::Value` on the agent write path.
35#[derive(Debug, Serialize)]
36pub struct DryRunEnvelope<'a, P: Serialize> {
37    /// Envelope schema version.
38    pub schema_version: u32,
39    /// Always `true` for dry-run envelopes.
40    pub ok: bool,
41    /// Command name that would have run.
42    pub command: &'a str,
43    /// Always `true` — marks the response as a dry-run plan.
44    pub dry_run: bool,
45    /// Planned request details.
46    pub data: DryRunData<'a, P>,
47    /// Wall-clock duration until the plan was emitted.
48    pub duration_ms: u64,
49}
50
51/// Dry-run `data` object (`planned_url` + typed `planned_params`).
52#[derive(Debug, Serialize)]
53pub struct DryRunData<'a, P: Serialize> {
54    /// Absolute URL that would be requested.
55    pub planned_url: &'a str,
56    /// Command-specific planned query/body parameters (typed struct).
57    pub planned_params: P,
58}
59
60/// JSON error envelope for agents.
61#[derive(Debug, Serialize)]
62pub struct ErrorEnvelope {
63    /// Envelope schema version.
64    pub schema_version: u32,
65    /// Always `false` for error envelopes.
66    pub ok: bool,
67    /// Structured error body.
68    pub error: ErrorBody,
69}
70
71/// Error body fields inside the envelope.
72#[derive(Debug, Serialize)]
73pub struct ErrorBody {
74    /// Process exit code as an integer.
75    pub code: u8,
76    /// Snake_case error kind.
77    pub kind: String,
78    /// Technical English message.
79    pub message: String,
80    /// Whether an agent may retry after backoff.
81    pub retryable: bool,
82    /// Optional Retry-After seconds.
83    #[serde(skip_serializing_if = "Option::is_none")]
84    pub retry_after_secs: Option<u64>,
85}
86
87/// Render a human-readable markdown document for an embedded JSON Schema.
88///
89/// Includes title, description, required fields, a property table, and the
90/// raw JSON Schema fenced for agents that still want the machine schema.
91pub fn render_schema_markdown(cmd: &str, schema: &serde_json::Value) -> String {
92    // Schema markdown is small but non-trivial; avoid repeated small reallocs.
93    let mut out = String::with_capacity(1024);
94    let title = schema.get("title").and_then(|v| v.as_str()).unwrap_or(cmd);
95    out.push_str(&format!("# Schema: `{cmd}`\n\n"));
96    out.push_str(&format!("**Title:** {title}\n\n"));
97    if let Some(desc) = schema.get("description").and_then(|v| v.as_str()) {
98        out.push_str(&format!("{desc}\n\n"));
99    }
100    if let Some(req) = schema.get("required").and_then(|v| v.as_array()) {
101        out.push_str("## Required fields\n\n");
102        for r in req {
103            if let Some(name) = r.as_str() {
104                out.push_str(&format!("- `{name}`\n"));
105            }
106        }
107        out.push('\n');
108    }
109    out.push_str("## Properties\n\n");
110    out.push_str("| property | type | required | description |\n");
111    out.push_str("| --- | --- | --- | --- |\n");
112    let required: std::collections::HashSet<&str> = schema
113        .get("required")
114        .and_then(|v| v.as_array())
115        .map(|a| a.iter().filter_map(|x| x.as_str()).collect())
116        .unwrap_or_default();
117    if let Some(props) = schema.get("properties").and_then(|v| v.as_object()) {
118        for (name, prop) in props {
119            let ty = schema_type_label(prop);
120            let is_req = if required.contains(name.as_str()) {
121                "yes"
122            } else {
123                "no"
124            };
125            let desc = prop
126                .get("description")
127                .and_then(|v| v.as_str())
128                .unwrap_or("")
129                .replace('|', "\\|");
130            out.push_str(&format!("| `{name}` | {ty} | {is_req} | {desc} |\n"));
131        }
132    } else {
133        out.push_str("| _(none)_ | | | |\n");
134    }
135    out.push_str("\n## JSON Schema\n\n");
136    out.push_str("```json\n");
137    out.push_str(&serde_json::to_string_pretty(schema).unwrap_or_else(|_| "{}".to_string()));
138    out.push_str("\n```\n");
139    out
140}
141
142fn schema_type_label(prop: &serde_json::Value) -> String {
143    if let Some(t) = prop.get("type") {
144        if let Some(s) = t.as_str() {
145            return s.to_string();
146        }
147        if let Some(arr) = t.as_array() {
148            let parts: Vec<&str> = arr.iter().filter_map(|v| v.as_str()).collect();
149            if !parts.is_empty() {
150                return parts.join(" | ");
151            }
152        }
153    }
154    if prop.get("properties").is_some() {
155        return "object".into();
156    }
157    if prop.get("items").is_some() {
158        return "array".into();
159    }
160    "any".into()
161}
162
163/// Build a typed success envelope (`schema_version`, `ok`, `command`, `data`, `duration_ms`).
164pub fn success_envelope<'a, T: Serialize>(
165    command: &'a str,
166    data: T,
167    duration_ms: u64,
168    source_url: Option<&'a str>,
169) -> SuccessEnvelope<'a, T> {
170    SuccessEnvelope {
171        schema_version: SCHEMA_VERSION,
172        ok: true,
173        command,
174        data,
175        duration_ms,
176        source_url,
177    }
178}
179
180/// Build a typed dry-run success envelope with planned URL/params.
181pub fn dry_run_envelope<'a, P: Serialize>(
182    command: &'a str,
183    planned_url: &'a str,
184    planned_params: P,
185    duration_ms: u64,
186) -> DryRunEnvelope<'a, P> {
187    DryRunEnvelope {
188        schema_version: SCHEMA_VERSION,
189        ok: true,
190        command,
191        dry_run: true,
192        data: DryRunData {
193            planned_url,
194            planned_params,
195        },
196        duration_ms,
197    }
198}
199
200/// Build an error envelope. SIGINT/SIGTERM surface as kind `canceled` with exit 130/143.
201pub fn error_envelope(err: &AppError) -> ErrorEnvelope {
202    let kind = err.kind();
203    let kind_str = match kind {
204        ErrorKind::Interrupted | ErrorKind::Terminated => "canceled",
205        ErrorKind::BrokenPipe => "broken_pipe",
206        other => other.as_str(),
207    };
208    ErrorEnvelope {
209        schema_version: SCHEMA_VERSION,
210        ok: false,
211        error: ErrorBody {
212            code: kind.exit_code(),
213            kind: kind_str.to_string(),
214            message: err.message().to_string(),
215            retryable: kind.retryable(),
216            retry_after_secs: err.retry_after_secs(),
217        },
218    }
219}
220
221/// Truncate UTF-8 text on a char boundary; returns (text, truncated).
222pub fn truncate_output(text: &str, max_bytes: u64) -> (String, bool) {
223    if max_bytes == 0 {
224        return (String::new(), true);
225    }
226    let max = max_bytes as usize;
227    if text.len() <= max {
228        return (text.to_string(), false);
229    }
230    let mut end = max;
231    while end > 0 && !text.is_char_boundary(end) {
232        end -= 1;
233    }
234    (text[..end].to_string(), true)
235}
236
237/// Human Markdown for search-crates.
238pub fn render_search_markdown(data: &SearchCratesData) -> String {
239    let mut out = format!(
240        "# Crate Search Results for \"{}\" (page {})\n\n",
241        data.query, data.page
242    );
243    if data.hits.is_empty() {
244        out.push_str("No crates found.\n");
245        return out;
246    }
247    for h in &data.hits {
248        out.push_str(&format!("## {} ({})\n\n", h.name, h.version));
249        out.push_str(&format!("**Description:** {}\n\n", h.description));
250        out.push_str(&format!("**Downloads:** {}\n\n", h.downloads));
251        out.push_str(&format!(
252            "**Documentation:** {}\n\n---\n\n",
253            h.documentation.as_deref().unwrap_or("N/A")
254        ));
255    }
256    out
257}
258
259/// Human Markdown for readme.
260pub fn render_readme_markdown(data: &ReadmeData) -> String {
261    let mut out = format!("# {} Documentation\n\n", data.crate_name);
262    if data.empty {
263        out.push_str("No documentation content found.\n");
264    } else {
265        out.push_str(&data.markdown);
266        out.push('\n');
267    }
268    out
269}
270
271/// Human Markdown for get-item.
272pub fn render_item_markdown(data: &GetItemData) -> String {
273    let mut out = format!("# {}\n\n", data.title);
274    out.push_str(&format!("**Documentation URL:** {}\n\n", data.source_url));
275    if data.empty {
276        out.push_str("No documentation content found.\n");
277    } else {
278        out.push_str(&data.markdown);
279        out.push('\n');
280    }
281    out
282}
283
284/// Human Markdown for search-in-crate.
285pub fn render_search_in_crate_markdown(data: &SearchInCrateData) -> String {
286    // Borrow query text — no String clone for the heading.
287    let term = if data.query.is_empty() {
288        "all items"
289    } else {
290        data.query.as_str()
291    };
292    let mut out = format!(
293        "# Search Results for \"{}\" in {}\n\nFound {} items (emitted {})\n\n",
294        term, data.crate_name, data.total, data.emitted
295    );
296    if data.hits.is_empty() {
297        out.push_str("No matching items found.\n");
298        return out;
299    }
300    for h in &data.hits {
301        out.push_str(&format!("## {} ({})\n\n", h.name, h.kind));
302        out.push_str(&format!("**Link:** {}\n\n---\n\n", h.url));
303    }
304    out
305}
306
307/// Apply max_output_bytes truncation to readme payload.
308pub fn apply_truncation_to_readme(mut data: ReadmeData, cfg: &Config) -> ReadmeData {
309    let (md, trunc) = truncate_output(&data.markdown, cfg.max_output_bytes);
310    data.markdown = md;
311    data.truncated = trunc;
312    data
313}
314
315/// Apply max_output_bytes truncation to get-item payload.
316pub fn apply_truncation_to_item(mut data: GetItemData, cfg: &Config) -> GetItemData {
317    let (md, trunc) = truncate_output(&data.markdown, cfg.max_output_bytes);
318    data.markdown = md;
319    data.truncated = trunc;
320    data
321}
322
323/// Map clap parse failures to usage errors.
324pub fn usage_error(msg: impl Into<String>) -> AppError {
325    AppError::new(ErrorKind::Usage, msg)
326}
327
328#[cfg(test)]
329mod tests {
330    use super::*;
331    use crate::crates_io::{CrateSearchHit, SearchCratesData, SearchMeta};
332    use crate::docs_rs::{GetItemData, ReadmeData};
333    use crate::error::AppError;
334
335    #[test]
336    fn truncate_marks_flag() {
337        let (out, trunc) = truncate_output("abcdef", 3);
338        assert!(trunc);
339        assert_eq!(out, "abc");
340    }
341
342    #[test]
343    fn cancel_kinds_in_envelope() {
344        let e = error_envelope(&AppError::terminated());
345        assert_eq!(e.error.code, 143);
346        assert_eq!(e.error.kind, "canceled");
347        let e = error_envelope(&AppError::interrupted());
348        assert_eq!(e.error.code, 130);
349        assert_eq!(e.error.kind, "canceled");
350    }
351
352    #[test]
353    fn empty_search_markdown() {
354        let data = SearchCratesData {
355            query: "z".into(),
356            page: 1,
357            per_page: 10,
358            sort: "relevance".into(),
359            hits: vec![],
360            meta: SearchMeta {
361                total: 0,
362                next_page: None,
363                prev_page: None,
364            },
365            cache_hit: false,
366        };
367        let md = render_search_markdown(&data);
368        assert!(md.contains("No crates found"));
369    }
370
371    #[test]
372    fn empty_readme_and_item() {
373        let r = ReadmeData {
374            crate_name: "c".into(),
375            version: "latest".into(),
376            resolved_version: None,
377            markdown: String::new(),
378            empty: true,
379            truncated: false,
380            source_url: "u".into(),
381            cache_hit: false,
382        };
383        assert!(render_readme_markdown(&r).contains("No documentation"));
384        let i = GetItemData {
385            crate_name: "c".into(),
386            item_type: "fn".into(),
387            item_path: "c::f".into(),
388            item_name: "f".into(),
389            version: "latest".into(),
390            resolved_version: None,
391            markdown: String::new(),
392            empty: true,
393            truncated: false,
394            source_url: "u".into(),
395            title: "c::f (fn)".into(),
396            cache_hit: false,
397        };
398        assert!(render_item_markdown(&i).contains("No documentation"));
399    }
400
401    #[test]
402    fn success_and_dry_run_envelopes() {
403        let payload = serde_json::json!({"n": 1});
404        let v = success_envelope("version", &payload, 3, Some("https://x"));
405        let v = serde_json::to_value(&v).expect("serialize success envelope");
406        assert_eq!(v["ok"], true);
407        assert_eq!(v["source_url"], "https://x");
408        assert_eq!(v["schema_version"], SCHEMA_VERSION);
409        // Optional source_url omitted when None (not JSON null).
410        let no_url = success_envelope("version", &payload, 1, None);
411        let no_url = serde_json::to_value(&no_url).expect("serialize");
412        assert!(no_url.get("source_url").is_none());
413        #[derive(serde::Serialize)]
414        struct EmptyParams {}
415        let d = dry_run_envelope("readme", "https://u", EmptyParams {}, 1);
416        let d = serde_json::to_value(&d).expect("serialize dry-run envelope");
417        assert_eq!(d["dry_run"], true);
418        assert_eq!(d["data"]["planned_url"], "https://u");
419        assert_eq!(d["data"]["planned_params"], serde_json::json!({}));
420        assert!(usage_error("x").kind() == ErrorKind::Usage);
421    }
422
423    #[test]
424    fn optional_fields_omitted_not_null() {
425        let hit = CrateSearchHit {
426            name: "x".into(),
427            description: "d".into(),
428            downloads: 1,
429            version: "1.0.0".into(),
430            documentation: None,
431            max_version: None,
432            max_stable_version: None,
433            default_version: None,
434            recent_downloads: None,
435            exact_match: None,
436            yanked: None,
437            repository: None,
438            homepage: None,
439        };
440        let v = serde_json::to_value(&hit).expect("serialize hit");
441        assert!(v.get("documentation").is_none());
442        assert!(v.get("repository").is_none());
443        assert!(!v
444            .as_object()
445            .expect("object")
446            .values()
447            .any(|x| x.is_null()));
448
449        let readme = ReadmeData {
450            crate_name: "c".into(),
451            version: "latest".into(),
452            resolved_version: None,
453            markdown: "m".into(),
454            empty: false,
455            truncated: false,
456            source_url: "https://example.com".into(),
457            cache_hit: false,
458        };
459        let r = serde_json::to_value(&readme).expect("serialize readme");
460        assert!(r.get("resolved_version").is_none());
461        assert!(!r
462            .as_object()
463            .expect("object")
464            .values()
465            .any(|x| x.is_null()));
466    }
467
468    #[test]
469    fn apply_truncation_sets_flags() {
470        let cfg = Config {
471            max_output_bytes: 4,
472            ..Config::default()
473        };
474        let r = apply_truncation_to_readme(
475            ReadmeData {
476                crate_name: "c".into(),
477                version: "1".into(),
478                resolved_version: None,
479                markdown: "hello world".into(),
480                empty: false,
481                truncated: false,
482                source_url: "u".into(),
483            cache_hit: false,
484        },
485            &cfg,
486        );
487        assert!(r.truncated);
488        assert!(r.markdown.len() <= 4);
489        let i = apply_truncation_to_item(
490            GetItemData {
491                crate_name: "c".into(),
492                item_type: "fn".into(),
493                item_path: "c::f".into(),
494                item_name: "f".into(),
495                version: "1".into(),
496                resolved_version: None,
497                markdown: "abcdef".into(),
498                empty: false,
499                truncated: false,
500                source_url: "u".into(),
501                title: "t".into(),
502            cache_hit: false,
503        },
504            &cfg,
505        );
506        assert!(i.truncated);
507        assert_eq!(i.markdown, "abcd");
508    }
509
510    #[test]
511    fn truncate_zero_and_utf8_boundary() {
512        let (out, trunc) = truncate_output("abc", 0);
513        assert!(trunc);
514        assert!(out.is_empty());
515        let s = "áéí"; // multi-byte
516        let (out, trunc) = truncate_output(s, 2);
517        assert!(trunc);
518        assert!(out.is_char_boundary(out.len()));
519    }
520
521    #[test]
522    fn empty_search_in_crate_markdown() {
523        use crate::docs_rs::SearchInCrateData;
524        let data = SearchInCrateData {
525            crate_name: "c".into(),
526            query: String::new(),
527            version: "1".into(),
528            item_type: None,
529            match_mode: "prefix".into(),
530            total: 0,
531            emitted: 0,
532            hits: vec![],
533            truncated: false,
534            source_url: "u".into(),
535            cache_hit: false,
536        };
537        let md = render_search_in_crate_markdown(&data);
538        assert!(md.contains("all items"));
539        assert!(md.contains("No matching items"));
540    }
541}