Skip to main content

ito_core/
config.rs

1//! JSON configuration file CRUD operations.
2//!
3//! This module provides low-level functions for reading, writing, and
4//! manipulating JSON configuration files with dot-delimited path navigation.
5
6use std::path::Path;
7
8use crate::errors::{CoreError, CoreResult};
9use ito_config::ConfigContext;
10use ito_config::load_cascading_project_config;
11use ito_config::types::{IntegrationMode, WorktreeStrategy};
12
13/// Read a JSON config file, returning an empty object if the file doesn't exist.
14///
15/// # Errors
16///
17/// Returns [`CoreError::Serde`] if the file contains invalid JSON or is not a JSON object.
18pub fn read_json_config(path: &Path) -> CoreResult<serde_json::Value> {
19    let Ok(contents) = std::fs::read_to_string(path) else {
20        return Ok(serde_json::Value::Object(serde_json::Map::new()));
21    };
22    let v: serde_json::Value = serde_json::from_str(&contents).map_err(|e| {
23        CoreError::serde(format!("Invalid JSON in {}", path.display()), e.to_string())
24    })?;
25    match v {
26        serde_json::Value::Object(_) => Ok(v),
27        _ => Err(CoreError::serde(
28            format!("Expected JSON object in {}", path.display()),
29            "root value is not an object",
30        )),
31    }
32}
33
34/// Write a JSON value to a config file (pretty-printed with trailing newline).
35///
36/// # Errors
37///
38/// Returns [`CoreError::Serde`] if serialization fails, or [`CoreError::Io`] if writing fails.
39pub fn write_json_config(path: &Path, value: &serde_json::Value) -> CoreResult<()> {
40    let mut bytes = serde_json::to_vec_pretty(value)
41        .map_err(|e| CoreError::serde("Failed to serialize JSON config", e.to_string()))?;
42    bytes.push(b'\n');
43    ito_common::io::write_atomic_std(path, bytes)
44        .map_err(|e| CoreError::io(format!("Failed to write config to {}", path.display()), e))?;
45    Ok(())
46}
47
48/// Parse a CLI argument as a JSON value, falling back to a string if parsing fails.
49///
50/// If `force_string` is true, always returns a JSON string without attempting to parse.
51pub fn parse_json_value_arg(raw: &str, force_string: bool) -> serde_json::Value {
52    if force_string {
53        return serde_json::Value::String(raw.to_string());
54    }
55    match serde_json::from_str::<serde_json::Value>(raw) {
56        Ok(v) => v,
57        Err(_) => serde_json::Value::String(raw.to_string()),
58    }
59}
60
61/// Split a dot-delimited config key path into parts, trimming and filtering empty segments.
62pub fn json_split_path(key: &str) -> Vec<&str> {
63    let mut out: Vec<&str> = Vec::new();
64    for part in key.split('.') {
65        let part = part.trim();
66        if part.is_empty() {
67            continue;
68        }
69        out.push(part);
70    }
71    out
72}
73
74/// Navigate a JSON object by a slice of path parts, returning the value if found.
75pub fn json_get_path<'a>(
76    root: &'a serde_json::Value,
77    parts: &[&str],
78) -> Option<&'a serde_json::Value> {
79    let mut cur = root;
80    for p in parts {
81        let serde_json::Value::Object(map) = cur else {
82            return None;
83        };
84        let next = map.get(*p)?;
85        cur = next;
86    }
87    Some(cur)
88}
89
90/// Set a value at a dot-delimited path in a JSON object, creating intermediate objects as needed.
91///
92/// # Errors
93///
94/// Returns [`CoreError::Validation`] if the path is empty or if setting the path fails.
95#[allow(clippy::match_like_matches_macro)]
96pub fn json_set_path(
97    root: &mut serde_json::Value,
98    parts: &[&str],
99    value: serde_json::Value,
100) -> CoreResult<()> {
101    if parts.is_empty() {
102        return Err(CoreError::validation("Invalid empty path"));
103    }
104
105    let mut cur = root;
106    for (i, key) in parts.iter().enumerate() {
107        let is_last = i + 1 == parts.len();
108
109        let is_object = match cur {
110            serde_json::Value::Object(_) => true,
111            _ => false,
112        };
113        if !is_object {
114            *cur = serde_json::Value::Object(serde_json::Map::new());
115        }
116
117        let serde_json::Value::Object(map) = cur else {
118            return Err(CoreError::validation("Failed to set path"));
119        };
120
121        if is_last {
122            map.insert((*key).to_string(), value);
123            return Ok(());
124        }
125
126        let needs_object = match map.get(*key) {
127            Some(serde_json::Value::Object(_)) => false,
128            Some(_) => true,
129            None => true,
130        };
131        if needs_object {
132            map.insert(
133                (*key).to_string(),
134                serde_json::Value::Object(serde_json::Map::new()),
135            );
136        }
137
138        let Some(next) = map.get_mut(*key) else {
139            return Err(CoreError::validation("Failed to set path"));
140        };
141        cur = next;
142    }
143
144    Ok(())
145}
146
147/// Validate a config value for known keys that require enum values.
148///
149/// Returns `Ok(())` if the key is not constrained or the value is valid.
150/// Returns `Err` with a descriptive message if the value is invalid.
151///
152/// # Errors
153///
154/// Returns [`CoreError::Validation`] if the value does not match the allowed enum values.
155pub fn validate_config_value(parts: &[&str], value: &serde_json::Value) -> CoreResult<()> {
156    let path = parts.join(".");
157    match path.as_str() {
158        "worktrees.strategy" => {
159            let Some(s) = value.as_str() else {
160                return Err(CoreError::validation(format!(
161                    "Key '{}' requires a string value. Valid values: {}",
162                    path,
163                    WorktreeStrategy::ALL.join(", ")
164                )));
165            };
166            if WorktreeStrategy::parse_value(s).is_none() {
167                return Err(CoreError::validation(format!(
168                    "Invalid value '{}' for key '{}'. Valid values: {}",
169                    s,
170                    path,
171                    WorktreeStrategy::ALL.join(", ")
172                )));
173            }
174        }
175        "worktrees.apply.integration_mode" => {
176            let Some(s) = value.as_str() else {
177                return Err(CoreError::validation(format!(
178                    "Key '{}' requires a string value. Valid values: {}",
179                    path,
180                    IntegrationMode::ALL.join(", ")
181                )));
182            };
183            if IntegrationMode::parse_value(s).is_none() {
184                return Err(CoreError::validation(format!(
185                    "Invalid value '{}' for key '{}'. Valid values: {}",
186                    s,
187                    path,
188                    IntegrationMode::ALL.join(", ")
189                )));
190            }
191        }
192        _ => {}
193    }
194    Ok(())
195}
196
197/// Validate that a worktree strategy string is one of the supported values.
198///
199/// Returns `true` if valid, `false` otherwise.
200pub fn is_valid_worktree_strategy(s: &str) -> bool {
201    WorktreeStrategy::parse_value(s).is_some()
202}
203
204/// Validate that an integration mode string is one of the supported values.
205///
206/// Returns `true` if valid, `false` otherwise.
207pub fn is_valid_integration_mode(s: &str) -> bool {
208    IntegrationMode::parse_value(s).is_some()
209}
210
211#[derive(Debug, Clone, PartialEq, Eq)]
212/// Resolved defaults used when rendering worktree-aware templates.
213pub struct WorktreeTemplateDefaults {
214    /// Worktree strategy (e.g., `checkout_subdir`).
215    pub strategy: String,
216    /// Directory name used by the strategy layout.
217    pub layout_dir_name: String,
218    /// Integration mode for applying changes.
219    pub integration_mode: String,
220    /// Default branch name.
221    pub default_branch: String,
222}
223
224/// Resolve effective worktree defaults from cascading project configuration.
225///
226/// Falls back to built-in defaults when keys are not configured.
227pub fn resolve_worktree_template_defaults(
228    target_path: &Path,
229    ctx: &ConfigContext,
230) -> WorktreeTemplateDefaults {
231    let ito_path = ito_config::ito_dir::get_ito_path(target_path, ctx);
232    let merged = load_cascading_project_config(target_path, &ito_path, ctx).merged;
233
234    let mut defaults = WorktreeTemplateDefaults {
235        strategy: "checkout_subdir".to_string(),
236        layout_dir_name: "ito-worktrees".to_string(),
237        integration_mode: "commit_pr".to_string(),
238        default_branch: "main".to_string(),
239    };
240
241    if let Some(wt) = merged.get("worktrees") {
242        if let Some(v) = wt.get("strategy").and_then(|v| v.as_str())
243            && !v.is_empty()
244        {
245            defaults.strategy = v.to_string();
246        }
247
248        if let Some(v) = wt.get("default_branch").and_then(|v| v.as_str())
249            && !v.is_empty()
250        {
251            defaults.default_branch = v.to_string();
252        }
253
254        if let Some(layout) = wt.get("layout")
255            && let Some(v) = layout.get("dir_name").and_then(|v| v.as_str())
256            && !v.is_empty()
257        {
258            defaults.layout_dir_name = v.to_string();
259        }
260
261        if let Some(apply) = wt.get("apply")
262            && let Some(v) = apply.get("integration_mode").and_then(|v| v.as_str())
263            && !v.is_empty()
264        {
265            defaults.integration_mode = v.to_string();
266        }
267    }
268
269    defaults
270}
271
272/// Remove a key at a dot-delimited path in a JSON object.
273///
274/// Returns `true` if a key was removed, `false` if the path didn't exist.
275///
276/// # Errors
277///
278/// Returns [`CoreError::Validation`] if the path is empty.
279pub fn json_unset_path(root: &mut serde_json::Value, parts: &[&str]) -> CoreResult<bool> {
280    if parts.is_empty() {
281        return Err(CoreError::validation("Invalid empty path"));
282    }
283
284    let mut cur = root;
285    for (i, p) in parts.iter().enumerate() {
286        let is_last = i + 1 == parts.len();
287        let serde_json::Value::Object(map) = cur else {
288            return Ok(false);
289        };
290
291        if is_last {
292            return Ok(map.remove(*p).is_some());
293        }
294
295        let Some(next) = map.get_mut(*p) else {
296            return Ok(false);
297        };
298        cur = next;
299    }
300
301    Ok(false)
302}
303
304#[cfg(test)]
305mod tests {
306    use super::*;
307    use serde_json::json;
308
309    #[test]
310    fn validate_config_value_accepts_valid_strategy() {
311        let parts = ["worktrees", "strategy"];
312        let value = json!("checkout_subdir");
313        assert!(validate_config_value(&parts, &value).is_ok());
314
315        let value = json!("checkout_siblings");
316        assert!(validate_config_value(&parts, &value).is_ok());
317
318        let value = json!("bare_control_siblings");
319        assert!(validate_config_value(&parts, &value).is_ok());
320    }
321
322    #[test]
323    fn validate_config_value_rejects_invalid_strategy() {
324        let parts = ["worktrees", "strategy"];
325        let value = json!("custom_layout");
326        let err = validate_config_value(&parts, &value).unwrap_err();
327        let msg = err.to_string();
328        assert!(msg.contains("Invalid value"));
329        assert!(msg.contains("custom_layout"));
330    }
331
332    #[test]
333    fn validate_config_value_rejects_non_string_strategy() {
334        let parts = ["worktrees", "strategy"];
335        let value = json!(42);
336        let err = validate_config_value(&parts, &value).unwrap_err();
337        let msg = err.to_string();
338        assert!(msg.contains("requires a string value"));
339    }
340
341    #[test]
342    fn validate_config_value_accepts_valid_integration_mode() {
343        let parts = ["worktrees", "apply", "integration_mode"];
344        let value = json!("commit_pr");
345        assert!(validate_config_value(&parts, &value).is_ok());
346
347        let value = json!("merge_parent");
348        assert!(validate_config_value(&parts, &value).is_ok());
349    }
350
351    #[test]
352    fn validate_config_value_rejects_invalid_integration_mode() {
353        let parts = ["worktrees", "apply", "integration_mode"];
354        let value = json!("squash_merge");
355        let err = validate_config_value(&parts, &value).unwrap_err();
356        let msg = err.to_string();
357        assert!(msg.contains("Invalid value"));
358        assert!(msg.contains("squash_merge"));
359    }
360
361    #[test]
362    fn validate_config_value_accepts_unknown_keys() {
363        let parts = ["worktrees", "enabled"];
364        let value = json!(true);
365        assert!(validate_config_value(&parts, &value).is_ok());
366
367        let parts = ["some", "other", "key"];
368        let value = json!("anything");
369        assert!(validate_config_value(&parts, &value).is_ok());
370    }
371
372    #[test]
373    fn is_valid_worktree_strategy_checks_correctly() {
374        assert!(is_valid_worktree_strategy("checkout_subdir"));
375        assert!(is_valid_worktree_strategy("checkout_siblings"));
376        assert!(is_valid_worktree_strategy("bare_control_siblings"));
377        assert!(!is_valid_worktree_strategy("custom"));
378        assert!(!is_valid_worktree_strategy(""));
379    }
380
381    #[test]
382    fn is_valid_integration_mode_checks_correctly() {
383        assert!(is_valid_integration_mode("commit_pr"));
384        assert!(is_valid_integration_mode("merge_parent"));
385        assert!(!is_valid_integration_mode("squash"));
386        assert!(!is_valid_integration_mode(""));
387    }
388
389    #[test]
390    fn resolve_worktree_template_defaults_uses_defaults_when_missing() {
391        let project = tempfile::tempdir().expect("tempdir should succeed");
392        let ctx = ConfigContext {
393            project_dir: Some(project.path().to_path_buf()),
394            ..Default::default()
395        };
396
397        let resolved = resolve_worktree_template_defaults(project.path(), &ctx);
398        assert_eq!(
399            resolved,
400            WorktreeTemplateDefaults {
401                strategy: "checkout_subdir".to_string(),
402                layout_dir_name: "ito-worktrees".to_string(),
403                integration_mode: "commit_pr".to_string(),
404                default_branch: "main".to_string(),
405            }
406        );
407    }
408
409    #[test]
410    fn resolve_worktree_template_defaults_reads_overrides() {
411        let project = tempfile::tempdir().expect("tempdir should succeed");
412        let ito_dir = project.path().join(".ito");
413        std::fs::create_dir_all(&ito_dir).expect("create .ito should succeed");
414        std::fs::write(
415            ito_dir.join("config.json"),
416            r#"{
417  "worktrees": {
418    "strategy": "bare_control_siblings",
419    "default_branch": "develop",
420    "layout": { "dir_name": "wt" },
421    "apply": { "integration_mode": "merge_parent" }
422  }
423}
424"#,
425        )
426        .expect("write config should succeed");
427
428        let ctx = ConfigContext {
429            project_dir: Some(project.path().to_path_buf()),
430            ..Default::default()
431        };
432
433        let resolved = resolve_worktree_template_defaults(project.path(), &ctx);
434        assert_eq!(
435            resolved,
436            WorktreeTemplateDefaults {
437                strategy: "bare_control_siblings".to_string(),
438                layout_dir_name: "wt".to_string(),
439                integration_mode: "merge_parent".to_string(),
440                default_branch: "develop".to_string(),
441            }
442        );
443    }
444}