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
|
use std::{
fs::File,
io::{Read, Write},
};
use serde::{Deserialize, Serialize};
use crate::error::MLE;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Cfg {
pub data: String,
pub cache: String,
pub apis: Apis,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Apis {
pub modrinth: String,
}
impl Cfg {
pub fn init(path: Option<String>) -> MLE<Self> {
let configfile = match path {
Some(p) => String::from(p),
None => dirs::config_dir().unwrap().join("modlist.toml").to_string_lossy().into(),
};
let mut file = match File::open(&configfile) {
Ok(file) => file,
Err(err) => {
if err.kind() == std::io::ErrorKind::NotFound {
println!("No config file found, creating one");
let default_cfg = Cfg {
data: String::from("~/.cache/modlist/"),
cache: String::from("~/.cache/modlist/cache"),
apis: Apis {
modrinth: String::from("https://api.modrinth.com/v2/"),
},
};
let mut file = File::create(&configfile)?;
println!("Created config file");
file.write_all(toml::to_string(&default_cfg)?.as_bytes())?;
File::open(&configfile)?
} else {
return Err(err.into());
}
}
};
let mut content = String::new();
file.read_to_string(&mut content)?;
let config = toml::from_str::<Cfg>(&content)?;
Ok(config)
}
}
|