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    success_envelope_with_ok(command, data, duration_ms, source_url, true)
171}
172
173/// Build a success-shaped envelope with an explicit top-level `ok` (used by `doctor`).
174pub fn success_envelope_with_ok<'a, T: Serialize>(
175    command: &'a str,
176    data: T,
177    duration_ms: u64,
178    source_url: Option<&'a str>,
179    ok: bool,
180) -> SuccessEnvelope<'a, T> {
181    SuccessEnvelope {
182        schema_version: SCHEMA_VERSION,
183        ok,
184        command,
185        data,
186        duration_ms,
187        source_url,
188    }
189}
190
191/// Build a typed dry-run success envelope with planned URL/params.
192pub fn dry_run_envelope<'a, P: Serialize>(
193    command: &'a str,
194    planned_url: &'a str,
195    planned_params: P,
196    duration_ms: u64,
197) -> DryRunEnvelope<'a, P> {
198    DryRunEnvelope {
199        schema_version: SCHEMA_VERSION,
200        ok: true,
201        command,
202        dry_run: true,
203        data: DryRunData {
204            planned_url,
205            planned_params,
206        },
207        duration_ms,
208    }
209}
210
211/// Build an error envelope. SIGINT/SIGTERM surface as kind `canceled` with exit 130/143.
212pub fn error_envelope(err: &AppError) -> ErrorEnvelope {
213    let kind = err.kind();
214    let kind_str = match kind {
215        ErrorKind::Interrupted | ErrorKind::Terminated => "canceled",
216        ErrorKind::BrokenPipe => "broken_pipe",
217        other => other.as_str(),
218    };
219    ErrorEnvelope {
220        schema_version: SCHEMA_VERSION,
221        ok: false,
222        error: ErrorBody {
223            code: kind.exit_code(),
224            kind: kind_str.to_string(),
225            message: err.message().to_string(),
226            retryable: kind.retryable(),
227            retry_after_secs: err.retry_after_secs(),
228        },
229    }
230}
231
232/// Truncate UTF-8 text on a char boundary; returns (text, truncated).
233pub fn truncate_output(text: &str, max_bytes: u64) -> (String, bool) {
234    if max_bytes == 0 {
235        return (String::new(), true);
236    }
237    let max = max_bytes as usize;
238    if text.len() <= max {
239        return (text.to_string(), false);
240    }
241    let mut end = max;
242    while end > 0 && !text.is_char_boundary(end) {
243        end -= 1;
244    }
245    (text[..end].to_string(), true)
246}
247
248/// Human Markdown for search-crates.
249pub fn render_search_markdown(data: &SearchCratesData) -> String {
250    let mut out = format!(
251        "# Crate Search Results for \"{}\" (page {})\n\n",
252        data.query, data.page
253    );
254    if data.hits.is_empty() {
255        out.push_str("No crates found.\n");
256        return out;
257    }
258    for h in &data.hits {
259        out.push_str(&format!("## {} ({})\n\n", h.name, h.version));
260        out.push_str(&format!("**Description:** {}\n\n", h.description));
261        out.push_str(&format!("**Downloads:** {}\n\n", h.downloads));
262        out.push_str(&format!(
263            "**Documentation:** {}\n\n---\n\n",
264            h.documentation.as_deref().unwrap_or("N/A")
265        ));
266    }
267    out
268}
269
270/// Human Markdown for readme.
271pub fn render_readme_markdown(data: &ReadmeData) -> String {
272    let mut out = format!("# {} Documentation\n\n", data.crate_name);
273    if data.empty {
274        out.push_str("No documentation content found.\n");
275    } else {
276        out.push_str(&data.markdown);
277        out.push('\n');
278    }
279    out
280}
281
282/// Human Markdown for get-item.
283pub fn render_item_markdown(data: &GetItemData) -> String {
284    let mut out = format!("# {}\n\n", data.title);
285    out.push_str(&format!("**Documentation URL:** {}\n\n", data.source_url));
286    if data.empty {
287        out.push_str("No documentation content found.\n");
288    } else {
289        out.push_str(&data.markdown);
290        out.push('\n');
291    }
292    out
293}
294
295/// Human Markdown for search-in-crate.
296pub fn render_search_in_crate_markdown(data: &SearchInCrateData) -> String {
297    // Borrow query text — no String clone for the heading.
298    let term = if data.query.is_empty() {
299        "all items"
300    } else {
301        data.query.as_str()
302    };
303    let mut out = format!(
304        "# Search Results for \"{}\" in {}\n\nFound {} items (emitted {})\n\n",
305        term, data.crate_name, data.total, data.emitted
306    );
307    if data.hits.is_empty() {
308        out.push_str("No matching items found.\n");
309        return out;
310    }
311    for h in &data.hits {
312        out.push_str(&format!("## {} ({})\n\n", h.name, h.kind));
313        out.push_str(&format!("**Link:** {}\n\n---\n\n", h.url));
314    }
315    out
316}
317
318/// Apply max_output_bytes truncation to readme payload.
319pub fn apply_truncation_to_readme(mut data: ReadmeData, cfg: &Config) -> ReadmeData {
320    let (md, trunc) = truncate_output(&data.markdown, cfg.max_output_bytes);
321    data.markdown = md;
322    data.truncated = trunc;
323    data
324}
325
326/// Apply max_output_bytes truncation to get-item payload.
327pub fn apply_truncation_to_item(mut data: GetItemData, cfg: &Config) -> GetItemData {
328    let (md, trunc) = truncate_output(&data.markdown, cfg.max_output_bytes);
329    data.markdown = md;
330    data.truncated = trunc;
331    data
332}
333
334/// Map clap parse failures to usage errors.
335pub fn usage_error(msg: impl Into<String>) -> AppError {
336    AppError::new(ErrorKind::Usage, msg)
337}
338
339#[cfg(test)]
340mod tests {
341    use super::*;
342    use crate::crates_io::{CrateSearchHit, SearchCratesData, SearchMeta};
343    use crate::docs_rs::{GetItemData, ReadmeData};
344    use crate::error::AppError;
345
346    #[test]
347    fn truncate_marks_flag() {
348        let (out, trunc) = truncate_output("abcdef", 3);
349        assert!(trunc);
350        assert_eq!(out, "abc");
351    }
352
353    #[test]
354    fn cancel_kinds_in_envelope() {
355        let e = error_envelope(&AppError::terminated());
356        assert_eq!(e.error.code, 143);
357        assert_eq!(e.error.kind, "canceled");
358        let e = error_envelope(&AppError::interrupted());
359        assert_eq!(e.error.code, 130);
360        assert_eq!(e.error.kind, "canceled");
361    }
362
363    #[test]
364    fn empty_search_markdown() {
365        let data = SearchCratesData {
366            query: "z".into(),
367            page: 1,
368            per_page: 10,
369            sort: "relevance".into(),
370            hits: vec![],
371            meta: SearchMeta {
372                total: 0,
373                next_page: None,
374                prev_page: None,
375            },
376            cache_hit: false,
377        };
378        let md = render_search_markdown(&data);
379        assert!(md.contains("No crates found"));
380    }
381
382    #[test]
383    fn empty_readme_and_item() {
384        let r = ReadmeData {
385            crate_name: "c".into(),
386            version: "latest".into(),
387            resolved_version: None,
388            markdown: String::new(),
389            empty: true,
390            truncated: false,
391            source_url: "u".into(),
392            cache_hit: false,
393        };
394        assert!(render_readme_markdown(&r).contains("No documentation"));
395        let i = GetItemData {
396            crate_name: "c".into(),
397            item_type: "fn".into(),
398            item_path: "c::f".into(),
399            item_name: "f".into(),
400            version: "latest".into(),
401            resolved_version: None,
402            markdown: String::new(),
403            empty: true,
404            truncated: false,
405            source_url: "u".into(),
406            title: "c::f (fn)".into(),
407            cache_hit: false,
408            extraction: None,
409        };
410        assert!(render_item_markdown(&i).contains("No documentation"));
411    }
412
413    #[test]
414    fn success_and_dry_run_envelopes() {
415        let payload = serde_json::json!({"n": 1});
416        let v = success_envelope("version", &payload, 3, Some("https://x"));
417        let v = serde_json::to_value(&v).expect("serialize success envelope");
418        assert_eq!(v["ok"], true);
419        assert_eq!(v["source_url"], "https://x");
420        assert_eq!(v["schema_version"], SCHEMA_VERSION);
421        // Optional source_url omitted when None (not JSON null).
422        let no_url = success_envelope("version", &payload, 1, None);
423        let no_url = serde_json::to_value(&no_url).expect("serialize");
424        assert!(no_url.get("source_url").is_none());
425        #[derive(serde::Serialize)]
426        struct EmptyParams {}
427        let d = dry_run_envelope("readme", "https://u", EmptyParams {}, 1);
428        let d = serde_json::to_value(&d).expect("serialize dry-run envelope");
429        assert_eq!(d["dry_run"], true);
430        assert_eq!(d["data"]["planned_url"], "https://u");
431        assert_eq!(d["data"]["planned_params"], serde_json::json!({}));
432        assert!(usage_error("x").kind() == ErrorKind::Usage);
433    }
434
435    #[test]
436    fn optional_fields_omitted_not_null() {
437        let hit = CrateSearchHit {
438            name: "x".into(),
439            description: "d".into(),
440            downloads: 1,
441            version: "1.0.0".into(),
442            documentation: None,
443            max_version: None,
444            max_stable_version: None,
445            default_version: None,
446            recent_downloads: None,
447            exact_match: None,
448            yanked: None,
449            repository: None,
450            homepage: None,
451        };
452        let v = serde_json::to_value(&hit).expect("serialize hit");
453        assert!(v.get("documentation").is_none());
454        assert!(v.get("repository").is_none());
455        assert!(!v.as_object().expect("object").values().any(|x| x.is_null()));
456
457        let readme = ReadmeData {
458            crate_name: "c".into(),
459            version: "latest".into(),
460            resolved_version: None,
461            markdown: "m".into(),
462            empty: false,
463            truncated: false,
464            source_url: "https://example.com".into(),
465            cache_hit: false,
466        };
467        let r = serde_json::to_value(&readme).expect("serialize readme");
468        assert!(r.get("resolved_version").is_none());
469        assert!(!r.as_object().expect("object").values().any(|x| x.is_null()));
470    }
471
472    #[test]
473    fn apply_truncation_sets_flags() {
474        let cfg = Config {
475            max_output_bytes: 4,
476            ..Config::default()
477        };
478        let r = apply_truncation_to_readme(
479            ReadmeData {
480                crate_name: "c".into(),
481                version: "1".into(),
482                resolved_version: None,
483                markdown: "hello world".into(),
484                empty: false,
485                truncated: false,
486                source_url: "u".into(),
487                cache_hit: false,
488            },
489            &cfg,
490        );
491        assert!(r.truncated);
492        assert!(r.markdown.len() <= 4);
493        let i = apply_truncation_to_item(
494            GetItemData {
495                crate_name: "c".into(),
496                item_type: "fn".into(),
497                item_path: "c::f".into(),
498                item_name: "f".into(),
499                version: "1".into(),
500                resolved_version: None,
501                markdown: "abcdef".into(),
502                empty: false,
503                truncated: false,
504                source_url: "u".into(),
505                title: "t".into(),
506                cache_hit: false,
507                extraction: None,
508            },
509            &cfg,
510        );
511        assert!(i.truncated);
512        assert_eq!(i.markdown, "abcd");
513    }
514
515    #[test]
516    fn truncate_zero_and_utf8_boundary() {
517        let (out, trunc) = truncate_output("abc", 0);
518        assert!(trunc);
519        assert!(out.is_empty());
520        let s = "áéí"; // multi-byte
521        let (out, trunc) = truncate_output(s, 2);
522        assert!(trunc);
523        assert!(out.is_char_boundary(out.len()));
524    }
525
526    #[test]
527    fn empty_search_in_crate_markdown() {
528        use crate::docs_rs::SearchInCrateData;
529        let data = SearchInCrateData {
530            crate_name: "c".into(),
531            query: String::new(),
532            version: "1".into(),
533            item_type: None,
534            match_mode: "prefix".into(),
535            total: 0,
536            emitted: 0,
537            hits: vec![],
538            truncated: false,
539            source_url: "u".into(),
540            cache_hit: false,
541        };
542        let md = render_search_in_crate_markdown(&data);
543        assert!(md.contains("all items"));
544        assert!(md.contains("No matching items"));
545    }
546}