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
use std::io::prelude::*;
use std::path::Path;
use std::fs::File;
use std::fs;
use serde::de::DeserializeOwned;
static FILE_PATH: &str = "./Data";
static FILE_NAME: &str = "appsettings.json";
fn verify_path_and_file_exists() -> std::io::Result<()> {
let directory_path = Path::new(FILE_PATH);
if !directory_path.exists() {
fs::create_dir(FILE_PATH)?;
}
let file_path = directory_path.join(FILE_PATH);
if !file_path.exists() {
File::create(&file_path)?;
fs::write(file_path, "{}").expect("Unable to write file");
}
Ok(())
}
pub struct SettingsFile {}
impl SettingsFile {
pub fn get<T: DeserializeOwned>() -> std::io::Result<T> {
verify_path_and_file_exists()?;
let file_path = Path::new(FILE_PATH).join(FILE_NAME);
let mut file = File::open(&file_path)?;
let mut contents = String::new();
file.read_to_string(&mut contents)?;
let v: T = serde_json::from_str(contents.as_str()).unwrap();
Ok(v)
}
}
#[cfg(test)]
mod tests {
#[test]
fn it_works() {
assert_eq!(2 + 2, 4);
}
}