-
Notifications
You must be signed in to change notification settings - Fork 174
Expand file tree
/
Copy pathconfig_cmd.rs
More file actions
356 lines (301 loc) · 10.2 KB
/
config_cmd.rs
File metadata and controls
356 lines (301 loc) · 10.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
//! `mofa config` command implementation
use crate::CliError;
use colored::Colorize;
use mofa_kernel::config::{load_config, substitute_env_vars};
use serde_json::{Value, json};
use std::collections::HashMap;
use std::fs;
use std::path::PathBuf;
/// Execute the `mofa config get` command
pub fn run_get(key: &str) -> Result<(), CliError> {
let config = load_global_config()?;
match config.get(key) {
Some(value) => println!("{}", value),
None => {
println!("Config key '{}' not found", key.yellow());
std::process::exit(1);
}
}
Ok(())
}
/// Execute the `mofa config set` command
pub fn run_set(key: &str, value: &str) -> Result<(), CliError> {
println!(
"{} Setting config: {} = {}",
"->".green(),
key.cyan(),
value.white()
);
let mut config = load_global_config()?;
config.insert(key.to_string(), value.to_string());
save_global_config(config)?;
println!("{} Config saved successfully", "✓".green());
Ok(())
}
/// Execute the `mofa config unset` command
pub fn run_unset(key: &str) -> Result<(), CliError> {
println!("{} Unsetting config: {}", "->".green(), key.cyan());
let mut config = load_global_config()?;
if config.remove(key).is_none() {
println!("{} Config key '{}' not found", "Warning".yellow(), key);
} else {
save_global_config(config)?;
println!("{} Config unset successfully", "✓".green());
}
Ok(())
}
/// Execute the `mofa config list` command
pub fn run_list() -> Result<(), CliError> {
println!("{} Global configuration", "->".green());
println!();
let config = load_global_config()?;
if config.is_empty() {
println!(" No configuration values set.");
} else {
let width = config.keys().map(|k| k.len()).max().unwrap_or(0);
for (key, value) in config {
println!(" {:<width$} = {}", key, value, width = width);
}
}
Ok(())
}
/// Execute the `mofa config validate` command
pub fn run_validate(config_path: Option<PathBuf>) -> Result<(), CliError> {
println!("{} Validating configuration", "->".green());
let config_path = if let Some(path) = config_path {
path
} else {
// Try to find a config file
find_config_file().ok_or_else(|| CliError::ConfigError("No config file found".into()))?
};
println!(
" Config file: {}",
config_path.display().to_string().cyan()
);
// Load and validate the config
match validate_config_file(&config_path) {
Ok(_) => {
println!("{} Configuration is valid", "✓".green());
Ok(())
}
Err(e) => {
println!("{} Configuration validation failed: {}", "✗".red(), e);
std::process::exit(1);
}
}
}
/// Execute the `mofa config path` command
pub fn run_path() -> Result<(), CliError> {
let path = crate::utils::mofa_config_dir()?;
println!("{}", path.display());
Ok(())
}
/// Load global configuration from config directory
fn load_global_config() -> Result<HashMap<String, String>, CliError> {
let config_dir = crate::utils::mofa_config_dir()?;
let config_file = config_dir.join("config.yml");
if !config_file.exists() {
return Ok(HashMap::new());
}
let _content = fs::read_to_string(&config_file)?;
// Use the global config loading
let config: Value = load_config(config_file.to_string_lossy().as_ref())
.map_err(|e| CliError::ConfigError(format!("Failed to parse config: {}", e)))?;
let mut result = HashMap::new();
if let Some(obj) = config.as_object() {
for (key, value) in obj {
if let Some(s) = value.as_str() {
result.insert(key.clone(), s.to_string());
} else {
result.insert(key.clone(), value.to_string());
}
}
}
Ok(result)
}
/// Save global configuration to config directory
fn save_global_config(config: HashMap<String, String>) -> Result<(), CliError> {
let config_dir = crate::utils::mofa_config_dir()?;
fs::create_dir_all(&config_dir)?;
let config_file = config_dir.join("config.yml");
// Convert to JSON/YAML structure
let json_obj: Value = config.into_iter().map(|(k, v)| (k, json!(v))).collect();
let content = serde_yaml::to_string(&json_obj)?;
fs::write(&config_file, content)?;
Ok(())
}
/// Find a config file in the current directory or parent directories
fn find_config_file() -> Option<PathBuf> {
let supported_filenames = [
"agent.yml",
"agent.yaml",
"agent.toml",
"agent.json",
"agent.ini",
"agent.ron",
"agent.json5",
];
// Try current directory first
for name in &supported_filenames {
let path = PathBuf::from(name);
if path.exists() {
return Some(path);
}
}
// Search upward
let mut current = std::env::current_dir().ok()?;
loop {
for name in &supported_filenames {
let target = current.join(name);
if target.exists() {
return Some(target);
}
}
if !current.pop() {
break;
}
}
None
}
/// Validate a configuration file
fn validate_config_file(path: &PathBuf) -> Result<(), CliError> {
let content = fs::read_to_string(path)?;
// Check for environment variable substitution
let substituted = substitute_env_vars(&content);
// Try to parse based on file extension
let result = match path.extension().and_then(|e| e.to_str()) {
Some(ext) => match ext.to_lowercase().as_str() {
"yaml" | "yml" => serde_yaml::from_str::<Value>(&substituted)
.map_err(|e| CliError::ConfigError(format!("YAML parsing error: {}", e))),
"toml" => toml::from_str::<Value>(&substituted)
.map_err(|e| CliError::ConfigError(format!("TOML parsing error: {}", e))),
"json" => serde_json::from_str::<Value>(&substituted)
.map_err(|e| CliError::ConfigError(format!("JSON parsing error: {}", e))),
"json5" => json5::from_str::<Value>(&substituted)
.map_err(|e| CliError::ConfigError(format!("JSON5 parsing error: {}", e))),
"ini" => {
return Err(CliError::ConfigError(
"INI format validation is not yet supported. Please use YAML, TOML, or JSON format for validated configuration.".into()
));
}
"ron" => {
return Err(CliError::ConfigError(
"RON format validation is not yet supported. Please use YAML, TOML, or JSON format for validated configuration.".into()
));
}
_ => {
return Err(CliError::ConfigError(format!(
"Unsupported config format: {}",
ext
)));
}
},
None => {
return Err(CliError::ConfigError("Cannot determine file format".into()));
}
};
let config = result?;
// Validate required fields
if let Some(obj) = config.as_object() {
// Check for agent section
if !obj.contains_key("agent") {
return Err(CliError::ConfigError(
"Missing required 'agent' section".into(),
));
}
// Check for required agent fields
if let Some(agent) = obj.get("agent").and_then(|v| v.as_object()) {
if !agent.contains_key("id") {
return Err(CliError::ConfigError(
"Missing required 'agent.id' field".into(),
));
}
if !agent.contains_key("name") {
return Err(CliError::ConfigError(
"Missing required 'agent.name' field".into(),
));
}
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::validate_config_file;
use crate::CliError;
use std::fs;
use std::path::PathBuf;
use tempfile::TempDir;
fn write_temp_json5(content: &str) -> (TempDir, PathBuf) {
let dir = TempDir::new().expect("create temp dir");
let path = dir.path().join("agent.json5");
fs::write(&path, content).expect("write json5 file");
(dir, path)
}
#[test]
fn accepts_json5_comments() {
let json5 = r#"
{
// comment
agent: {
id: "agent-1",
name: "Agent One"
}
}
"#;
let (_dir, path) = write_temp_json5(json5);
let result = validate_config_file(&path);
assert!(result.is_ok(), "expected JSON5 with comments to be valid");
}
#[test]
fn accepts_json5_trailing_commas() {
let json5 = r#"
{
agent: {
id: "agent-1",
name: "Agent One",
},
}
"#;
let (_dir, path) = write_temp_json5(json5);
let result = validate_config_file(&path);
assert!(
result.is_ok(),
"expected JSON5 with trailing commas to be valid"
);
}
#[test]
fn accepts_json5_unquoted_keys() {
let json5 = r#"
{
agent: {
id: "agent-1",
name: "Agent One"
}
}
"#;
let (_dir, path) = write_temp_json5(json5);
let result = validate_config_file(&path);
assert!(
result.is_ok(),
"expected JSON5 with unquoted keys to be valid"
);
}
#[test]
fn rejects_invalid_json5() {
let invalid = r#"
{
agent: {
id: "agent-1",
name: "Agent One,
}
}
"#;
let (_dir, path) = write_temp_json5(invalid);
let result = validate_config_file(&path);
match result {
Err(CliError::ConfigError(_)) => {}
other => panic!("expected ConfigError, got: {:?}", other),
}
}
}