forked from SpaceManiac/SpacemanDMM
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconfig.rs
More file actions
78 lines (66 loc) · 1.98 KB
/
config.rs
File metadata and controls
78 lines (66 loc) · 1.98 KB
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
use std::{io, env, fs};
use std::path::{Path, PathBuf};
#[derive(Serialize, Deserialize, Debug, Default)]
pub struct Config {
pub recent: Vec<PathBuf>,
}
impl Config {
pub fn load() -> Config {
load(&get_config_path()).unwrap_or_default()
}
pub fn save(&self) {
if let Err(e) = save(self, &get_config_path()) {
println!("Config write error:\n{}", e);
}
}
pub fn make_recent(&mut self, recent: &Path) {
if let Some(first) = self.recent.first() {
if first == recent {
return; // no work to do
}
}
self.recent.retain(|path| path != recent);
self.recent.insert(0, recent.to_owned());
}
}
fn get_config_path() -> PathBuf {
// Determine the configuration directory
let mut config_dir;
if let Ok(current_exe) = env::current_exe() {
// Put runtime files adjacent to the executable
config_dir = current_exe;
config_dir.pop();
} else {
// As a fallback, use the working directory
config_dir = PathBuf::from(".");
}
config_dir.push("config.toml");
config_dir
}
fn load(path: &Path) -> io::Result<Config> {
use std::io::Read;
let mut contents = String::new();
io::BufReader::new(fs::File::open(path)?).read_to_string(&mut contents)?;
match toml::from_str::<Config>(&contents) {
Ok(cfg) => Ok(cfg),
Err(e) => {
println!("Config read error:\n{}", e);
Ok(Config::default())
}
}
}
fn save(cfg: &Config, path: &Path) -> io::Result<()> {
use std::io::Write;
use serde::Serialize;
let mut buffer = String::new();
cfg.serialize(
toml::ser::Serializer::new(&mut buffer)
.pretty_string(true)
.pretty_string_literal(false)
.pretty_array(true),
).unwrap();
if let Some(parent) = path.parent() {
fs::create_dir_all(parent)?;
}
fs::File::create(path)?.write_all(buffer.as_bytes())
}