Skip to content

Commit

Permalink
Fix more errors
Browse files Browse the repository at this point in the history
  • Loading branch information
pvshvp-oss committed May 11, 2024
1 parent 3c45305 commit a63e994
Show file tree
Hide file tree
Showing 3 changed files with 57 additions and 134 deletions.
88 changes: 30 additions & 58 deletions paxy/src/app/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ lazy_static! {
/// local paths. overridden by environment variables starting with `PAXY_`,
/// overridden by the configuration file specified by the commandline.
/// Values from only files with supported file extensions would be merged.
pub fn init_config<G>(cli_global_arguments: G) -> Result<(ConfigTemplate, Vec<PathBuf>), Error>
pub fn init_config<G>(console_global_arguments: &G) -> Result<(ConfigTemplate, Vec<PathBuf>), Error>
where
G: ui::GlobalArguments,
{
Expand Down Expand Up @@ -45,50 +45,33 @@ where
let mut config = Config::new();

// Merge configuration values from global and local filepaths
config.with_overriding_files(candidate_config_filepaths);
config = config.with_overriding_files(&candidate_config_filepaths);

// Merge configuration values from environment variables
config.with_overriding_env(&format!("{}_", *app::APP_NAME));
config = config.with_overriding_env(&format!("{}_", *app::APP_NAME));

// Merge configuration values from the CLI
config.with_overriding_args(cli_global_arguments);
config = config.with_overriding_args(console_global_arguments);

Ok((
config
.object()
.context(ExtractConfigSnafu {})?,
.object()?,
candidate_config_filepaths,
))
}

fn admerge_from_stub(candidate_config_filepath_stub: &PathBuf, mut figment: Figment) -> Figment {
figment = figment.admerge(Toml::file(
candidate_config_filepath_stub.with_extension("toml"),
));
figment = figment.admerge(Json::file(
candidate_config_filepath_stub.with_extension("json"),
));
figment = figment.admerge(Yaml::file(
candidate_config_filepath_stub.with_extension("yml"),
));
figment = figment.admerge(Yaml::file(
candidate_config_filepath_stub.with_extension("yaml"),
));
figment
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ConfigTemplate {
pub config_filepaths: Vec<PathBuf>,
pub log_filepath_stub: PathBuf,
pub log_dirpath: PathBuf,
pub console_output_format: ui::ConsoleOutputFormat,
}

impl Default for ConfigTemplate {
fn default() -> Self {
Self {
config_filepaths: Vec::new(),
log_filepath_stub: PathBuf::default(),
log_dirpath: PathBuf::default(),
console_output_format: ui::ConsoleOutputFormat::default(),
}
}
Expand All @@ -101,11 +84,11 @@ pub struct Config {
impl Config {
pub fn new() -> Self {
Self {
figment: Figment::from(ConfigTemplate::default()),
figment: Figment::new(),
}
}

pub fn with_overriding_file<P: AsRef<Path>>(&mut self, filepath: P) -> &mut Self {
pub fn with_overriding_file<P: AsRef<Path>>(mut self, filepath: P) -> Self {
let filepath: &Path = filepath.as_ref();
if let Some(file_extension) = filepath.extension() {
file_extension = file_extension
Expand Down Expand Up @@ -133,60 +116,56 @@ impl Config {
self
}

pub fn with_overriding_files<P, I>(&mut self, filepaths: I) -> &mut Self
pub fn with_overriding_files<P, I>(self, filepaths: I) -> Self
where
P: AsRef<Path>,
I: Iterator<Item = P>,
I: IntoIterator<Item = P>,
{
filepaths.for_each(|filepath| self.with_overriding_file(filepath));

self
filepaths.into_iter().fold(self, |config, filepath| config.with_overriding_file(filepath))
}

pub fn with_overriding_filepath_stubs<I1, I2, S, P>(
&mut self,
mut self,
file_extensions: I1,
filepath_stubs: I2,
) -> &mut Self
) -> Self
where
I1: IntoIterator<Item = S>,
S: AsRef<str>,
I2: IntoIterator<Item = P>,
P: Into<PathBuf>,
{
let filepath_stubs: Iterator<Item = PathBuf> = filepath_stubs
let filepath_stubs = filepath_stubs
.into_iter()
.map(Into::into);
file_extensions
.into_iter()
.map(AsRef::as_ref)
.cartesian_product(filepath_stubs)
.map(|file_extension| file_extension.as_ref())
.cartesian_product(&filepath_stubs)
.map(|(file_extension, filepath_stub)| {
let filepath = filepath_stub;
filepath.set_extension(file_extension);

self.with_overriding_file(filepath);
self = self.with_overriding_file(filepath);
});

self
}

pub fn with_overriding_filepath_stub<I, S, P>(
&mut self,
self,
file_extensions: I,
filepath_stub: P,
) -> &mut Self
) -> Self
where
I: IntoIterator<Item = S>,
S: AsRef<str>,
P: Into<PathBuf>,
{
self.with_overriding_filepath_stubs(file_extensions, iter::once(filepath_stub));

self
self.with_overriding_filepath_stubs(file_extensions, iter::once(filepath_stub))
}

pub fn with_overriding_env<S: AsRef<str>>(&mut self, prefix: S) -> &mut Self {
pub fn with_overriding_env<S: AsRef<str>>(mut self, prefix: S) -> Self {
let prefix = prefix.as_ref();
self.figment = self
.figment
Expand All @@ -198,23 +177,18 @@ impl Config {
/// Merge configuration values from the CLI
/// These are not set to be optional, so only action-required states are
/// merged with the configuration
pub fn with_overriding_args<A: ui::GlobalArguments>(
&mut self,
console_arguments: A,
) -> &mut Self {
pub fn with_overriding_args<A: ui::GlobalArguments>(mut self, console_arguments: A) -> Self {
// Incorporate the extra config file specified through arguments
if let Some(path) = console_arguments.config_filepath() {
self.figment = self
.figment
self.figment = self.figment
.admerge(("config_filepaths", path));
}

// Override console output mode from console arguments only if a
// non-regular output mode is explicitly specified
let console_output_mode = console_arguments.console_output_mode();
if console_output_mode != ConsoleOutputMode::Regular {
self.figment = self
.figment
self.figment = self.figment
.admerge(("console_output_format.mode", console_output_mode));
}

Expand All @@ -226,8 +200,7 @@ impl Config {
let requested_max_verbosity = console_arguments.max_output_verbosity();
if let Ok(current_max_verbosity) = current_max_verbosity {
if requested_max_verbosity > current_max_verbosity {
self.figment = self
.figment
self.figment = self.figment
.admerge((
"console_output_format.max_verbosity",
requested_max_verbosity,
Expand All @@ -250,18 +223,17 @@ impl Config {
String::from(*app::APP_NAME).to_uppercase()
))
.is_ok()
|| env::var("TERM").is_ok_and(|env_term_value| env_term_value.to_lowercase == "dumb");
|| env::var("TERM").is_ok_and(|env_term_value| env_term_value.to_lowercase() == "dumb");
if (requested_no_color || env_no_color) && !current_no_color.unwrap_or(false) {
self.figment = self
.figment
self.figment = self.figment
.admerge(("console_output_format.no_color", true));
}

self
}

pub fn object(&self) -> Result<ConfigTemplate, Error> {
let mut config_object = self
let mut config_object: ConfigTemplate = self
.figment
.extract()
.context(ExtractConfigSnafu {})?;
Expand Down Expand Up @@ -291,7 +263,7 @@ use lazy_static::lazy_static;
use serde::{Deserialize, Serialize};
use snafu::{OptionExt, ResultExt, Snafu};

use super::ui::{ConsoleOutputMode, GlobalArguments};
use super::ui::ConsoleOutputMode;
use crate::app;
use crate::app::ui;

Expand Down
28 changes: 12 additions & 16 deletions paxy/src/app/logging.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
pub fn init_log(config: &config::ConfigTemplate) -> Result<(Handle, PathBuf), Error> {
let log_filename = format!("{}.log", *app::APP_NAME);
let log_dirpath = obtain_log_dirpath(config.log_dirpath)?;
let log_dirpath = obtain_log_dirpath(config.log_dirpath.clone())?;
let log_file_appender =
tracing_appender::rolling::daily(log_dirpath.clone(), log_filename.clone());
let log_level_filter = tracing_level_filter_from_log_level_filter(
Expand Down Expand Up @@ -156,7 +156,7 @@ pub fn init_log(config: &config::ConfigTemplate) -> Result<(Handle, PathBuf), Er
))
}

fn obtain_log_dirpath(preferred_log_dirpath: Option<PathBuf>) -> Result<PathBuf, Error> {
fn obtain_log_dirpath(preferred_log_dirpath: PathBuf) -> Result<PathBuf, Error> {
let obtain_fallback_log_dirpath = || {
let xdg_app_dirs =
directories::BaseDirs::new().context(RetreiveLoggingUserAppBaseDirectoriesSnafu {})?;
Expand All @@ -173,20 +173,16 @@ fn obtain_log_dirpath(preferred_log_dirpath: Option<PathBuf>) -> Result<PathBuf,
.data_dir()
.to_owned())
};
Ok(match preferred_log_dirpath {
Some(preferred_log_dirpath) => {
if !fs::metadata(&preferred_log_dirpath)
.map(|m| m.permissions())
.map(|p| p.readonly())
.unwrap_or(true)
{
preferred_log_dirpath
} else {
obtain_fallback_log_dirpath()?
}
}
None => obtain_fallback_log_dirpath()?,
})

if !fs::metadata(&preferred_log_dirpath)
.map(|m| m.permissions())
.map(|p| p.readonly())
.unwrap_or(true)
{
Ok(preferred_log_dirpath)
} else {
Ok(obtain_fallback_log_dirpath()?)
}
}

fn tracing_level_filter_from_log_level_filter(level_filter: log::LevelFilter) -> LevelFilter {
Expand Down
Loading

0 comments on commit a63e994

Please sign in to comment.