config_rw 1.0.0

配置文件读取与写入
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
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
#[macro_use]
extern crate log;

use std::path::Path;
use std::collections::HashMap;
use std::env;
use parking_lot::RwLock;
use serde_json::Value;
use toml_edit::{DocumentMut, Item, Table};
use std::sync::LazyLock as Lazy;

/// 全局配置管理器实例
static CONFIG_MANAGER: Lazy<RwLock<ConfigManager>> = Lazy::new(|| {
    RwLock::new(ConfigManager::new())
});

/// 配置管理器结构体
#[derive(Debug)]
pub struct ConfigManager {
    /// TOML 文档对象,保持原始格式和注释
    document: DocumentMut,
    /// 配置文件路径
    file_path: Option<String>,
    /// 是否已修改
    is_modified: bool,
    /// 命令行参数映射
    args_map: HashMap<String, String>,
}

impl ConfigManager {
    /// 创建新的配置管理器
    pub fn new() -> Self {
        Self {
            document: DocumentMut::new(),
            file_path: None,
            is_modified: false,
            args_map: HashMap::new(),
        }
    }

    /// 解析命令行参数
    /// 支持格式:./xx.exe arg1 arg2=2 arg3="3"
    pub fn parse_args(&mut self, args: Vec<String>) {
        self.args_map.clear();
        
        // 跳过程序名(第一个参数)
        for (index, arg) in args.iter().skip(1).enumerate() {
            if arg.contains('=') {
                // 处理 key=value 格式
                let parts: Vec<&str> = arg.splitn(2, '=').collect();
                if parts.len() == 2 {
                    let key = parts[0].trim();
                    let value = parts[1].trim();
                    // 去掉引号
                    let cleaned_value = if (value.starts_with('"') && value.ends_with('"')) ||
                                          (value.starts_with('\'') && value.ends_with('\'')) {
                        &value[1..value.len()-1]
                    } else {
                        value
                    };
                    self.args_map.insert(key.to_string(), cleaned_value.to_string());
                }
            } else {
                // 处理位置参数,使用索引作为键
                let key = format!("arg{}", index);
                self.args_map.insert(key, arg.clone());
            }
        }
        
        info!("Parsed {} command line arguments", self.args_map.len());
    }

    /// 从文件加载配置
    pub fn load_from_file<P: AsRef<Path>>(&mut self, path: P) -> Result<(), Box<dyn std::error::Error>> {
        let path = path.as_ref();
        let path_str = path.to_string_lossy().to_string();
        
        if path.exists() {
            let content = std::fs::read_to_string(path)?;
            self.document = content.parse::<DocumentMut>().map_err(|e| {
                format!("Failed to parse TOML file '{}': {}", path_str, e)
            })?;
            info!("Config loaded from file: {}", path_str);
        } else {
            // 如果文件不存在,创建空文档
            self.document = DocumentMut::new();
            info!("Config file not found, created empty config: {}", path_str);
        }
        
        self.file_path = Some(path_str);
        self.is_modified = false;
        Ok(())
    }

    /// 保存配置到文件
    pub fn save_to_file(&mut self) -> Result<(), Box<dyn std::error::Error>> {
        if let Some(ref path) = self.file_path {
            if self.is_modified {
                // 确保目录存在
                if let Some(parent) = Path::new(path).parent() {
                    std::fs::create_dir_all(parent)?;
                }
                
                std::fs::write(path, self.document.to_string())?;
                self.is_modified = false;
                info!("Config saved to file: {}", path);
            }
        } else {
            return Err("No file path specified".into());
        }
        Ok(())
    }

    /// 按优先级获取配置值:命令行参数 > 配置文件 > 环境变量
    pub fn get_value(&self, path: &str) -> Option<String> {
        // 1. 首先检查命令行参数
        if let Some(value) = self.args_map.get(path) {
            return Some(value.clone());
        }
        
        // 2. 然后检查配置文件
        if let Some(config_value) = self.get_config_value(path) {
            if let Some(string_value) = self.json_value_to_string(&config_value) {
                return Some(string_value);
            }
        }
        
        // 3. 最后检查环境变量
        if let Ok(env_value) = env::var(path.to_uppercase().replace('.', "_")) {
            return Some(env_value);
        }
        
        None
    }

    /// 从配置文件获取值
    fn get_config_value(&self, path: &str) -> Option<Value> {
        let keys: Vec<&str> = path.split('.').collect();
        let mut current = self.document.as_table();
        
        for (i, key) in keys.iter().enumerate() {
            if i == keys.len() - 1 {
                // 最后一个键,获取值
                if let Some(item) = current.get(key) {
                    return self.item_to_json_value(item);
                }
            } else {
                // 中间键,继续导航
                if let Some(Item::Table(table)) = current.get(key) {
                    current = table;
                } else {
                    return None;
                }
            }
        }
        None
    }

    /// 将 JSON 值转换为字符串
    fn json_value_to_string(&self, value: &Value) -> Option<String> {
        match value {
            Value::String(s) => Some(s.clone()),
            Value::Number(n) => Some(n.to_string()),
            Value::Bool(b) => Some(b.to_string()),
            _ => None,
        }
    }

    /// 字符串转换为 i64
    fn string_to_i64(&self, s: &str) -> Option<i64> {
        s.parse::<i64>().ok()
    }

    /// 字符串转换为 f64
    fn string_to_f64(&self, s: &str) -> Option<f64> {
        s.parse::<f64>().ok()
    }

    /// 字符串转换为 bool
    fn string_to_bool(&self, s: &str) -> Option<bool> {
        match s.to_lowercase().as_str() {
            "true" | "1" | "yes" | "on" => Some(true),
            "false" | "0" | "no" | "off" => Some(false),
            _ => None,
        }
    }

    /// 获取 i64 类型的配置值
    pub fn get_i64(&self, path: &str) -> Option<i64> {
        if let Some(value) = self.get_value(path) {
            self.string_to_i64(&value)
        } else {
            None
        }
    }

    /// 获取 f64 类型的配置值
    pub fn get_f64(&self, path: &str) -> Option<f64> {
        if let Some(value) = self.get_value(path) {
            self.string_to_f64(&value)
        } else {
            None
        }
    }

    /// 获取 bool 类型的配置值
    pub fn get_bool(&self, path: &str) -> Option<bool> {
        if let Some(value) = self.get_value(path) {
            self.string_to_bool(&value)
        } else {
            None
        }
    }

    /// 获取字符串类型的配置值
    pub fn get_string(&self, path: &str) -> Option<String> {
        self.get_value(path)
    }

    /// 按路径设置配置值(带来源检查和自动保存)
    pub fn set_value(&mut self, path: &str, value: Value) -> Result<(), Box<dyn std::error::Error>> {
        // 检查配置来源,如果来自命令行或环境变量则报错
        
        // 1. 检查是否来自命令行参数
        if self.args_map.contains_key(path) {
            return Err("当前为命令行参数, 不能保存".into());
        }
        
        // 2. 检查是否来自环境变量
        let env_key = path.to_uppercase().replace('.', "_");
        if env::var(&env_key).is_ok() {
            // 还需要确认配置文件中没有这个值
            if self.get_config_value(path).is_none() {
                return Err("当前为环境变量参数, 不能保存".into());
            }
        }
        
        let keys: Vec<&str> = path.split('.').collect();
        
        // 先转换 JSON 值到 TOML
        let toml_value = Self::json_value_to_toml_static(&value)?;
        
        let mut current = self.document.as_table_mut();
        
        // 导航到目标位置,创建中间表格
        for (i, key) in keys.iter().enumerate() {
            if i == keys.len() - 1 {
                // 最后一个键,设置值
                current.insert(key, toml_value);
                self.is_modified = true;
                info!("Config value set: {} = {:?}", path, value);
                
                // 自动保存到文件
                self.save_to_file()?;
                
                return Ok(());
            } else {
                // 中间键,创建或获取表格
                if !current.contains_key(key) {
                    current.insert(key, Item::Table(Table::new()));
                }
                
                if let Some(Item::Table(table)) = current.get_mut(key) {
                    current = table;
                } else {
                    return Err(format!("Key '{}' in path '{}' is not a table", key, path).into());
                }
            }
        }
        
        Err("Failed to set value".into())
    }

    /// 转换 toml_edit::Item 到 serde_json::Value
    fn item_to_json_value(&self, item: &Item) -> Option<Value> {
        match item {
            Item::Value(value) => {
                match value {
                    toml_edit::Value::String(s) => Some(Value::String(s.value().to_string())),
                    toml_edit::Value::Integer(i) => Some(Value::Number(serde_json::Number::from(*i.value()))),
                    toml_edit::Value::Float(f) => {
                        if let Some(n) = serde_json::Number::from_f64(*f.value()) {
                            Some(Value::Number(n))
                        } else {
                            None
                        }
                    },
                    toml_edit::Value::Boolean(b) => Some(Value::Bool(*b.value())),
                    toml_edit::Value::Array(arr) => {
                        let mut json_array = Vec::new();
                        for item in arr.iter() {
                            if let Some(json_val) = self.item_to_json_value(&Item::Value(item.clone())) {
                                json_array.push(json_val);
                            }
                        }
                        Some(Value::Array(json_array))
                    },
                    toml_edit::Value::InlineTable(table) => {
                        let mut json_obj = serde_json::Map::new();
                        for (key, value) in table.iter() {
                            if let Some(json_val) = self.item_to_json_value(&Item::Value(value.clone())) {
                                json_obj.insert(key.to_string(), json_val);
                            }
                        }
                        Some(Value::Object(json_obj))
                    },
                    _ => None,
                }
            },
            Item::Table(table) => {
                let mut json_obj = serde_json::Map::new();
                for (key, item) in table.iter() {
                    if let Some(json_val) = self.item_to_json_value(item) {
                        json_obj.insert(key.to_string(), json_val);
                    }
                }
                Some(Value::Object(json_obj))
            },
            _ => None,
        }
    }

    /// 转换 serde_json::Value 到 toml_edit::Item (静态方法)
    fn json_value_to_toml_static(value: &Value) -> Result<Item, Box<dyn std::error::Error>> {
        match value {
            Value::String(s) => {
                let string_value = toml_edit::Value::String(toml_edit::Formatted::new(s.clone()));
                Ok(Item::Value(string_value))
            },
            Value::Number(n) => {
                if let Some(i) = n.as_i64() {
                    let int_value = toml_edit::Value::Integer(toml_edit::Formatted::new(i));
                    Ok(Item::Value(int_value))
                } else if let Some(f) = n.as_f64() {
                    let float_value = toml_edit::Value::Float(toml_edit::Formatted::new(f));
                    Ok(Item::Value(float_value))
                } else {
                    Err("Invalid number format".into())
                }
            },
            Value::Bool(b) => {
                let bool_value = toml_edit::Value::Boolean(toml_edit::Formatted::new(*b));
                Ok(Item::Value(bool_value))
            },
            Value::Array(arr) => {
                let mut toml_array = toml_edit::Array::new();
                for item in arr {
                    if let Item::Value(toml_val) = Self::json_value_to_toml_static(item)? {
                        toml_array.push(toml_val);
                    }
                }
                Ok(Item::Value(toml_edit::Value::Array(toml_array)))
            },
            Value::Object(obj) => {
                let mut toml_table = Table::new();
                for (key, val) in obj {
                    toml_table.insert(key, Self::json_value_to_toml_static(val)?);
                }
                Ok(Item::Table(toml_table))
            },
            Value::Null => Err("TOML does not support null values".into()),
        }
    }
}

/// 初始化配置管理器
pub fn init_config<P: AsRef<Path>>(config_path: P) -> Result<(), Box<dyn std::error::Error>> {
    let mut manager = CONFIG_MANAGER.write();
    // 解析命令行参数
    let args: Vec<String> = env::args().collect();
    manager.parse_args(args);
    // 加载配置文件
    manager.load_from_file(config_path)?;
    Ok(())
}

/// 仅加载配置文件,不解析命令行参数(测试用)
pub fn init_config_file_only<P: AsRef<Path>>(config_path: P) -> Result<(), Box<dyn std::error::Error>> {
    let mut manager = CONFIG_MANAGER.write();
    manager.load_from_file(config_path)?;
    Ok(())
}

/// 重置配置管理器(测试用)
pub fn reset_config() {
    let mut manager = CONFIG_MANAGER.write();
    *manager = ConfigManager::new();
}

/// 获取配置值 (保持兼容性,返回 JSON Value)
pub fn get_arg(path: &str) -> Value {
    let manager = CONFIG_MANAGER.read();
    if let Some(string_value) = manager.get_value(path) {
        // 尝试解析为 JSON,如果失败则返回字符串
        if let Ok(json_value) = serde_json::from_str::<Value>(&string_value) {
            json_value
        } else {
            Value::String(string_value)
        }
    } else {
        Value::Null
    }
}

/// 设置配置值
pub fn set_arg(path: &str, value: Value) -> Result<(), Box<dyn std::error::Error>> {
    let mut manager = CONFIG_MANAGER.write();
    manager.set_value(path, value)?;
    Ok(())
}

/// 保存配置到文件
pub fn save_config() -> Result<(), Box<dyn std::error::Error>> {
    let mut manager = CONFIG_MANAGER.write();
    manager.save_to_file()?;
    Ok(())
}

/// 获取字符串配置
pub fn get_string(path: &str) -> Option<String> {
    let manager = CONFIG_MANAGER.read();
    manager.get_string(path)
}

/// 获取整数配置
pub fn get_i64(path: &str) -> Option<i64> {
    let manager = CONFIG_MANAGER.read();
    manager.get_i64(path)
}

/// 获取浮点数配置
pub fn get_f64(path: &str) -> Option<f64> {
    let manager = CONFIG_MANAGER.read();
    manager.get_f64(path)
}

/// 获取布尔值配置
pub fn get_bool(path: &str) -> Option<bool> {
    let manager = CONFIG_MANAGER.read();
    manager.get_bool(path)
}

/// 设置字符串配置
pub fn set_string(path: &str, value: String) -> Result<(), Box<dyn std::error::Error>> {
    set_arg(path, Value::String(value))
}

/// 设置整数配置
pub fn set_i64(path: &str, value: i64) -> Result<(), Box<dyn std::error::Error>> {
    set_arg(path, Value::Number(serde_json::Number::from(value)))
}

/// 设置浮点数配置
pub fn set_f64(path: &str, value: f64) -> Result<(), Box<dyn std::error::Error>> {
    if let Some(n) = serde_json::Number::from_f64(value) {
        set_arg(path, Value::Number(n))
    } else {
        Err("Invalid float value".into())
    }
}

/// 设置布尔值配置
pub fn set_bool(path: &str, value: bool) -> Result<(), Box<dyn std::error::Error>> {
    set_arg(path, Value::Bool(value))
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use tempfile::tempdir;

    #[test]
    fn test_config_basic_operations() {
        reset_config(); // 重置配置管理器
        
        let temp_dir = tempdir().unwrap();
        let config_path = temp_dir.path().join("basic_test_config.toml");
        
        // 创建测试配置文件
        let config_content = r#"
# 这是一个测试配置文件
[database]
host = "localhost"
port = 5432
enabled = true

[app]
name = "test_app"
version = "1.0.0"

[app.features]
logging = true
metrics = false
"#;
        fs::write(&config_path, config_content).unwrap();
        
        // 初始化配置
        init_config_file_only(&config_path).unwrap();
        
        // 测试读取配置
        assert_eq!(get_string("database.host"), Some("localhost".to_string()));
        assert_eq!(get_i64("database.port"), Some(5432));
        assert_eq!(get_bool("database.enabled"), Some(true));
        assert_eq!(get_string("app.name"), Some("test_app".to_string()));
        assert_eq!(get_bool("app.features.logging"), Some(true));
        assert_eq!(get_bool("app.features.metrics"), Some(false));
        
        // 测试设置配置
        set_string("database.host", "127.0.0.1".to_string()).unwrap();
        set_i64("database.port", 3306).unwrap();
        set_bool("app.features.metrics", true).unwrap();
        
        // 验证设置是否生效
        assert_eq!(get_string("database.host"), Some("127.0.0.1".to_string()));
        assert_eq!(get_i64("database.port"), Some(3306));
        assert_eq!(get_bool("app.features.metrics"), Some(true));
        
        // 保存配置
        save_config().unwrap();
        
        // 验证文件是否更新
        let saved_content = fs::read_to_string(&config_path).unwrap();
        assert!(saved_content.contains("127.0.0.1"));
        assert!(saved_content.contains("3306"));
        
        // 验证注释是否保留
        assert!(saved_content.contains("# 这是一个测试配置文件"));
    }
    
    #[test]
    fn test_nested_config() {
        reset_config(); // 重置配置管理器
        
        let temp_dir = tempdir().unwrap();
        let config_path = temp_dir.path().join("nested_config_test.toml");
        
        // 初始化空配置
        init_config_file_only(&config_path).unwrap();
        
        // 设置嵌套配置
        set_string("a.b.c", "deep_value".to_string()).unwrap();
        set_i64("x.y.z", 42).unwrap();
        
        // 验证嵌套配置
        assert_eq!(get_string("a.b.c"), Some("deep_value".to_string()));
        assert_eq!(get_i64("x.y.z"), Some(42));
        
        // 保存并验证
        save_config().unwrap();
        
        let saved_content = fs::read_to_string(&config_path).unwrap();
        assert!(saved_content.contains("deep_value"));
        assert!(saved_content.contains("42"));
    }

    #[test]
    fn test_command_line_args() {
        reset_config(); // 重置配置管理器
        
        let temp_dir = tempdir().unwrap();
        let config_path = temp_dir.path().join("args_test_config.toml");
        
        // 创建测试配置文件
        let config_content = r#"
[database]
host = "localhost"
port = 5432
"#;
        fs::write(&config_path, config_content).unwrap();
        
        // 模拟命令行参数
        let test_args = vec![
            "program_name".to_string(),
            "database.host=127.0.0.1".to_string(),
            "database.port=3306".to_string(),
            "debug=true".to_string(),
        ];
        
        let mut manager = CONFIG_MANAGER.write();
        manager.parse_args(test_args);
        manager.load_from_file(&config_path).unwrap();
        drop(manager);
        
        // 命令行参数应该覆盖配置文件
        assert_eq!(get_string("database.host"), Some("127.0.0.1".to_string()));
        assert_eq!(get_i64("database.port"), Some(3306));
        assert_eq!(get_bool("debug"), Some(true));
    }

    #[test]
    fn test_type_conversions() {
        reset_config(); // 重置配置管理器
        
        let temp_dir = tempdir().unwrap();
        let config_path = temp_dir.path().join("type_test_config.toml");
        
        // 模拟命令行参数
        let test_args = vec![
            "program_name".to_string(),
            "int_val=42".to_string(),
            "float_val=3.14".to_string(),
            "bool_val=true".to_string(),
            "str_val=hello".to_string(),
        ];
        
        let mut manager = CONFIG_MANAGER.write();
        manager.parse_args(test_args);
        manager.load_from_file(&config_path).unwrap();
        drop(manager);
        
        // 测试类型转换
        assert_eq!(get_i64("int_val"), Some(42));
        assert_eq!(get_f64("float_val"), Some(3.14));
        assert_eq!(get_bool("bool_val"), Some(true));
        assert_eq!(get_string("str_val"), Some("hello".to_string()));
    }

    #[test]
    fn test_source_protection() {
        reset_config(); // 重置配置管理器
        
        let temp_dir = tempdir().unwrap();
        let config_path = temp_dir.path().join("source_test_config.toml");
        
        // 创建测试配置文件
        let config_content = r#"
[database]
host = "localhost"
port = 5432
"#;
        fs::write(&config_path, config_content).unwrap();
        
        // 模拟命令行参数
        let test_args = vec![
            "program_name".to_string(),
            "cmd_arg=from_cmd".to_string(),
        ];
        
        // 设置环境变量
        unsafe { env::set_var("ENV_VAR", "from_env"); }
        
        let mut manager = CONFIG_MANAGER.write();
        manager.parse_args(test_args);
        manager.load_from_file(&config_path).unwrap();
        drop(manager);
        
        // 验证读取值
        assert_eq!(get_string("cmd_arg"), Some("from_cmd".to_string()));
        assert_eq!(get_string("ENV_VAR"), Some("from_env".to_string()));
        assert_eq!(get_string("database.host"), Some("localhost".to_string()));
        
        // 尝试设置命令行参数 - 应该报错
        let result = set_string("cmd_arg", "modified".to_string());
        assert!(result.is_err());
        assert_eq!(result.unwrap_err().to_string(), "当前为命令行参数, 不能保存");
        
        // 尝试设置环境变量 - 应该报错
        let result = set_string("ENV_VAR", "modified".to_string());
        assert!(result.is_err());
        assert_eq!(result.unwrap_err().to_string(), "当前为环境变量参数, 不能保存");
        
        // 设置配置文件中的值 - 应该成功
        let result = set_string("database.host", "127.0.0.1".to_string());
        assert!(result.is_ok());
        
        // 验证配置文件值被修改
        assert_eq!(get_string("database.host"), Some("127.0.0.1".to_string()));
        
        // 设置新的配置值 - 应该成功
        let result = set_string("new_config", "new_value".to_string());
        assert!(result.is_ok());
        assert_eq!(get_string("new_config"), Some("new_value".to_string()));
        
        // 清理环境变量
        unsafe { env::remove_var("ENV_VAR"); }
    }
}