fyi-core 0.1.0

Core types and traits for fyi
Documentation
//! Settings installation logic.
//!
//! This module handles writing hooks configuration to settings files,
//! supporting both JSON and TOML formats. It includes logic for merging
//! configurations and managing OTel environment variables.

use std::path::Path;

use crate::{ConfigFormat, FrameworkAdapter};

use super::config::json_to_toml_string;
use super::options::{InitError, InstallSettingsOptions};
use super::otel::OTEL_ENV_KEYS;

/// Install hooks configuration to a settings file.
///
/// This function merges the new hooks configuration with any existing settings
/// and writes the result to the specified path.
///
/// # Arguments
/// * `adapter` - The framework adapter.
/// * `settings_path` - Path where settings should be written.
/// * `new_hooks` - The hooks configuration to install.
/// * `options` - Additional options for OTel configuration.
pub fn install_settings(
    adapter: &dyn FrameworkAdapter,
    settings_path: &Path,
    new_hooks: &serde_json::Value,
    options: &InstallSettingsOptions,
) -> Result<(), InitError> {
    // Create parent directory if needed
    if let Some(parent) = settings_path.parent() {
        std::fs::create_dir_all(parent)?;
    }

    match adapter.config_format() {
        ConfigFormat::Json => install_json_settings(adapter, settings_path, new_hooks, options),
        ConfigFormat::Toml => {
            install_toml_settings(adapter, settings_path, new_hooks, options.remove_otel)
        }
    }
}

/// Install settings to a JSON configuration file.
fn install_json_settings(
    adapter: &dyn FrameworkAdapter,
    settings_path: &Path,
    new_hooks: &serde_json::Value,
    options: &InstallSettingsOptions,
) -> Result<(), InitError> {
    // Read existing settings or start fresh
    let existing: Option<serde_json::Value> = if settings_path.exists() {
        let contents = std::fs::read_to_string(settings_path)?;
        serde_json::from_str(&contents).ok()
    } else {
        None
    };

    // Use adapter to merge hooks
    let mut settings = adapter.merge_config(new_hooks.clone(), existing);

    // Handle OTel env vars for JSON configs.
    // Note: JSON configs (like Claude Code) store OTel settings as individual env vars,
    // so we remove them one by one. TOML configs (like Codex) use an [otel] section instead.
    if options.remove_otel {
        // Remove OTel-related env vars one by one
        if let Some(existing_env) = settings.get_mut("env")
            && let Some(env_obj) = existing_env.as_object_mut()
        {
            for key in OTEL_ENV_KEYS {
                env_obj.remove(*key);
            }
        }
    } else if let Some(new_env) = &options.otel_env {
        // Merge env if otel is enabled
        if let Some(existing_env) = settings.get_mut("env") {
            if let (Some(existing_obj), Some(new_obj)) =
                (existing_env.as_object_mut(), new_env.as_object())
            {
                for (key, value) in new_obj {
                    existing_obj.insert(key.clone(), value.clone());
                }
            }
        } else {
            settings["env"] = new_env.clone();
        }
    }

    // Write back as JSON
    let output = serde_json::to_string_pretty(&settings)
        .map_err(|e| InitError::Config(format!("failed to serialize JSON: {e}")))?;
    std::fs::write(settings_path, output)?;

    Ok(())
}

/// Install settings to a TOML configuration file.
fn install_toml_settings(
    adapter: &dyn FrameworkAdapter,
    settings_path: &Path,
    new_config: &serde_json::Value,
    remove_otel: bool,
) -> Result<(), InitError> {
    // Read existing TOML settings or start fresh
    let existing: Option<serde_json::Value> = if settings_path.exists() {
        let contents = std::fs::read_to_string(settings_path)?;
        // Parse TOML to a generic toml::Value, then convert to serde_json::Value
        // If parsing fails, start fresh (existing file may be corrupted or empty)
        toml::from_str::<toml::Value>(&contents)
            .ok()
            .and_then(|v| serde_json::to_value(v).ok())
    } else {
        None
    };

    // Use adapter to merge config
    let mut settings = adapter.merge_config(new_config.clone(), existing);

    // Handle --no-otel flag for TOML configs.
    // Note: TOML configs (like Codex) store OTel settings in an [otel] section,
    // so we remove the entire section. JSON configs remove individual env vars instead.
    if remove_otel && let Some(obj) = settings.as_object_mut() {
        obj.remove("otel");
    }

    // Convert serde_json::Value to toml::Value and write as TOML
    let toml_str = json_to_toml_string(&settings)?;
    std::fs::write(settings_path, toml_str)?;

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::init::otel::generate_otel_env;
    use std::fs;
    use tempfile::TempDir;

    #[test]
    fn test_install_json_settings_new_file() -> Result<(), String> {
        let temp_dir = TempDir::new().map_err(|e| e.to_string())?;
        let settings_path = temp_dir.path().join("settings.json");
        let adapter = crate::ClaudeAdapter;

        let hooks = serde_json::json!({
            "hooks": {
                "SessionStart": ["fyi log SessionStart"]
            }
        });

        install_settings(
            &adapter,
            &settings_path,
            &hooks,
            &InstallSettingsOptions::default(),
        )
        .map_err(|e| e.to_string())?;

        assert!(settings_path.exists());
        let content = fs::read_to_string(&settings_path).map_err(|e| e.to_string())?;
        let parsed: serde_json::Value =
            serde_json::from_str(&content).map_err(|e| e.to_string())?;
        assert!(parsed["hooks"]["SessionStart"].is_array());
        Ok(())
    }

    #[test]
    fn test_install_json_settings_with_otel() -> Result<(), String> {
        let temp_dir = TempDir::new().map_err(|e| e.to_string())?;
        let settings_path = temp_dir.path().join("settings.json");
        let adapter = crate::ClaudeAdapter;

        let hooks = serde_json::json!({
            "hooks": {
                "SessionStart": ["fyi log SessionStart"]
            }
        });

        install_settings(
            &adapter,
            &settings_path,
            &hooks,
            &InstallSettingsOptions {
                otel_env: Some(generate_otel_env(4318)),
                remove_otel: false,
            },
        )
        .map_err(|e| e.to_string())?;

        let content = fs::read_to_string(&settings_path).map_err(|e| e.to_string())?;
        let parsed: serde_json::Value =
            serde_json::from_str(&content).map_err(|e| e.to_string())?;
        assert_eq!(parsed["env"]["CLAUDE_CODE_ENABLE_TELEMETRY"], "1");
        Ok(())
    }

    #[test]
    fn test_install_json_settings_remove_otel() -> Result<(), String> {
        let temp_dir = TempDir::new().map_err(|e| e.to_string())?;
        let settings_path = temp_dir.path().join("settings.json");
        let adapter = crate::ClaudeAdapter;

        // First install with OTel
        let hooks = serde_json::json!({
            "hooks": {
                "SessionStart": ["fyi log SessionStart"]
            }
        });
        install_settings(
            &adapter,
            &settings_path,
            &hooks,
            &InstallSettingsOptions {
                otel_env: Some(generate_otel_env(4318)),
                remove_otel: false,
            },
        )
        .map_err(|e| e.to_string())?;

        // Verify OTel was added
        let content = fs::read_to_string(&settings_path).map_err(|e| e.to_string())?;
        let parsed: serde_json::Value =
            serde_json::from_str(&content).map_err(|e| e.to_string())?;
        assert!(parsed["env"]["CLAUDE_CODE_ENABLE_TELEMETRY"].is_string());

        // Now remove OTel
        install_settings(
            &adapter,
            &settings_path,
            &hooks,
            &InstallSettingsOptions {
                otel_env: None,
                remove_otel: true,
            },
        )
        .map_err(|e| e.to_string())?;

        // Verify OTel was removed
        let content = fs::read_to_string(&settings_path).map_err(|e| e.to_string())?;
        let parsed: serde_json::Value =
            serde_json::from_str(&content).map_err(|e| e.to_string())?;
        assert!(parsed["env"]["CLAUDE_CODE_ENABLE_TELEMETRY"].is_null());
        Ok(())
    }

    #[test]
    fn test_initialize_writes_settings_file() -> Result<(), String> {
        // Use settings_local option with a temp directory as working directory
        // so we get a predictable path like ".claude/settings.local.json"
        let temp_dir = TempDir::new().map_err(|e| e.to_string())?;
        let settings_path = temp_dir.path().join(".claude").join("settings.local.json");

        // We can't easily test initialize() with a controlled path, but we can
        // test the low-level functions that it uses. For a true integration test,
        // we'd need to change to temp_dir, which isn't ideal.
        // Instead, let's verify the key components work together:

        let adapter = crate::ClaudeAdapter;
        let config = crate::Config::default();
        let enabled_events = config.hooks.enabled_hooks();
        let hooks_json = adapter.generate_hooks_config(&enabled_events, "fyi", true, 4318);
        let otel_env = generate_otel_env(4318);

        // Create parent dir
        let parent = settings_path.parent().ok_or("no parent dir")?;
        std::fs::create_dir_all(parent).map_err(|e| e.to_string())?;

        // Install settings
        install_settings(
            &adapter,
            &settings_path,
            &hooks_json,
            &InstallSettingsOptions {
                otel_env: Some(otel_env.clone()),
                remove_otel: false,
            },
        )
        .map_err(|e| e.to_string())?;

        // Verify file was created with correct content
        assert!(settings_path.exists());
        let content = fs::read_to_string(&settings_path).map_err(|e| e.to_string())?;
        let parsed: serde_json::Value =
            serde_json::from_str(&content).map_err(|e| e.to_string())?;

        // Verify hooks are present
        assert!(parsed["hooks"]["SessionStart"].is_array());
        assert!(parsed["hooks"]["SessionEnd"].is_array());

        // Verify otel env is present
        assert_eq!(parsed["env"]["CLAUDE_CODE_ENABLE_TELEMETRY"], "1");
        assert_eq!(
            parsed["env"]["OTEL_EXPORTER_OTLP_ENDPOINT"],
            "http://127.0.0.1:4318"
        );
        Ok(())
    }
}