config_rw 1.0.2

配置文件读取与写入
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
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
#[macro_use]
extern crate log;

use std::path::Path;
use std::collections::HashMap;
use std::env;
use serde_json::Value;
use toml_edit::{DocumentMut, Item, Table};
use std::sync::OnceLock;

type StdBoxError = Box<dyn std::error::Error + Send + Sync>;
type R<V = ()> = Result<V, StdBoxError>;

/// 全局配置状态,只存储文件路径和命令行参数
static CONFIG_STATE: OnceLock<ConfigState> = OnceLock::new();

/// 配置状态结构体,只保存必要的状态信息
#[derive(Debug)]
struct ConfigState {
    /// 配置文件路径
    file_path: Option<String>,
    /// 命令行参数映射
    args_map: HashMap<String, String>,
}

impl ConfigState {
    /// 创建新的配置状态
    fn new() -> Self {
        Self {
            file_path: None,
            args_map: HashMap::new(),
        }
    }

    /// 解析命令行参数
    /// 支持格式:./xx.exe arg1 arg2=2 arg3="3"
    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());
    }

    /// 设置配置文件路径
    fn set_file_path<P: AsRef<Path>>(&mut self, path: P) {
        let path_str = path.as_ref().to_string_lossy().to_string();
        self.file_path = Some(path_str);
        info!("Config file path set to: {}", self.file_path.as_ref().unwrap());
    }

    /// 获取配置文件路径
    fn get_file_path(&self) -> Option<&String> {
        self.file_path.as_ref()
    }

    /// 获取命令行参数
    fn get_arg(&self, key: &str) -> Option<&String> {
        self.args_map.get(key)
    }

    /// 检查是否有命令行参数
    fn has_arg(&self, key: &str) -> bool {
        self.args_map.contains_key(key)
    }
}

/// 配置管理器工具类,提供无状态的配置文件操作
struct ConfigManager;

impl ConfigManager {
    /// 从文件加载配置文档
    fn load_document(file_path: &str) -> R<DocumentMut> {
        let path = Path::new(file_path);
        
        if path.exists() {
            let content = std::fs::read_to_string(path)?;
            let document = content.parse::<DocumentMut>().map_err(|e| {
                format!("Failed to parse TOML file '{}': {}", file_path, e)
            })?;
            Ok(document)
        } else {
            // 如果文件不存在,返回空文档
            Ok(DocumentMut::new())
        }
    }

    /// 保存配置文档到文件
    fn save_document(file_path: &str, document: &DocumentMut) -> R {
        // 确保目录存在
        if let Some(parent) = Path::new(file_path).parent() {
            std::fs::create_dir_all(parent)?;
        }
        
        std::fs::write(file_path, document.to_string())?;
        info!("Config saved to file: {}", file_path);
        Ok(())
    }

    /// 按优先级获取配置值:命令行参数 > 配置文件 > 环境变量
    fn get_value_with_priority(path: &str, state: &ConfigState) -> Option<String> {
        // 1. 首先检查命令行参数
        if let Some(value) = state.get_arg(path) {
            return Some(value.clone());
        }
        
        // 2. 然后检查配置文件
        if let Some(file_path) = state.get_file_path() {
            match Self::load_document(file_path) {
                Ok(document) => {
                    if let Some(config_value) = Self::get_config_value(&document, path) {
                        if let Some(string_value) = Self::json_value_to_string(&config_value) {
                            return Some(string_value);
                        }
                    }
                }
                Err(e) => {
                    warn!("Failed to load config file '{}': {}", file_path, e);
                }
            }
        }
        
        // 3. 最后检查环境变量
        if let Ok(env_value) = env::var(path.to_uppercase().replace('.', "_")) {
            return Some(env_value);
        }
        
        None
    }

    /// 从配置文件获取值
    fn get_config_value(document: &DocumentMut, path: &str) -> Option<Value> {
        let keys: Vec<&str> = path.split('.').collect();
        let mut current = 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(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(s: &str) -> Option<i64> {
        s.parse::<i64>().ok()
    }

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

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

    /// 设置配置值(原子操作:读取->修改->写入)
    fn set_config_value(path: &str, value: Value, state: &ConfigState) -> R {
        // 检查配置来源,如果来自命令行或环境变量则报错
        
        // 1. 检查是否来自命令行参数
        if state.has_arg(path) {
            return Err("当前为命令行参数, 不能保存".into());
        }
        
        // 2. 检查是否来自环境变量
        let env_key = path.to_uppercase().replace('.', "_");
        if env::var(&env_key).is_ok() {
            // 还需要确认配置文件中没有这个值
            if let Some(file_path) = state.get_file_path() {
                if let Ok(document) = Self::load_document(file_path) {
                    if Self::get_config_value(&document, path).is_none() {
                        return Err("当前为环境变量参数, 不能保存".into());
                    }
                }
            }
        }
        
        // 获取文件路径
        let file_path = state.get_file_path().ok_or("No file path specified")?;
        
        // 原子操作:读取->修改->写入
        let mut document = Self::load_document(file_path)?;
        
        let keys: Vec<&str> = path.split('.').collect();
        
        // 先转换 JSON 值到 TOML
        let toml_value = Self::json_value_to_toml(&value)?;
        
        let mut current = document.as_table_mut();
        
        // 导航到目标位置,创建中间表格
        for (i, key) in keys.iter().enumerate() {
            if i == keys.len() - 1 {
                // 最后一个键,设置值
                current.insert(key, toml_value);
                info!("Config value set: {} = {:?}", path, value);
                
                // 立即保存到文件
                Self::save_document(file_path, &document)?;
                
                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(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(value: &Value) -> R<Item> {
        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(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(val)?);
                }
                Ok(Item::Table(toml_table))
            },
            Value::Null => Err("TOML does not support null values".into()),
        }
    }
}

/// 获取全局配置状态
fn get_config_state() -> &'static ConfigState {
    CONFIG_STATE.get().expect("Config not initialized. Call init_config() first.")
}

/// 初始化配置管理器
pub fn init_config<P: AsRef<Path>>(config_path: P) -> R {
    let mut state = ConfigState::new();
    
    // 解析命令行参数
    let args: Vec<String> = env::args().collect();
    state.parse_args(args);
    
    // 设置配置文件路径
    state.set_file_path(config_path);
    
    // 设置全局状态
    CONFIG_STATE.set(state).map_err(|_| "Config already initialized")?;
    
    Ok(())
}

/// 仅设置配置文件路径,不解析命令行参数(测试用)
pub fn init_config_file_only<P: AsRef<Path>>(config_path: P) -> R {
    let mut state = ConfigState::new();
    state.set_file_path(config_path);
    
    // 设置全局状态
    CONFIG_STATE.set(state).map_err(|_| "Config already initialized")?;
    
    Ok(())
}

/// 获取配置值 (保持兼容性,返回 JSON Value)
pub fn get_arg(path: &str) -> Value {
    let state = get_config_state();
    
    // 1. 首先检查命令行参数
    if let Some(value) = state.get_arg(path) {
        // 尝试解析为 JSON,如果失败则返回字符串
        if let Ok(json_value) = serde_json::from_str::<Value>(value) {
            return json_value;
        } else {
            return Value::String(value.clone());
        }
    }
    
    // 2. 然后检查配置文件
    if let Some(file_path) = state.get_file_path() {
        match ConfigManager::load_document(file_path) {
            Ok(document) => {
                if let Some(config_value) = ConfigManager::get_config_value(&document, path) {
                    return config_value; // 直接返回 JSON 值,不转换为字符串
                }
            }
            Err(_) => {
                // 忽略加载错误,继续检查环境变量
            }
        }
    }
    
    // 3. 最后检查环境变量
    let env_key = path.to_uppercase().replace('.', "_");
    if let Ok(env_value) = env::var(&env_key) {
        // 尝试解析为 JSON,如果失败则返回字符串
        if let Ok(json_value) = serde_json::from_str::<Value>(&env_value) {
            return json_value;
        } else {
            return Value::String(env_value);
        }
    }
    
    Value::Null
}

/// 设置配置值
pub fn set_arg(path: &str, value: Value) -> R {
    let state = get_config_state();
    ConfigManager::set_config_value(path, value, state)?;
    Ok(())
}

/// 保存配置到文件(无状态模式下此方法无需实现,因为每次设置都自动保存)
pub fn save_config() -> R {
    // 无状态模式下,每次设置都自动保存,此方法保持兼容性
    Ok(())
}

/// 获取字符串配置
pub fn get_string(path: &str) -> Option<String> {
    let state = get_config_state();
    ConfigManager::get_value_with_priority(path, state)
}

/// 获取整数配置
pub fn get_i64(path: &str) -> Option<i64> {
    let state = get_config_state();
    if let Some(value) = ConfigManager::get_value_with_priority(path, state) {
        ConfigManager::string_to_i64(&value)
    } else {
        None
    }
}

/// 获取浮点数配置
pub fn get_f64(path: &str) -> Option<f64> {
    let state = get_config_state();
    if let Some(value) = ConfigManager::get_value_with_priority(path, state) {
        ConfigManager::string_to_f64(&value)
    } else {
        None
    }
}

/// 获取布尔值配置
pub fn get_bool(path: &str) -> Option<bool> {
    let state = get_config_state();
    if let Some(value) = ConfigManager::get_value_with_priority(path, state) {
        ConfigManager::string_to_bool(&value)
    } else {
        None
    }
}

/// 设置字符串配置
pub fn set_string(path: &str, value: String) -> R {
    set_arg(path, Value::String(value))
}

/// 设置整数配置
pub fn set_i64(path: &str, value: i64) -> R {
    set_arg(path, Value::Number(serde_json::Number::from(value)))
}

/// 设置浮点数配置
pub fn set_f64(path: &str, value: f64) -> R {
    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) -> R {
    set_arg(path, Value::Bool(value))
}

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

    #[test]
    fn test_config_basic_operations() {
        let temp_dir = tempdir().unwrap();
        let config_path = temp_dir.path().join("basic_test_config_unique.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();
        
        // 创建独立的配置状态进行测试
        let mut state = ConfigState::new();
        state.set_file_path(&config_path);
        
        // 测试读取配置
        assert_eq!(
            ConfigManager::get_value_with_priority("database.host", &state),
            Some("localhost".to_string())
        );
        assert_eq!(
            ConfigManager::string_to_i64(
                &ConfigManager::get_value_with_priority("database.port", &state).unwrap()
            ),
            Some(5432)
        );
        assert_eq!(
            ConfigManager::string_to_bool(
                &ConfigManager::get_value_with_priority("database.enabled", &state).unwrap()
            ),
            Some(true)
        );
        
        // 测试设置配置
        ConfigManager::set_config_value("database.host", Value::String("127.0.0.1".to_string()), &state).unwrap();
        ConfigManager::set_config_value("database.port", Value::Number(serde_json::Number::from(3306)), &state).unwrap();
        
        // 验证设置是否生效(重新读取文件)
        assert_eq!(
            ConfigManager::get_value_with_priority("database.host", &state),
            Some("127.0.0.1".to_string())
        );
        assert_eq!(
            ConfigManager::string_to_i64(
                &ConfigManager::get_value_with_priority("database.port", &state).unwrap()
            ),
            Some(3306)
        );
        
        // 验证文件是否更新
        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() {
        let temp_dir = tempdir().unwrap();
        let config_path = temp_dir.path().join("nested_config_test_unique.toml");
        
        // 创建独立的配置状态
        let mut state = ConfigState::new();
        state.set_file_path(&config_path);
        
        // 设置嵌套配置
        ConfigManager::set_config_value("a.b.c", Value::String("deep_value".to_string()), &state).unwrap();
        ConfigManager::set_config_value("x.y.z", Value::Number(serde_json::Number::from(42)), &state).unwrap();
        
        // 验证嵌套配置
        assert_eq!(
            ConfigManager::get_value_with_priority("a.b.c", &state),
            Some("deep_value".to_string())
        );
        assert_eq!(
            ConfigManager::string_to_i64(
                &ConfigManager::get_value_with_priority("x.y.z", &state).unwrap()
            ),
            Some(42)
        );
        
        // 验证文件内容
        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() {
        let temp_dir = tempdir().unwrap();
        let config_path = temp_dir.path().join("args_test_config_unique.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 state = ConfigState::new();
        state.parse_args(test_args);
        state.set_file_path(&config_path);
        
        // 命令行参数应该覆盖配置文件
        assert_eq!(
            ConfigManager::get_value_with_priority("database.host", &state),
            Some("127.0.0.1".to_string())
        );
        assert_eq!(
            ConfigManager::string_to_i64(
                &ConfigManager::get_value_with_priority("database.port", &state).unwrap()
            ),
            Some(3306)
        );
        assert_eq!(
            ConfigManager::string_to_bool(
                &ConfigManager::get_value_with_priority("debug", &state).unwrap()
            ),
            Some(true)
        );
    }

    #[test]
    fn test_type_conversions() {
        let temp_dir = tempdir().unwrap();
        let config_path = temp_dir.path().join("type_test_config_unique.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 state = ConfigState::new();
        state.parse_args(test_args);
        state.set_file_path(&config_path);
        
        // 测试类型转换
        assert_eq!(
            ConfigManager::string_to_i64(
                &ConfigManager::get_value_with_priority("int_val", &state).unwrap()
            ),
            Some(42)
        );
        assert_eq!(
            ConfigManager::string_to_f64(
                &ConfigManager::get_value_with_priority("float_val", &state).unwrap()
            ),
            Some(3.14)
        );
        assert_eq!(
            ConfigManager::string_to_bool(
                &ConfigManager::get_value_with_priority("bool_val", &state).unwrap()
            ),
            Some(true)
        );
        assert_eq!(
            ConfigManager::get_value_with_priority("str_val", &state),
            Some("hello".to_string())
        );
    }

    #[test]
    fn test_source_protection() {
        let temp_dir = tempdir().unwrap();
        let config_path = temp_dir.path().join("source_test_config_unique.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 state = ConfigState::new();
        state.parse_args(test_args);
        state.set_file_path(&config_path);
        
        // 验证读取值
        assert_eq!(
            ConfigManager::get_value_with_priority("cmd_arg", &state),
            Some("from_cmd".to_string())
        );
        assert_eq!(
            ConfigManager::get_value_with_priority("ENV_VAR", &state),
            Some("from_env".to_string())
        );
        assert_eq!(
            ConfigManager::get_value_with_priority("database.host", &state),
            Some("localhost".to_string())
        );
        
        // 尝试设置命令行参数 - 应该报错
        let result = ConfigManager::set_config_value("cmd_arg", Value::String("modified".to_string()), &state);
        assert!(result.is_err());
        assert_eq!(result.unwrap_err().to_string(), "当前为命令行参数, 不能保存");
        
        // 尝试设置环境变量 - 应该报错
        let result = ConfigManager::set_config_value("ENV_VAR", Value::String("modified".to_string()), &state);
        assert!(result.is_err());
        assert_eq!(result.unwrap_err().to_string(), "当前为环境变量参数, 不能保存");
        
        // 设置配置文件中的值 - 应该成功
        let result = ConfigManager::set_config_value("database.host", Value::String("127.0.0.1".to_string()), &state);
        assert!(result.is_ok());
        
        // 验证配置文件值被修改
        assert_eq!(
            ConfigManager::get_value_with_priority("database.host", &state),
            Some("127.0.0.1".to_string())
        );
        
        // 设置新的配置值 - 应该成功
        let result = ConfigManager::set_config_value("new_config", Value::String("new_value".to_string()), &state);
        assert!(result.is_ok());
        assert_eq!(
            ConfigManager::get_value_with_priority("new_config", &state),
            Some("new_value".to_string())
        );
        
        // 清理环境变量
        unsafe { env::remove_var("ENV_VAR"); }
    }

    #[test]
    fn test_concurrent_file_operations() {
        let temp_dir = tempdir().unwrap();
        let config_path = temp_dir.path().join("concurrent_test_config_unique.toml");
        
        // 创建测试配置文件
        let config_content = r#"
[test]
counter = 0
"#;
        fs::write(&config_path, config_content).unwrap();
        
        // 创建独立的配置状态
        let mut state = ConfigState::new();
        state.set_file_path(&config_path);
        
        // 验证初始值
        assert_eq!(
            ConfigManager::string_to_i64(
                &ConfigManager::get_value_with_priority("test.counter", &state).unwrap()
            ),
            Some(0)
        );
        
        // 模拟外部程序修改文件
        let external_content = r#"
[test]
counter = 100
external_value = "added_by_external"
"#;
        fs::write(&config_path, external_content).unwrap();
        
        // 读取时应该获取到外部修改的值
        assert_eq!(
            ConfigManager::string_to_i64(
                &ConfigManager::get_value_with_priority("test.counter", &state).unwrap()
            ),
            Some(100)
        );
        assert_eq!(
            ConfigManager::get_value_with_priority("test.external_value", &state),
            Some("added_by_external".to_string())
        );
        
        // 写入新值时应该基于当前文件内容
        ConfigManager::set_config_value("test.counter", Value::Number(serde_json::Number::from(200)), &state).unwrap();
        
        // 验证写入后的文件内容
        let final_content = fs::read_to_string(&config_path).unwrap();
        assert!(final_content.contains("200"));
        assert!(final_content.contains("added_by_external"));
        
        // 验证读取结果
        assert_eq!(
            ConfigManager::string_to_i64(
                &ConfigManager::get_value_with_priority("test.counter", &state).unwrap()
            ),
            Some(200)
        );
        assert_eq!(
            ConfigManager::get_value_with_priority("test.external_value", &state),
            Some("added_by_external".to_string())
        );
    }
}