penguin_config/
lib.rs

1pub use prelude::*;
2mod prelude {
3    use std::fs::File;
4    use std::io::Read;
5
6    pub use serde::Deserialize;
7    pub use serde::Serialize;
8    pub use crate::deserializer::Deserializer;
9    pub use crate::serializer::Serializer;
10
11    pub use crate::traits::PenguinConfig;
12    pub use crate::traits::PenguinConfigGenerate;
13
14    pub use penguin_config_derive::PenguinConfigFile;
15    pub use penguin_config_derive::PenguinConfigGenerate;
16
17    pub fn read_json(file_path: &str) -> String {
18        let mut file = File::open(file_path).expect("couldn't open file");
19        let mut json = String::new();
20        file.read_to_string(&mut json).expect("couldn't read to json");
21        json
22    }
23}
24
25mod traits {
26    pub trait PenguinConfig {
27        fn read_config() -> Self;
28    }
29
30    pub trait PenguinConfigGenerate {
31        fn generate_penguin_config_file();
32    }
33}
34
35mod deserializer {
36    use std::marker::PhantomData;
37    use crate::read_json;
38
39    /// let t: T = Deserializer::file_path("some_path.json").deserialize();
40    pub struct Deserializer<'a, T: serde::Deserialize<'a>> {
41        json: String,
42        phantom_data: PhantomData<&'a T>,
43    }
44
45    impl<'a, T> Deserializer<'a, T> where T: serde::Deserialize<'a> {
46        pub fn file_path(file_path: &str) -> Self {
47            Self {
48                json: read_json(file_path),
49                phantom_data: PhantomData,
50            }
51        }
52
53        pub fn deserialize(&'a self) -> T {
54            let config: T = serde_json::from_str(&self.json)
55                .expect(&format!("couldn't deserialize string: [{}]", &self.json));
56            config
57        }
58    }
59}
60
61mod serializer {
62    use std::fs::File;
63    use std::io::Write;
64    use std::path::Path;
65
66    /// Serializer::file_path("some_path.json").serialize(&T::default());
67    pub struct Serializer {
68        path: String,
69    }
70    
71    impl Serializer {
72        pub fn file_path(file_path: &str) -> Self {
73
74            // create folder(s) if not already present
75            let path = Path::new(file_path);
76            let prefix = path.parent().expect("couldn't find parent dirs");
77            std::fs::create_dir_all(prefix).expect("couldn't create parent dirs");
78
79            Self { path: file_path.to_owned(), }
80        }
81
82        pub fn serialize<T: serde::Serialize>(&self, data: &T) {
83            let json = serde_json::to_string(data).expect("couldn't turn data into json");
84
85            let mut file = File::create(&self.path)
86                .expect(&format!("couldn't create file at path: {}", &self.path));
87
88            file.write_all(json.as_bytes())
89                .expect(&format!("couldn't write json to file {}", &self.path));
90        }
91    }
92}
93
94
95
96
97
98
99
100