1use serde_json::Value;
2
3#[derive(Clone, clap::ValueEnum)]
4pub enum OutputFormat {
5 Json,
6 Text,
7 Jsonl,
8}
9
10pub fn format_output(value: &Value, format: &OutputFormat) -> String {
11 match format {
12 OutputFormat::Json => format_as_json(value),
13 OutputFormat::Text => format_as_text(value),
14 OutputFormat::Jsonl => format_as_jsonl(value),
15 }
16}
17
18fn format_as_json(value: &Value) -> String {
19 serde_json::to_string_pretty(value).unwrap_or_default()
20}
21
22fn format_as_jsonl(value: &Value) -> String {
23 match value {
24 Value::Array(items) => items
25 .iter()
26 .map(|item| serde_json::to_string(item).unwrap_or_default())
27 .collect::<Vec<_>>()
28 .join("\n"),
29 _ => serde_json::to_string(value).unwrap_or_default(),
30 }
31}
32
33fn format_as_text(value: &Value) -> String {
34 match value {
35 Value::Object(map) => format_object_as_text(map),
36 Value::Array(items) => format_array_as_text(items),
37 Value::String(string) => string.clone(),
38 Value::Null => String::new(),
39 other => other.to_string(),
40 }
41}
42
43fn format_object_as_text(map: &serde_json::Map<String, Value>) -> String {
44 map.iter()
45 .map(|(key, value)| format!("{key}: {}", scalar_to_text(value)))
46 .collect::<Vec<_>>()
47 .join("\n")
48}
49
50fn format_array_as_text(items: &[Value]) -> String {
51 items
52 .iter()
53 .map(format_as_text)
54 .collect::<Vec<_>>()
55 .join("\n---\n")
56}
57
58fn scalar_to_text(value: &Value) -> String {
59 match value {
60 Value::String(string) => string.clone(),
61 Value::Null => String::new(),
62 Value::Array(_) | Value::Object(_) => serde_json::to_string(value).unwrap_or_default(),
63 other => other.to_string(),
64 }
65}