1use 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#[derive(Debug, Serialize)]
15pub struct SuccessEnvelope<'a, T: Serialize> {
16 pub schema_version: u32,
18 pub ok: bool,
20 pub command: &'a str,
22 pub data: T,
24 pub duration_ms: u64,
26 #[serde(skip_serializing_if = "Option::is_none")]
28 pub source_url: Option<&'a str>,
29}
30
31#[derive(Debug, Serialize)]
36pub struct DryRunEnvelope<'a, P: Serialize> {
37 pub schema_version: u32,
39 pub ok: bool,
41 pub command: &'a str,
43 pub dry_run: bool,
45 pub data: DryRunData<'a, P>,
47 pub duration_ms: u64,
49}
50
51#[derive(Debug, Serialize)]
53pub struct DryRunData<'a, P: Serialize> {
54 pub planned_url: &'a str,
56 pub planned_params: P,
58}
59
60#[derive(Debug, Serialize)]
62pub struct ErrorEnvelope {
63 pub schema_version: u32,
65 pub ok: bool,
67 pub error: ErrorBody,
69}
70
71#[derive(Debug, Serialize)]
73pub struct ErrorBody {
74 pub code: u8,
76 pub kind: String,
78 pub message: String,
80 pub retryable: bool,
82 #[serde(skip_serializing_if = "Option::is_none")]
84 pub retry_after_secs: Option<u64>,
85}
86
87pub fn render_schema_markdown(cmd: &str, schema: &serde_json::Value) -> String {
92 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
163pub 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
173pub 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
191pub 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
211pub 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
232pub 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
248pub 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
270pub 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
282pub 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
295pub fn render_search_in_crate_markdown(data: &SearchInCrateData) -> String {
297 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
318pub 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
326pub 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
334pub 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 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 = "áéí"; 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}