mongodb_atlas_cli/config/
mod.rs1use std::path::Path;
2
3use config::{Config, ConfigError, Environment};
4
5use serde::Deserialize;
6use source::{AtlasCLIGlobalConfigSource, AtlasCLIProfileConfigSource};
7
8use crate::path::GetCLICfgFilePathError;
9
10pub mod source;
11
12#[derive(thiserror::Error, Debug)]
13pub enum LoadCLIConfigError {
14 #[error("Failed to get config file path: {0}")]
15 FailedToGetConfigFilePath(#[from] GetCLICfgFilePathError),
16
17 #[error("Failed to build config: {0}")]
18 FailedToBuildConfig(#[from] ConfigError),
19
20 #[error("Unsupported config version: {0}")]
21 UnsupportedConfigVersion(u32),
22}
23
24#[derive(Clone, Debug, Default, Deserialize, PartialEq, Eq)]
25pub struct AtlasCLIConfig {
26 pub local_deployment_image: Option<String>,
28 pub mongosh_path: Option<String>,
30 pub telemetry_enabled: Option<bool>,
32 pub skip_update_check: Option<bool>,
34
35 pub auth_type: Option<AuthType>,
37 pub org_id: Option<String>,
39 pub project_id: Option<String>,
41 pub service: Option<Service>,
43 pub output: Option<OutputFormat>,
45}
46
47#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Eq)]
48pub enum AuthType {
49 #[serde(rename = "user_account")]
50 UserAccount,
51 #[serde(rename = "api_keys")]
52 ApiKeys,
53 #[serde(rename = "service_account")]
54 ServiceAccount,
55}
56
57#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Eq)]
58pub enum Service {
59 #[serde(rename = "cloud")]
60 Cloud,
61 #[serde(rename = "cloudgov")]
62 CloudGov,
63}
64
65#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Eq)]
66pub enum OutputFormat {
67 #[serde(rename = "json")]
68 Json,
69 #[serde(rename = "plaintext")]
70 Plaintext,
71}
72
73pub fn load_config(profile_name: Option<&str>) -> Result<AtlasCLIConfig, LoadCLIConfigError> {
76 let config_file_path = crate::path::config_file()?;
78
79 load_config_from_file(config_file_path, true, profile_name)
81}
82
83pub fn load_config_from_file(
85 config_file_path: impl AsRef<Path>,
86 load_environment_variables: bool,
87 profile_name: Option<&str>,
88) -> Result<AtlasCLIConfig, LoadCLIConfigError> {
89 let config_file_path = config_file_path.as_ref();
90
91 let mut config_builder = Config::builder()
99 .add_source(AtlasCLIGlobalConfigSource::new(config_file_path))
100 .add_source(AtlasCLIProfileConfigSource::new(
101 config_file_path,
102 profile_name.unwrap_or("default"),
103 ));
104
105 if load_environment_variables {
107 config_builder = config_builder
108 .add_source(Environment::with_prefix("MCLI"))
109 .add_source(Environment::with_prefix("MONGODB_ATLAS"));
110 }
111
112 let config = config_builder.build()?;
114
115 let config_version = config
117 .get::<u32>("version")
118 .map_err(|_| LoadCLIConfigError::UnsupportedConfigVersion(0))?;
119 if config_version != 2 {
120 return Err(LoadCLIConfigError::UnsupportedConfigVersion(config_version));
121 }
122
123 let config = config.try_deserialize::<AtlasCLIConfig>()?;
125
126 Ok(config)
127}