cli: extract function that reads user config without merging

The next commit will add a struct that keeps umerged configs, which will be
used to insert repo config between user and override configs.
This commit is contained in:
Yuya Nishihara 2023-01-05 13:34:10 +09:00
parent b3c792f7bf
commit 47e2e4d220

View file

@ -13,7 +13,7 @@
// limitations under the License.
use std::borrow::Cow;
use std::path::PathBuf;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::{env, fmt};
@ -124,12 +124,7 @@ fn env_overrides() -> config::Config {
builder.build().unwrap()
}
pub fn read_config() -> Result<UserSettings, ConfigError> {
let mut config_builder = config::Config::builder()
.add_source(default_config())
.add_source(env_base());
if let Some(config_path) = config_path()? {
fn read_config_path(config_path: &Path) -> Result<config::Config, config::ConfigError> {
let mut files = vec![];
if config_path.is_dir() {
if let Ok(read_dir) = config_path.read_dir() {
@ -143,19 +138,30 @@ pub fn read_config() -> Result<UserSettings, ConfigError> {
}
files.sort();
} else {
files.push(config_path);
files.push(config_path.to_owned());
}
for file in files {
files
.iter()
.fold(config::Config::builder(), |builder, path| {
// TODO: Accept other formats and/or accept only certain file extensions?
config_builder = config_builder.add_source(
config::File::from(file)
builder.add_source(
config::File::from(path.as_ref())
.required(false)
.format(config::FileFormat::Toml),
);
)
})
.build()
}
};
let config = config_builder.add_source(env_overrides()).build()?;
pub fn read_config() -> Result<UserSettings, ConfigError> {
let mut config_builder = config::Config::builder()
.add_source(default_config())
.add_source(env_base());
if let Some(path) = config_path()? {
config_builder = config_builder.add_source(read_config_path(&path)?);
}
let config = config_builder.add_source(env_overrides()).build().unwrap();
Ok(UserSettings::from_config(config))
}