config_rw 1.0.0

配置文件读取与写入
Documentation
use super::{get_arg, set_arg, save_config, init_config};
use super::{get_string, get_i64, get_bool};
use super::{set_string, set_i64, set_bool};
use serde_json::Value;

/// 演示配置管理器基本功能
#[test]
pub fn demo_config_manager() -> Result<(), Box<dyn std::error::Error>> {
    println!("=== 配置管理器演示 ===");
    
    // 1. 初始化配置(已在 main 中初始化)
    println!("✓ 配置管理器初始化成功");
    
    // 2. 读取配置
    let app_name = get_string("app.name").unwrap_or("未知应用".to_string());
    let debug_mode = get_bool("app.debug").unwrap_or(false);
    let server_port = get_i64("network.server_port").unwrap_or(8080);
    
    println!("✓ 读取配置:");
    println!("  - 应用名称: {}", app_name);
    println!("  - 调试模式: {}", debug_mode);
    println!("  - 服务器端口: {}", server_port);
    
    // 3. 使用 get_arg 读取原始 JSON 值
    let host_value: Value = get_arg("database.host");
    println!("  - 数据库主机: {}", host_value);
    
    // 4. 修改配置
    set_bool("app.debug", true)?;
    
    // 版本号加1
    let version = get_string("app.version").unwrap_or("1.0.0".to_string());
    let version_num = version.split(".").nth(2).unwrap_or("1").parse::<i64>().unwrap_or(1);
    set_string("app.version", format!("1.0.{}", version_num + 1))?;
    
    println!("✓ 修改配置:");
    println!("  - 启用调试模式");
    println!("  - 更新应用版本");
    
    // 5. 验证修改
    let new_debug = get_bool("app.debug").unwrap();
    let new_version = get_string("app.version").unwrap();
    
    println!("✓ 验证修改:");
    println!("  - 调试模式: {}", new_debug);
    println!("  - 应用版本: {}", new_version);
    
    // 6. 保存配置
    save_config()?;
    println!("✓ 配置已保存到文件,注释和格式得到保留");
    
    Ok(())
}

/// 演示跨模块配置访问
pub fn demo_cross_module_access() -> Result<(), Box<dyn std::error::Error>> {
    println!("\n=== 跨模块配置访问演示 ===");
    
    // 模拟不同模块中的函数
    module_a()?;
    module_b()?;
    
    Ok(())
}

/// 模拟模块 A 中的函数
fn module_a() -> Result<(), Box<dyn std::error::Error>> {
    println!("模块 A 函数:");
    
    let port = get_i64("network.server_port").unwrap_or(8080);
    println!("  - 读取端口: {}", port);
    
    set_i64("network.max_connections", 200)?;
    println!("  - 设置最大连接数: 200");
    
    Ok(())
}

/// 模拟模块 B 中的函数
fn module_b() -> Result<(), Box<dyn std::error::Error>> {
    println!("模块 B 函数:");
    
    let port = get_i64("network.server_port").unwrap_or(8080);
    let max_conn = get_i64("network.max_connections").unwrap_or(100);
    
    println!("  - 读取端口: {}", port);
    println!("  - 读取最大连接数: {}", max_conn);
    
    Ok(())
}

/// 演示复杂配置操作
pub fn demo_complex_config() -> Result<(), Box<dyn std::error::Error>> {
    println!("\n=== 复杂配置操作演示 ===");
    
    // 设置嵌套配置
    set_string("new_section.sub_section.key", "nested_value".to_string())?;
    println!("✓ 设置嵌套配置: new_section.sub_section.key = nested_value");
    
    // 设置数组配置
    let array_value = Value::Array(vec![
        Value::String("item1".to_string()),
        Value::String("item2".to_string()),
        Value::Number(serde_json::Number::from(42)),
    ]);
    set_arg("complex.array", array_value)?;
    println!("✓ 设置数组配置");
    
    // 读取复杂配置
    let nested_value = get_string("new_section.sub_section.key").unwrap();
    let array_config = get_arg("complex.array");
    
    println!("✓ 读取复杂配置:");
    println!("  - 嵌套值: {}", nested_value);
    println!("  - 数组配置: {}", array_config);
    
    save_config()?;
    println!("✓ 复杂配置已保存");
    
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use tempfile::tempdir;
    
    #[test]
    fn test_config_demo() {
        let temp_dir = tempdir().unwrap();
        let config_path = temp_dir.path().join("demo_config_unique.toml");
        
        // 创建示例配置文件
        let config_content = r#"
# 演示配置文件
[app]
name = "tick_rhino"
debug = false
version = "1.0.0"

[database]
host = "localhost"
port = 5432

[network]
server_port = 8080
max_connections = 100
"#;
        std::fs::write(&config_path, config_content).unwrap();
        
        // 初始化配置
        super::init_config(&config_path).unwrap();
        
        // 测试基本读取
        assert_eq!(get_string("app.name"), Some("tick_rhino".to_string()));
        assert_eq!(get_bool("app.debug"), Some(false));
        assert_eq!(get_i64("network.server_port"), Some(8080));
        
        // 测试修改
        set_bool("app.debug", true).unwrap();
        set_i64("network.server_port", 9090).unwrap();
        
        // 验证修改
        assert_eq!(get_bool("app.debug"), Some(true));
        assert_eq!(get_i64("network.server_port"), Some(9090));
        
        // 测试保存
        save_config().unwrap();
        
        // 等待一下确保文件写入完成
        std::thread::sleep(std::time::Duration::from_millis(50));
        
        // 验证文件已更新
        let saved_content = std::fs::read_to_string(&config_path).unwrap();
        println!("保存的配置内容:\n{}", saved_content);
        
        // 验证修改的值存在(不依赖具体的TOML格式)
        assert!(saved_content.contains("true") || saved_content.contains("= true"));
        assert!(saved_content.contains("9090"));
        
        println!("✓ 配置管理器演示测试通过");
    }
}