argot_cli/read_config/
json.rs1#![cfg(feature = "json")]
2use std::fs::File;
3use std::io::{BufReader, self};
4use std::path::Path;
5
6use crate::types::ConfigEntries;
7use crate::arg_parser::ParserConfig;
8
9pub fn read_config_file<P>(filename: P) -> io::Result<ParserConfig>
10where
11 P: AsRef<Path>,
12{
13 let file = File::open(filename)?;
14 let reader = BufReader::new(file);
15 let configs: ConfigEntries = serde_json::from_reader(reader)?;
16
17 ParserConfig::new(configs)
18}
19
20#[cfg(test)]
21mod test_json {
22 use super::*;
23 use std::collections::HashMap;
24 use crate::types::ConfigEntry;
25
26 #[test]
27 fn read_json_object() {
28 let configs: ParserConfig = read_config_file("config_object.json").unwrap();
29 let map: HashMap<String, ConfigEntry> = configs.into_inner();
30 let expected = HashMap::from([
31 ("quiet".to_string(), ConfigEntry::Flag),
32 ("q".to_string(), ConfigEntry::Alias { target: "quiet".to_string() }),
33 ("verbose".to_string(), ConfigEntry::Count),
34 ("v".to_string(), ConfigEntry::Alias { target: "verbose".to_string() }),
35 ("dry-run".to_string(), ConfigEntry::Flag),
36 ("n".to_string(), ConfigEntry::Alias { target: "dry-run".to_string() }),
37 ("j".to_string(), ConfigEntry::Int { default: Some(0) }),
38 ("browser".to_string(), ConfigEntry::Text { default: None }),
39 ("hints".to_string(), ConfigEntry::List { sep: None }),
40 ]);
41
42 assert_eq!(map, expected);
43 }
44
45 #[test]
46 fn read_json_array() {
47 let configs: ParserConfig = read_config_file("config_array.json").unwrap();
48 let map: HashMap<String, ConfigEntry> = configs.into_inner();
49 let expected = HashMap::from([
50 ("quiet".to_string(), ConfigEntry::Flag),
51 ("q".to_string(), ConfigEntry::Alias { target: "quiet".to_string() }),
52 ("verbose".to_string(), ConfigEntry::Count),
53 ("v".to_string(), ConfigEntry::Alias { target: "verbose".to_string() }),
54 ("dry-run".to_string(), ConfigEntry::Flag),
55 ("n".to_string(), ConfigEntry::Alias { target: "dry-run".to_string() }),
56 ("j".to_string(), ConfigEntry::Int { default: Some(0) }),
57 ]);
58
59 assert_eq!(map, expected);
60 }
61}