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 SuccessEnvelope {
171 schema_version: SCHEMA_VERSION,
172 ok: true,
173 command,
174 data,
175 duration_ms,
176 source_url,
177 }
178}
179
180pub 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
200pub 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
221pub 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
237pub 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
259pub 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
271pub 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
284pub fn render_search_in_crate_markdown(data: &SearchInCrateData) -> String {
286 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
307pub 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
315pub 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
323pub 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 };
366 let md = render_search_markdown(&data);
367 assert!(md.contains("No crates found"));
368 }
369
370 #[test]
371 fn empty_readme_and_item() {
372 let r = ReadmeData {
373 crate_name: "c".into(),
374 version: "latest".into(),
375 resolved_version: None,
376 markdown: String::new(),
377 empty: true,
378 truncated: false,
379 source_url: "u".into(),
380 };
381 assert!(render_readme_markdown(&r).contains("No documentation"));
382 let i = GetItemData {
383 crate_name: "c".into(),
384 item_type: "fn".into(),
385 item_path: "c::f".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 title: "c::f (fn)".into(),
393 };
394 assert!(render_item_markdown(&i).contains("No documentation"));
395 }
396
397 #[test]
398 fn success_and_dry_run_envelopes() {
399 let payload = serde_json::json!({"n": 1});
400 let v = success_envelope("version", &payload, 3, Some("https://x"));
401 let v = serde_json::to_value(&v).expect("serialize success envelope");
402 assert_eq!(v["ok"], true);
403 assert_eq!(v["source_url"], "https://x");
404 assert_eq!(v["schema_version"], SCHEMA_VERSION);
405 let no_url = success_envelope("version", &payload, 1, None);
407 let no_url = serde_json::to_value(&no_url).expect("serialize");
408 assert!(no_url.get("source_url").is_none());
409 #[derive(serde::Serialize)]
410 struct EmptyParams {}
411 let d = dry_run_envelope("readme", "https://u", EmptyParams {}, 1);
412 let d = serde_json::to_value(&d).expect("serialize dry-run envelope");
413 assert_eq!(d["dry_run"], true);
414 assert_eq!(d["data"]["planned_url"], "https://u");
415 assert_eq!(d["data"]["planned_params"], serde_json::json!({}));
416 assert!(usage_error("x").kind() == ErrorKind::Usage);
417 }
418
419 #[test]
420 fn optional_fields_omitted_not_null() {
421 let hit = CrateSearchHit {
422 name: "x".into(),
423 description: "d".into(),
424 downloads: 1,
425 version: "1.0.0".into(),
426 documentation: None,
427 max_version: None,
428 max_stable_version: None,
429 default_version: None,
430 recent_downloads: None,
431 exact_match: None,
432 yanked: None,
433 repository: None,
434 homepage: None,
435 };
436 let v = serde_json::to_value(&hit).expect("serialize hit");
437 assert!(v.get("documentation").is_none());
438 assert!(v.get("repository").is_none());
439 assert!(!v
440 .as_object()
441 .expect("object")
442 .values()
443 .any(|x| x.is_null()));
444
445 let readme = ReadmeData {
446 crate_name: "c".into(),
447 version: "latest".into(),
448 resolved_version: None,
449 markdown: "m".into(),
450 empty: false,
451 truncated: false,
452 source_url: "https://example.com".into(),
453 };
454 let r = serde_json::to_value(&readme).expect("serialize readme");
455 assert!(r.get("resolved_version").is_none());
456 assert!(!r
457 .as_object()
458 .expect("object")
459 .values()
460 .any(|x| x.is_null()));
461 }
462
463 #[test]
464 fn apply_truncation_sets_flags() {
465 let cfg = Config {
466 max_output_bytes: 4,
467 ..Config::default()
468 };
469 let r = apply_truncation_to_readme(
470 ReadmeData {
471 crate_name: "c".into(),
472 version: "1".into(),
473 resolved_version: None,
474 markdown: "hello world".into(),
475 empty: false,
476 truncated: false,
477 source_url: "u".into(),
478 },
479 &cfg,
480 );
481 assert!(r.truncated);
482 assert!(r.markdown.len() <= 4);
483 let i = apply_truncation_to_item(
484 GetItemData {
485 crate_name: "c".into(),
486 item_type: "fn".into(),
487 item_path: "c::f".into(),
488 version: "1".into(),
489 resolved_version: None,
490 markdown: "abcdef".into(),
491 empty: false,
492 truncated: false,
493 source_url: "u".into(),
494 title: "t".into(),
495 },
496 &cfg,
497 );
498 assert!(i.truncated);
499 assert_eq!(i.markdown, "abcd");
500 }
501
502 #[test]
503 fn truncate_zero_and_utf8_boundary() {
504 let (out, trunc) = truncate_output("abc", 0);
505 assert!(trunc);
506 assert!(out.is_empty());
507 let s = "áéí"; let (out, trunc) = truncate_output(s, 2);
509 assert!(trunc);
510 assert!(out.is_char_boundary(out.len()));
511 }
512
513 #[test]
514 fn empty_search_in_crate_markdown() {
515 use crate::docs_rs::SearchInCrateData;
516 let data = SearchInCrateData {
517 crate_name: "c".into(),
518 query: String::new(),
519 version: "1".into(),
520 total: 0,
521 emitted: 0,
522 hits: vec![],
523 truncated: false,
524 source_url: "u".into(),
525 };
526 let md = render_search_in_crate_markdown(&data);
527 assert!(md.contains("all items"));
528 assert!(md.contains("No matching items"));
529 }
530}