1use crate::{DiffOptions, DiffResult, OutputFormat};
6use anyhow::{anyhow, Result};
7use serde::Serialize;
8use serde_json::Value;
9
10pub fn value_type_name(value: &Value) -> &str {
12 match value {
13 Value::Null => "Null",
14 Value::Bool(_) => "Boolean",
15 Value::Number(_) => "Number",
16 Value::String(_) => "String",
17 Value::Array(_) => "Array",
18 Value::Object(_) => "Object",
19 }
20}
21
22pub fn format_output<T: Serialize>(results: &[T], format: OutputFormat) -> Result<String> {
24 match format {
25 OutputFormat::Json => serde_json::to_string_pretty(results)
26 .map_err(|e| anyhow!("JSON serialization error: {e}")),
27 OutputFormat::Yaml => {
28 serde_yaml::to_string(results).map_err(|e| anyhow!("YAML serialization error: {e}"))
29 }
30 OutputFormat::Diffx => {
31 let mut output = String::new();
32 for result in results {
33 let json = serde_json::to_string(result)?;
34 output.push_str(&json);
35 output.push('\n');
36 }
37 Ok(output)
38 }
39 }
40}
41
42pub fn format_diff_output(
44 results: &[DiffResult],
45 format: OutputFormat,
46 _options: Option<&DiffOptions>,
47) -> Result<String> {
48 match format {
49 OutputFormat::Json => serde_json::to_string_pretty(results)
50 .map_err(|e| anyhow!("JSON serialization error: {e}")),
51 OutputFormat::Yaml => {
52 let mut output = String::new();
53 for result in results {
54 match result {
55 DiffResult::Added(path, value) => {
56 output.push_str("- Added:\n");
57 output.push_str(&format!(" - {path}\n"));
58 output.push_str(&format!(
59 " - {}\n",
60 serde_yaml::to_string(value).unwrap_or_default().trim()
61 ));
62 }
63 DiffResult::Removed(path, value) => {
64 output.push_str("- Removed:\n");
65 output.push_str(&format!(" - {path}\n"));
66 output.push_str(&format!(
67 " - {}\n",
68 serde_yaml::to_string(value).unwrap_or_default().trim()
69 ));
70 }
71 DiffResult::Modified(path, old_value, new_value) => {
72 output.push_str("- Modified:\n");
73 output.push_str(&format!(" - {path}\n"));
74 output.push_str(&format!(
75 " - {}\n",
76 serde_yaml::to_string(old_value).unwrap_or_default().trim()
77 ));
78 output.push_str(&format!(
79 " - {}\n",
80 serde_yaml::to_string(new_value).unwrap_or_default().trim()
81 ));
82 }
83 DiffResult::TypeChanged(path, old_value, new_value) => {
84 output.push_str("- TypeChanged:\n");
85 output.push_str(&format!(" - {path}\n"));
86 output.push_str(&format!(
87 " - {}\n",
88 serde_yaml::to_string(old_value).unwrap_or_default().trim()
89 ));
90 output.push_str(&format!(
91 " - {}\n",
92 serde_yaml::to_string(new_value).unwrap_or_default().trim()
93 ));
94 }
95 }
96 }
97 Ok(output)
98 }
99 OutputFormat::Diffx => {
100 let mut output = String::new();
101 for result in results {
102 output.push_str(&result.to_string());
103 output.push('\n');
104 }
105 Ok(output)
106 }
107 }
108}