aboutsummaryrefslogtreecommitdiff
path: root/lockchain-files/src/config.rs
blob: 155e976b2db0d4ef51ee8103670824f8ef6d0861 (plain)
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
use std::{
    error::Error,
    fmt,
    fs::{File, OpenOptions as OO},
    io::{self, Write},
    path::PathBuf,
    time::SystemTime,
};

use semver::Version;
use serde_yaml;
use crate::utils::FileToString;

use crate::lcc::{errors::VaultError, VaultType};

/// 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(Debug, Serialize, Deserialize)]
pub struct VaultConfig {
    /// A semver conforming version string
    pub version: String,
    pub vault_type: ConfigType,
    pub created_at: SystemTime,
    pub modified_at: SystemTime,
}

#[derive(Debug, Serialize, Deserialize)]
pub enum ConfigType {
    SoloUser,
    Administrated,
    Unmanaged,
}

impl VaultConfig {
    pub fn new(vt: &VaultType) -> Result<Self, VaultError> {
        Ok(Self {
            version: "0.1".into(),
            vault_type: match vt {
                &VaultType::SoloUser { .. } => ConfigType::SoloUser,
                &VaultType::Administrated { .. } => ConfigType::Administrated,
                _ => ConfigType::Unmanaged,
            },
            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("vault.cfg");

        let t = serde_yaml::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("vault.cfg");

        let cfg: VaultConfig = match File::open(cfg_path.as_path()) {
            Ok(mut f) => match f.get_string() {
                Ok(s) => match serde_yaml::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)
        }
    }
}