alma/src/presets.rs
James McMurray 490ab30f4c Refactor main.rs and fix clippy lints
Status: WIP

Completed:
* Fixed flagged clippy lints
* Moved qemu(), main.rs::mount() and chroot() to the tools module.
* Moved constants in main.rs to constants.rs (including base packages
  array)
* Renamed Presets struct to PresetsCollection to avoid confusion with
  Preset struct
* Moved main() to the top of main.rs to highlight general logic path
* Added comments and docstrings to some functions
* Removed some uses of `use foo::*` to make the source of imported functions
  and structs clearer

TODO:
* Move remaining code in main.rs to modules (except main())
* Break up create() function in to separate steps
* Log every command run (with arguments) to debug! when verbose flag is used
* Add docstrings for remaining functions and document constants (e.g.
  why noatime is used)
* Remove remaining uses of `use foo::*`
* Consider renaming/moving tools module to address tool:: vs. Tool::
  confusion
2020-03-06 23:11:56 +01:00

66 lines
1.9 KiB
Rust

use crate::error::{Error, ErrorKind};
use failure::ResultExt;
use serde::Deserialize;
use std::collections::HashSet;
use std::env;
use std::fs;
use std::path::{Path, PathBuf};
#[derive(Deserialize)]
struct Preset {
packages: Option<Vec<String>>,
script: Option<String>,
environment_variables: Option<Vec<String>>,
}
impl Preset {
fn load(path: &Path) -> Result<Self, Error> {
let data = fs::read_to_string(path)
.with_context(|_| ErrorKind::Preset(format!("{}", path.display())))?;
Ok(toml::from_str(&data)
.with_context(|_| ErrorKind::Preset(format!("{}", path.display())))?)
}
}
pub struct PresetsCollection {
pub packages: HashSet<String>,
pub scripts: Vec<String>,
}
impl PresetsCollection {
pub fn load(list: &[PathBuf]) -> Result<Self, Error> {
let mut packages = HashSet::new();
let mut scripts = Vec::new();
let mut environment_variables = HashSet::new();
for preset in list {
let Preset {
script,
packages: preset_packages,
environment_variables: preset_environment_variables,
} = Preset::load(&preset)?;
if let Some(preset_packages) = preset_packages {
packages.extend(preset_packages);
}
if let Some(preset_environment_variables) = preset_environment_variables {
environment_variables.extend(preset_environment_variables);
}
scripts.extend(script);
}
let missing_envrionments: Vec<String> = environment_variables
.into_iter()
.filter(|var| env::var(var).is_err())
.collect();
if !missing_envrionments.is_empty() {
return Err(ErrorKind::MissingEnvironmentVariables(missing_envrionments).into());
}
Ok(Self { packages, scripts })
}
}