config_rw 1.0.5

配置文件读取与写入
Documentation

Config RW - Unified Configuration Management Library

统一配置管理库 - 让配置读写变得简单而强大

🚀 Features | 特性

Multi-source Configuration Priority | 多数据源配置优先级
Command line arguments > Configuration files > Environment variables
命令行参数 > 配置文件 > 环境变量

Type-safe Configuration Access | 类型安全的配置访问
Built-in support for string, integer, float, boolean, and complex JSON types
内置支持字符串、整数、浮点数、布尔值和复杂 JSON 类型

Auto-save and Hot Reload | 自动保存和热重载
Configuration changes are automatically saved to files
配置更改自动保存到文件中

Cross-module Global State | 跨模块全局状态
Share configuration seamlessly across different modules
在不同模块间无缝共享配置

Source Protection | 来源保护
Prevent accidental overwriting of command line and environment variables
防止意外覆盖命令行参数和环境变量

📦 Installation | 安装

Add this to your Cargo.toml:
将以下内容添加到你的 Cargo.toml 文件中:

[dependencies]

config_rw = "1"

🎯 Quick Start | 快速开始

Basic Usage | 基本使用

use config_rw::{init_config, get_string, get_i64, set_string, save_config};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Initialize configuration manager
    // 初始化配置管理器
    init_config("config.toml")?;
    
    // Read configuration values
    // 读取配置值
    let host = get_string("database.host").unwrap_or("localhost".to_string());
    let port = get_i64("database.port").unwrap_or(5432);
    
    println!("Connecting to {}:{}", host, port);
    println!("连接到 {}:{}", host, port);
    
    // Modify configuration
    // 修改配置
    set_string("database.host", "127.0.0.1".to_string())?;
    
    // Save changes to file
    // 保存更改到文件
    save_config()?;
    
    Ok(())
}

🌟 Advanced Examples | 高级示例

1. Configuration Priority Demo | 配置优先级演示

Demonstrates how different sources override each other
演示不同数据源如何相互覆盖

use config_rw::{init_config, get_string, get_i64};

fn priority_demo() -> Result<(), Box<dyn std::error::Error>> {
    init_config("config.toml")?;
    
    // Priority order: CLI args > config file > env vars
    // 优先级顺序:命令行参数 > 配置文件 > 环境变量
    
    // If you run: cargo run -- database.host=production.db
    // 如果你运行:cargo run -- database.host=production.db
    let host = get_string("database.host").unwrap_or("localhost".to_string());
    println!("Database host: {}", host); // Will show "production.db"
    println!("数据库主机:{}", host);      // 将显示 "production.db"
    
    Ok(())
}

2. Cross-Module Configuration | 跨模块配置

Share configuration state across different modules seamlessly
在不同模块间无缝共享配置状态

// main.rs
use config_rw::{init_config, set_i64};

mod database;
mod server;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    init_config("config.toml")?;
    
    // Set configuration in main
    // 在主模块中设置配置
    set_i64("server.port", 8080)?;
    
    // Other modules can access the same configuration
    // 其他模块可以访问相同的配置
    database::connect()?;
    server::start()?;
    
    Ok(())
}

// database.rs
use config_rw::get_string;

pub fn connect() -> Result<(), Box<dyn std::error::Error>> {
    // Access global configuration without initialization
    // 无需初始化即可访问全局配置
    let host = get_string("database.host").unwrap_or("localhost".to_string());
    println!("Database connecting to: {}", host);
    println!("数据库连接到:{}", host);
    Ok(())
}

// server.rs  
use config_rw::get_i64;

pub fn start() -> Result<(), Box<dyn std::error::Error>> {
    // Access the same global state
    // 访问相同的全局状态
    let port = get_i64("server.port").unwrap_or(3000);
    println!("Server starting on port: {}", port);
    println!("服务器启动端口:{}", port);
    Ok(())
}

3. Complex Data Types | 复杂数据类型

Handle arrays, objects, and nested configurations with ease
轻松处理数组、对象和嵌套配置

use config_rw::{init_config, get_arg, set_arg, save_config};
use serde_json::{Value, Map};

fn complex_config_demo() -> Result<(), Box<dyn std::error::Error>> {
    init_config("config.toml")?;
    
    // Set array configuration
    // 设置数组配置
    let servers = Value::Array(vec![
        Value::String("server1.com".to_string()),
        Value::String("server2.com".to_string()),
        Value::String("server3.com".to_string()),
    ]);
    set_arg("cluster.servers", servers)?;
    
    // Set object configuration
    // 设置对象配置
    let mut db_config = Map::new();
    db_config.insert("host".to_string(), Value::String("localhost".to_string()));
    db_config.insert("port".to_string(), Value::Number(5432.into()));
    db_config.insert("ssl".to_string(), Value::Bool(true));
    set_arg("database", Value::Object(db_config))?;
    
    // Read complex configurations
    // 读取复杂配置
    let servers = get_arg("cluster.servers");
    if let Value::Array(server_list) = servers {
        println!("Available servers: {:?}", server_list);
        println!("可用服务器:{:?}", server_list);
    }
    
    save_config()?;
    Ok(())
}

4. Auto-save and Source Protection | 自动保存和来源保护

Automatic configuration persistence with intelligent source protection
自动配置持久化和智能来源保护

use config_rw::{init_config, get_string, set_string, save_config};

fn auto_save_demo() -> Result<(), Box<dyn std::error::Error>> {
    init_config("config.toml")?;
    
    // Configuration changes are automatically saved
    // 配置更改会自动保存
    set_string("app.theme", "dark".to_string())?;
    set_string("app.language", "zh-CN".to_string())?;
    
    // Verify changes are persisted
    // 验证更改已持久化
    let theme = get_string("app.theme").unwrap();
    println!("Current theme: {}", theme);
    println!("当前主题:{}", theme);
    
    // Source protection: command line args cannot be overwritten
    // 来源保护:命令行参数无法被覆盖
    // If started with: cargo run -- app.mode=production
    // 如果启动时使用:cargo run -- app.mode=production
    set_string("app.mode", "development".to_string())?; // This won't override CLI arg
    
    let mode = get_string("app.mode").unwrap();
    println!("App mode: {} (CLI protected)", mode);
    println!("应用模式:{}(命令行保护)", mode);
    
    Ok(())
}

🔧 Configuration File Format | 配置文件格式

TOML format with support for nested structures
支持嵌套结构的 TOML 格式

# config.toml

[app]

name = "My Application"

version = "1.0.0"

debug = false



[app.features]

cache_enabled = true

logging = true



[database]

host = "localhost"

port = 5432

username = "admin"

password = "secret"



[server]

port = 8080

workers = 4



[[cluster.servers]]

host = "server1.com"

port = 8080



[[cluster.servers]]

host = "server2.com"

port = 8080

🎮 Command Line Usage | 命令行使用

Override any configuration value from command line
从命令行覆盖任何配置值

# Basic key-value pairs

# 基本键值对

cargo run -- database.host=prod.db server.port=9000


# Complex nested keys

# 复杂嵌套键

cargo run -- app.features.cache_enabled=false database.timeout=30


# Boolean and numeric values

# 布尔值和数值

cargo run -- app.debug=true server.workers=8

🌍 Environment Variables | 环境变量

Automatic environment variable mapping
自动环境变量映射

# Set environment variables (keys are converted to uppercase with underscores)

# 设置环境变量(键转换为大写并使用下划线)

export DATABASE_HOST=prod.db

export SERVER_PORT=9000

export APP_DEBUG=true


# Run your application

# 运行你的应用程序

cargo run

📋 API Reference | API 参考

Initialization | 初始化

// Initialize with configuration file
// 使用配置文件初始化
init_config("config.toml")?;

// Initialize with file path only (no CLI args parsing)
// 仅使用文件路径初始化(不解析命令行参数)
init_config_file_only("config.toml")?;

Reading Values | 读取值

// Type-safe getters
// 类型安全的获取器
let name: Option<String> = get_string("app.name");
let port: Option<i64> = get_i64("server.port");
let timeout: Option<f64> = get_f64("database.timeout");
let debug: Option<bool> = get_bool("app.debug");

// Raw JSON value getter
// 原始 JSON 值获取器
let raw_value: Value = get_arg("complex.config");

Writing Values | 写入值

// Type-safe setters
// 类型安全的设置器
set_string("app.name", "New Name".to_string())?;
set_i64("server.port", 8080)?;
set_f64("database.timeout", 30.5)?;
set_bool("app.debug", true)?;

// Raw JSON value setter
// 原始 JSON 值设置器
set_arg("complex.config", json_value)?;

// Save changes to file
// 保存更改到文件
save_config()?;

🆚 Comparison with Other Libraries | 与其他库的对比

Feature config_rw config figment confy
Multi-source Priority ✅ CLI > File > Env
Runtime Modification
Auto-save
Type Safety
Complex Types ✅ JSON ✅ Serde ✅ Serde ✅ Serde
Source Protection
Global State

多数据源优先级 | ✅ 命令行 > 文件 > 环境变量 | ❌ | ✅ | ❌
运行时修改 | ✅ | ❌ | ❌ | ✅
自动保存 | ✅ | ❌ | ❌ | ✅
类型安全 | ✅ | ✅ | ✅ | ✅
复杂类型 | ✅ JSON | ✅ Serde | ✅ Serde | ✅ Serde
来源保护 | ✅ | ❌ | ❌ | ❌
全局状态 | ✅ | ❌ | ❌ | ❌

🧪 Testing | 测试

Run the comprehensive test suite
运行综合测试套件

# Run all tests with detailed output

# 运行所有测试并显示详细输出

powershell -ExecutionPolicy Bypass -File run_all_tests.ps1


# Run individual test categories

# 运行单独的测试类别

cargo test --lib                    # Library unit tests | 库单元测试

cargo test test_demo_priority       # Priority functionality | 优先级功能

cargo test test_demo_auto_save      # Auto-save functionality | 自动保存功能

📄 License | 许可证

MIT/Apache-2.0 dual licensed
MIT/Apache-2.0 双重许可

See LICENSE for more details.
详见 LICENSE 文件。

🤝 Contributing | 贡献

Contributions are welcome! Please feel free to submit a Pull Request.
欢迎贡献!请随时提交 Pull Request。

  1. Fork the repository | Fork 仓库
  2. Create your feature branch | 创建你的功能分支 (git checkout -b feature/AmazingFeature)
  3. Commit your changes | 提交你的更改 (git commit -m 'Add some AmazingFeature')
  4. Push to the branch | 推送到分支 (git push origin feature/AmazingFeature)
  5. Open a Pull Request | 打开 Pull Request

📧 Contact | 联系方式

Email | 邮箱: guoyumail@qq.com

Project Link | 项目链接: https://github.com/your-username/config_rw


If this project helps you, please consider giving it a star!
如果这个项目对你有帮助,请考虑给它一个星标!