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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
|
use std::{
error::Error,
fmt,
fs::{File, OpenOptions as OO},
io::{self, Write},
path::PathBuf,
time::SystemTime,
};
use semver::Version;
use toml;
use utils::FileToString;
/// A set of errors around `lockchain-files` configs
#[derive(Debug)]
pub enum ConfigError {
IncompatibleVersion(String, String),
ConfigCorrupted,
}
impl fmt::Display for ConfigError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
use self::ConfigError::*;
write!(
f,
"{}",
match self {
IncompatibleVersion(f, l) => {
format!("Version '{}' is incompatible with library '{}'", f, l)
}
ConfigCorrupted => "Configuration file was corrupted!".into(),
}
)
}
}
impl Error for ConfigError {}
/// The configuration describing a file vault
#[derive(Serialize, Deserialize, Debug)]
pub struct VaultConfig {
/// A semver conforming version string
pub version: String,
pub created_at: SystemTime,
pub modified_at: SystemTime,
}
impl VaultConfig {
pub fn new() -> Self {
Self {
version: "0.1".into(),
created_at: SystemTime::now(),
modified_at: SystemTime::now(),
}
}
pub fn save(&self, vault: &PathBuf) -> Result<(), io::Error> {
let mut cfg_path = vault.clone();
cfg_path.push("config.toml");
let t = toml::to_string(self).unwrap();
let mut f = OO::new().create(true).write(true).open(cfg_path)?;
f.write_all(t.as_bytes())?;
Ok(())
}
/// Attempts to load a configuration – returning detailed errors
pub fn load(vault: &PathBuf) -> Result<Self, ConfigError> {
let mut cfg_path = vault.clone();
cfg_path.push("config.toml");
let cfg: VaultConfig = match File::open(cfg_path.as_path()) {
Ok(mut f) => match f.get_string() {
Ok(s) => match toml::from_str(&s) {
Ok(c) => c,
Err(_) => return Err(ConfigError::ConfigCorrupted),
},
Err(_) => return Err(ConfigError::ConfigCorrupted),
},
Err(_) => return Err(ConfigError::ConfigCorrupted),
};
let version = match Version::parse(&cfg.version) {
Ok(v) => v,
Err(_) => return Err(ConfigError::ConfigCorrupted),
};
if version != Version::parse("0.1").unwrap() {
Err(ConfigError::IncompatibleVersion(cfg.version, "0.1".into()))
} else {
Ok(cfg)
}
}
}
|