abscissa_core/
config.rs

1//! Support for managing global configuration, as well as loading it from TOML.
2
3mod cell;
4mod configurable;
5mod overrides;
6
7pub use self::{cell::CfgCell, configurable::Configurable, overrides::Override};
8
9use crate::{
10    fs::File,
11    path::AbsPath,
12    FrameworkError,
13    FrameworkErrorKind::{ConfigError, IoError, PathError},
14};
15use serde::de::DeserializeOwned;
16use std::{fmt::Debug, io::Read};
17
18/// Configuration reader.
19#[cfg(feature = "application")]
20pub type Reader<C> = std::sync::Arc<C>;
21
22/// Trait for Abscissa configuration data structures.
23pub trait Config: Debug + Default + DeserializeOwned {
24    /// Load the configuration from the given TOML string.
25    fn load_toml(toml_string: impl AsRef<str>) -> Result<Self, FrameworkError>;
26
27    /// Load the global configuration from the TOML file at the given path.
28    /// If an error occurs reading or parsing the file, print it out and exit.
29    fn load_toml_file(path: impl AsRef<AbsPath>) -> Result<Self, FrameworkError>;
30}
31
32impl<C> Config for C
33where
34    C: Debug + Default + DeserializeOwned,
35{
36    fn load_toml(toml_string: impl AsRef<str>) -> Result<Self, FrameworkError> {
37        Ok(toml::from_str(toml_string.as_ref())?)
38    }
39
40    fn load_toml_file(path: impl AsRef<AbsPath>) -> Result<Self, FrameworkError> {
41        let mut file = File::open(path.as_ref().as_path()).map_err(|e| {
42            let io_error = IoError.context(e);
43            let path_error = PathError {
44                name: Some(path.as_ref().as_path().into()),
45            }
46            .context(io_error);
47            ConfigError.context(path_error)
48        })?;
49
50        let mut toml_string = String::new();
51        file.read_to_string(&mut toml_string)?;
52        Self::load_toml(toml_string)
53    }
54}