summaryrefslogtreecommitdiff
path: root/src/config.rs
blob: 1866971619e9720a30507e7eb7f2ad16b6d20be3 (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
//! Tool configuration.

use log::debug;
use serde::Deserialize;
use std::default::Default;
use std::fs;
use std::path::{Path, PathBuf};

/// Configuration from configuration file.
#[derive(Default, Debug, Deserialize)]
pub struct Configuration {
    /// Base image, if provided.
    pub default_base_image: Option<PathBuf>,

    /// Default size of new VM image, in GiB.
    pub default_image_gib: Option<u64>,

    /// Default memory to give to new VM, in MiB.
    pub default_memory_mib: Option<u64>,

    /// Default number of CPUs for a new VM.
    pub default_cpus: Option<u64>,

    /// Should host certificates be generated for new VMs?
    pub default_generate_host_certificate: Option<bool>,

    /// Should new VM be started automatically on host boot?
    pub default_autostart: Option<bool>,

    /// Directory where new VM images should be created, if given.
    pub image_directory: Option<PathBuf>,

    /// List of path names of SSH public keys to put into the default
    /// user's `authorized_keys` file.
    pub authorized_keys: Option<Vec<PathBuf>>,

    /// Path name to SSH CA key for creating SSH host certificates.
    pub ca_key: Option<PathBuf>,
}

/// Errors from this module.
#[derive(Debug, thiserror::Error)]
pub enum ConfigurationError {
    /// Error reading configuration file.
    #[error("couldn't read configuration file {0}")]
    ReadError(PathBuf, #[source] std::io::Error),

    /// YAML parsing error.
    #[error(transparent)]
    YamlError(#[from] serde_yaml::Error),
}

impl Configuration {
    /// Read configuration from named file.
    pub fn from_file(filename: &Path) -> Result<Self, ConfigurationError> {
        if filename.exists() {
            debug!("reading configuration file {}", filename.display());
            let config = fs::read(filename)
                .map_err(|err| ConfigurationError::ReadError(filename.to_path_buf(), err))?;
            let config: Configuration = serde_yaml::from_slice(&config)?;
            debug!("config: {:#?}", config);
            Ok(config)
        } else {
            Ok(Self::default())
        }
    }
}