soph_config/support/
instance.rs

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
use crate::{
    error::Error,
    traits::{ConfigurationTrait, Source},
    Config,
};
use soph_core::{
    error::ContainerError,
    support::{base_path, Container},
    traits::{ErrorTrait, InstanceTrait},
    Result,
};
use std::{path::PathBuf, str::FromStr};

impl InstanceTrait for Config {
    fn register(_: &Container) -> Result<Self, ContainerError> {
        let args: Vec<String> = std::env::args()
            .filter(|arg| arg.starts_with("--config="))
            .map(|arg| arg.replace("--config=", ""))
            .collect();

        let source = args
            .first()
            .map(|arg| arg.to_owned())
            .unwrap_or(".config.toml".to_owned());

        // find package config file (not workspace config file)
        let mut paths = Vec::new();
        if let Ok(config) = std::env::var("SOPH_CONFIG") {
            paths.push(PathBuf::from(config));
        }

        paths.extend([base_path(&source), base_path(".env")]);

        Ok(
            Self::try_from_source(match paths.iter().find(|path| path.exists()) {
                None => Source::Default,
                Some(path) => Source::from_str(&path.to_string_lossy()).map_err(Error::wrap)?,
            })
            .map_err(Error::wrap)?,
        )
    }
}