Skip to main content

rskit_config/source/
toml.rs

1use std::path::{Path, PathBuf};
2
3use rskit_errors::{AppError, AppResult};
4
5use super::contract::ConfigSource;
6
7/// TOML file source.
8#[derive(Debug, Clone)]
9pub struct TomlFileSource {
10    path: PathBuf,
11    required: bool,
12}
13
14impl TomlFileSource {
15    /// Create a required TOML file source.
16    pub fn required(path: impl Into<PathBuf>) -> Self {
17        Self {
18            path: path.into(),
19            required: true,
20        }
21    }
22
23    /// Create an optional TOML file source.
24    pub fn optional(path: impl Into<PathBuf>) -> Self {
25        Self {
26            path: path.into(),
27            required: false,
28        }
29    }
30
31    /// Return the configured path.
32    pub fn path(&self) -> &Path {
33        &self.path
34    }
35}
36
37impl ConfigSource for TomlFileSource {
38    fn collect(&self) -> AppResult<config::Config> {
39        config::Config::builder()
40            .add_source(config::File::from(self.path.as_path()).required(self.required))
41            .build()
42            .map_err(|e| {
43                AppError::invalid_input(
44                    "config",
45                    format!("failed to load TOML config '{}': {e}", self.path.display()),
46                )
47            })
48    }
49}