mongodb_atlas_cli/config/source/
profile.rs

1use std::{collections::HashMap, path::PathBuf};
2
3use config::{ConfigError, Source, Value};
4
5use super::{AtlasCLIConfigSourceError, config_value_from_toml_file};
6
7#[derive(Clone, Debug)]
8pub struct AtlasCLIProfileConfigSource {
9    source: PathBuf,
10    profile_name: String,
11}
12
13impl AtlasCLIProfileConfigSource {
14    pub fn new(source: impl Into<PathBuf>, profile_name: impl Into<String>) -> Self {
15        Self {
16            source: source.into(),
17            profile_name: profile_name.into(),
18        }
19    }
20}
21
22impl Source for AtlasCLIProfileConfigSource {
23    fn clone_into_box(&self) -> Box<dyn Source + Send + Sync> {
24        Box::new((*self).clone())
25    }
26
27    fn collect(&self) -> Result<HashMap<String, Value>, ConfigError> {
28        let config = config_value_from_toml_file(
29            self.profile_name.clone(),
30            &self.source,
31            |mut toml_config| match toml_config.remove(&self.profile_name) {
32                Some(profile_config) => {
33                    if let toml::Value::Table(profile_config) = profile_config {
34                        Ok(profile_config)
35                    } else {
36                        Err(AtlasCLIConfigSourceError::InvalidProfileExpectedTable)
37                    }
38                }
39                None => Ok(toml::Table::new()),
40            },
41        )?;
42
43        Ok(config)
44    }
45}