codetree 0.2.0

AI-native version control system for autonomous agents
Documentation
use crate::error::{Context, Result};
use std::path::PathBuf;

/// Config subcommands.
pub enum ConfigAction {
    /// Get a config value by dotted key (e.g., "git.base_branch").
    Get(String),
    /// Set a config value by dotted key.
    Set(String, String),
    /// List all config values.
    List,
}

/// Handle `codetree config <subcommand>`.
pub async fn config_command(action: ConfigAction) -> Result<()> {
    let config_path = std::env::current_dir()
        .context("Failed to get current directory")?
        .join(".codetree")
        .join("config.toml");

    match action {
        ConfigAction::Get(key) => {
            let content = read_config_text(&config_path)?;
            if let Some(value) = find_config_value(&content, &key) {
                println!("{}", value);
            } else {
                println!("(not set)");
            }
        }
        ConfigAction::Set(key, value) => {
            let content = read_config_text(&config_path)?;
            let new_content = set_config_value(&content, &key, &value);
            crate::atomic::write_atomic(&config_path, new_content.as_bytes())?;
            println!("Set {} = {}", key, value);
        }
        ConfigAction::List => {
            let content = read_config_text(&config_path)?;
            print!("{}", content);
        }
    }

    Ok(())
}

fn read_config_text(path: &PathBuf) -> Result<String> {
    if path.exists() {
        Ok(std::fs::read_to_string(path)?)
    } else {
        Ok(String::new())
    }
}

/// Find a config value by dotted key in TOML text.
/// Supports simple `[section]` + `key = value` format.
fn find_config_value(content: &str, key: &str) -> Option<String> {
    let parts: Vec<&str> = key.split('.').collect();
    if parts.len() < 2 {
        return None;
    }
    let section = parts[0];
    let field = parts[1];

    let mut in_section = false;
    for line in content.lines() {
        let trimmed = line.trim();
        if trimmed.starts_with('[') && trimmed.ends_with(']') {
            in_section = trimmed == format!("[{}]", section);
            continue;
        }
        if in_section
            && let Some((k, v)) = trimmed.split_once('=')
            && k.trim() == field
        {
            return Some(v.trim().trim_matches('"').to_string());
        }
    }
    None
}

/// Set a config value by dotted key in TOML text.
/// Creates the section if it doesn't exist.
fn set_config_value(content: &str, key: &str, value: &str) -> String {
    let parts: Vec<&str> = key.split('.').collect();
    if parts.len() < 2 {
        return content.to_string();
    }
    let section = parts[0];
    let field = parts[1];

    let mut lines: Vec<String> = content.lines().map(|s| s.to_string()).collect();
    let mut in_section = false;
    let mut section_start = None;
    let mut found = false;

    // Try to find and update existing key.
    for (i, line) in lines.clone().iter().enumerate() {
        let trimmed = line.trim();
        if trimmed.starts_with('[') && trimmed.ends_with(']') {
            if in_section && !found {
                // We were in the right section but didn't find the key.
                // Insert before this section header.
                lines.insert(i, format!("{} = \"{}\"", field, value));
                found = true;
                break;
            }
            in_section = trimmed == format!("[{}]", section);
            if in_section {
                section_start = Some(i);
            }
            continue;
        }
        if in_section
            && let Some((k, _)) = trimmed.split_once('=')
            && k.trim() == field
        {
            lines[i] = format!("{} = \"{}\"", field, value);
            found = true;
            break;
        }
    }

    if !found {
        if in_section {
            // We were in the section but reached the end without finding the key.
            lines.push(format!("{} = \"{}\"", field, value));
        } else {
            // Section doesn't exist — add it.
            lines.push(String::new());
            lines.push(format!("[{}]", section));
            lines.push(format!("{} = \"{}\"", field, value));
        }
    }

    let _ = section_start; // suppress unused warning
    lines.join("\n") + "\n"
}