config_rw 1.0.5

配置文件读取与写入
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
# 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` 文件中:

```toml
[dependencies]
config_rw = "1"
```

## 🎯 Quick Start | 快速开始


### Basic Usage | 基本使用


```rust
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**  
**演示不同数据源如何相互覆盖**

```rust
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**  
**在不同模块间无缝共享配置状态**

```rust
// 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**  
**轻松处理数组、对象和嵌套配置**

```rust
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**  
**自动配置持久化和智能来源保护**

```rust
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 格式**

```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**  
**从命令行覆盖任何配置值**

```bash
# 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**  
**自动环境变量映射**

```bash
# 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 | 初始化


```rust
// 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 | 读取值


```rust
// 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 | 写入值


```rust
// 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**  
**运行综合测试套件**

```bash
# 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](LICENSE) for more details.  
详见 [LICENSE](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]https://github.com/your-username/config_rw

---

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