1use std::fs;
2use std::path::Path;
3use std::str::FromStr;
4
5use anyhow::{Context, Result, bail};
6use indexmap::IndexMap;
7use serde::{Deserialize, Serialize};
8
9pub const NAME: &str = "ConfigForge";
10pub const VERSION: &str = env!("CARGO_PKG_VERSION");
11
12pub fn describe() -> &'static str {
13 "A CLI tool for converting, inspecting, and validating configuration files."
14}
15
16#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
17#[serde(untagged)]
18pub enum ConfigValue {
19 Null,
20 Bool(bool),
21 Integer(i64),
22 Float(f64),
23 String(String),
24 Array(Vec<ConfigValue>),
25 Object(IndexMap<String, ConfigValue>),
26}
27
28#[derive(Clone, Copy, Debug, Eq, PartialEq)]
29pub enum Format {
30 Json,
31 Toml,
32 Yaml,
33}
34
35impl Format {
36 pub fn detect_path(path: &Path) -> Result<Self> {
37 let extension = path
38 .extension()
39 .and_then(|value| value.to_str())
40 .map(str::to_ascii_lowercase)
41 .with_context(|| format!("cannot detect format for `{}`", path.display()))?;
42
43 match extension.as_str() {
44 "json" => Ok(Self::Json),
45 "toml" => Ok(Self::Toml),
46 "yaml" | "yml" => Ok(Self::Yaml),
47 _ => bail!("unsupported file extension `{extension}`"),
48 }
49 }
50
51 pub fn name(self) -> &'static str {
52 match self {
53 Self::Json => "json",
54 Self::Toml => "toml",
55 Self::Yaml => "yaml",
56 }
57 }
58}
59
60impl FromStr for Format {
61 type Err = anyhow::Error;
62
63 fn from_str(value: &str) -> Result<Self> {
64 match value.to_ascii_lowercase().as_str() {
65 "json" => Ok(Self::Json),
66 "toml" => Ok(Self::Toml),
67 "yaml" | "yml" => Ok(Self::Yaml),
68 _ => bail!("unsupported format `{value}`"),
69 }
70 }
71}
72
73#[derive(Debug)]
74pub struct DocumentInfo {
75 pub format: Format,
76 pub root_kind: &'static str,
77 pub size_bytes: u64,
78}
79
80pub fn inspect_path(path: impl AsRef<Path>, format: Option<Format>) -> Result<DocumentInfo> {
81 let path = path.as_ref();
82 let format = match format {
83 Some(format) => format,
84 None => Format::detect_path(path)?,
85 };
86 let content = fs::read_to_string(path)
87 .with_context(|| format!("failed to read input file `{}`", path.display()))?;
88 let value = parse_str(&content, format)?;
89 let metadata = fs::metadata(path)
90 .with_context(|| format!("failed to read metadata for `{}`", path.display()))?;
91
92 Ok(DocumentInfo {
93 format,
94 root_kind: value.kind(),
95 size_bytes: metadata.len(),
96 })
97}
98
99pub fn convert_path(
100 input: impl AsRef<Path>,
101 output: Option<impl AsRef<Path>>,
102 from: Option<Format>,
103 to: Option<Format>,
104) -> Result<String> {
105 let input = input.as_ref();
106 let input_format = match from {
107 Some(format) => format,
108 None => Format::detect_path(input)?,
109 };
110 let output_format = match (to, output.as_ref().map(|path| path.as_ref())) {
111 (Some(format), _) => format,
112 (None, Some(path)) => Format::detect_path(path)?,
113 (None, None) => bail!("output format is required when writing to stdout"),
114 };
115
116 let content = fs::read_to_string(input)
117 .with_context(|| format!("failed to read input file `{}`", input.display()))?;
118 let value = parse_str(&content, input_format)?;
119 let rendered = render_string(&value, output_format)?;
120
121 if let Some(output) = output {
122 fs::write(output.as_ref(), &rendered).with_context(|| {
123 format!(
124 "failed to write output file `{}`",
125 output.as_ref().display()
126 )
127 })?;
128 }
129
130 Ok(rendered)
131}
132
133pub fn parse_str(content: &str, format: Format) -> Result<ConfigValue> {
134 match format {
135 Format::Json => {
136 let value: serde_json::Value =
137 serde_json::from_str(content).context("failed to parse JSON")?;
138 json_to_config(value)
139 }
140 Format::Toml => {
141 let value: toml::Value = toml::from_str(content).context("failed to parse TOML")?;
142 toml_to_config(value)
143 }
144 Format::Yaml => serde_yaml::from_str(content).context("failed to parse YAML"),
145 }
146}
147
148pub fn render_string(value: &ConfigValue, format: Format) -> Result<String> {
149 match format {
150 Format::Json => {
151 let mut rendered =
152 serde_json::to_string_pretty(value).context("failed to render JSON")?;
153 rendered.push('\n');
154 Ok(rendered)
155 }
156 Format::Toml => {
157 if !matches!(value, ConfigValue::Object(_)) {
158 bail!("TOML output requires an object at the document root");
159 }
160 let rendered = toml::to_string_pretty(value).context("failed to render TOML")?;
161 Ok(rendered)
162 }
163 Format::Yaml => serde_yaml::to_string(value).context("failed to render YAML"),
164 }
165}
166
167impl ConfigValue {
168 pub fn kind(&self) -> &'static str {
169 match self {
170 Self::Null => "null",
171 Self::Bool(_) => "bool",
172 Self::Integer(_) => "integer",
173 Self::Float(_) => "float",
174 Self::String(_) => "string",
175 Self::Array(_) => "array",
176 Self::Object(_) => "object",
177 }
178 }
179}
180
181fn json_to_config(value: serde_json::Value) -> Result<ConfigValue> {
182 match value {
183 serde_json::Value::Null => Ok(ConfigValue::Null),
184 serde_json::Value::Bool(value) => Ok(ConfigValue::Bool(value)),
185 serde_json::Value::Number(value) => {
186 if let Some(value) = value.as_i64() {
187 Ok(ConfigValue::Integer(value))
188 } else if value.as_u64().is_some() {
189 bail!("JSON unsigned integer exceeds the supported i64 range")
190 } else if let Some(value) = value.as_f64() {
191 Ok(ConfigValue::Float(value))
192 } else {
193 bail!("unsupported JSON number `{value}`")
194 }
195 }
196 serde_json::Value::String(value) => Ok(ConfigValue::String(value)),
197 serde_json::Value::Array(values) => values
198 .into_iter()
199 .map(json_to_config)
200 .collect::<Result<Vec<_>>>()
201 .map(ConfigValue::Array),
202 serde_json::Value::Object(values) => values
203 .into_iter()
204 .map(|(key, value)| json_to_config(value).map(|value| (key, value)))
205 .collect::<Result<IndexMap<_, _>>>()
206 .map(ConfigValue::Object),
207 }
208}
209
210fn toml_to_config(value: toml::Value) -> Result<ConfigValue> {
211 match value {
212 toml::Value::String(value) => Ok(ConfigValue::String(value)),
213 toml::Value::Integer(value) => Ok(ConfigValue::Integer(value)),
214 toml::Value::Float(value) => Ok(ConfigValue::Float(value)),
215 toml::Value::Boolean(value) => Ok(ConfigValue::Bool(value)),
216 toml::Value::Datetime(value) => Ok(ConfigValue::String(value.to_string())),
217 toml::Value::Array(values) => values
218 .into_iter()
219 .map(toml_to_config)
220 .collect::<Result<Vec<_>>>()
221 .map(ConfigValue::Array),
222 toml::Value::Table(values) => values
223 .into_iter()
224 .map(|(key, value)| toml_to_config(value).map(|value| (key, value)))
225 .collect::<Result<IndexMap<_, _>>>()
226 .map(ConfigValue::Object),
227 }
228}