Config file path

This commit is contained in:
Daniel Flanagan 2024-04-18 08:41:30 -05:00
parent 1cac4fc187
commit 6dca01fed7
4 changed files with 26 additions and 40 deletions

View file

@ -29,7 +29,7 @@ pub struct Cli {
/// The configuration file to load (defaults to $XDG_CONFIG_HOME/taskr/config.toml) /// The configuration file to load (defaults to $XDG_CONFIG_HOME/taskr/config.toml)
#[arg(long, default_value = None)] #[arg(long, default_value = None)]
pub data_directory: Option<String>, pub config_file_path: Option<String>,
} }
#[derive(Subcommand)] #[derive(Subcommand)]

View file

@ -1,6 +1,6 @@
use crate::prelude::*; use crate::prelude::*;
use std::{collections::HashMap, fmt::Debug}; use std::{collections::HashMap, fmt::Debug, path::Path};
use config::{builder::DefaultState, Config as CConfig, ConfigBuilder}; use config::{builder::DefaultState, Config as CConfig, ConfigBuilder};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
@ -20,36 +20,35 @@ pub struct Jira {
#[derive(Serialize, Deserialize, Debug, Clone)] #[derive(Serialize, Deserialize, Debug, Clone)]
pub struct Config { pub struct Config {
pub version: u64, pub version: u64,
pub gitlab: Option<Gitlab>, pub gitlab: Gitlab,
pub jira: Option<Jira>, pub jira: Jira,
} }
const CONFIG_FILE_PATH: &str = "./conf.toml";
impl Config { impl Config {
pub fn load() -> Result<Self> { pub fn load<P>(config_file_path: Option<P>) -> Result<Self>
let c = Self::builder()?.build()?; where
P: AsRef<Path>,
{
let c = Self::builder(config_file_path)?.build()?;
Ok(c.try_deserialize()?) Ok(c.try_deserialize()?)
} }
pub fn builder() -> Result<ConfigBuilder<DefaultState>> { pub fn builder<P>(config_file_path: Option<P>) -> Result<ConfigBuilder<DefaultState>>
let p = std::path::PathBuf::from(CONFIG_FILE_PATH); where
if !p.exists() { P: AsRef<Path>,
// TODO: this won't output since tracing is not setup before we load {
// config, so we need something like let config_file_path: Box<dyn AsRef<Path>> = config_file_path
// https://docs.rs/tracing-capture/latest/tracing_capture/ .as_ref()
// to capture trace events to be output _after_ configuration has .map(|s| Ok::<Box<dyn AsRef<Path>>, anyhow::Error>(Box::new(s.as_ref())))
// loaded and the "actual" subscriber is setup .unwrap_or_else(|| {
warn!( Ok(Box::new(
"Config file '{}' doesn't exist, so defaults will likely be loaded!", xdg::BaseDirectories::new()?.get_config_file("taskr/config.toml"),
p.display(), ))
); })?;
}
// TODO: log whether or not we were able to load conf.toml?
Ok(Self::default_builder() Ok(Self::default_builder()
.map_err(anyhow::Error::from)? .map_err(anyhow::Error::from)?
.add_source(config::File::from(p).required(false)) .add_source(config::File::from((*config_file_path).as_ref()).required(false))
.add_source(config::Environment::with_prefix("taskr").separator("__"))) .add_source(config::Environment::with_prefix("taskr").separator("__")))
} }

View file

@ -19,8 +19,8 @@ use crate::prelude::*;
#[tokio::main] #[tokio::main]
async fn main() -> Result<()> { async fn main() -> Result<()> {
let conf = Config::load()?;
let cli = Cli::new(); let cli = Cli::new();
let conf = Config::load(cli.config_file_path)?;
// this guard causes logs to be flushed when dropped (which is at the end of // this guard causes logs to be flushed when dropped (which is at the end of
// this function which would be the end of our program) // this function which would be the end of our program)

View file

@ -108,14 +108,8 @@ impl Tasks {
token token
} }
}; };
let result = GitLab::try_new( let result =
&format!( GitLab::try_new(&format!("{}/api/v4", self.config.gitlab.url), &gl_token)?;
"{}/api/v4",
self.config
.require_or_prompt_and_set::<String>("gitlab.url")?
),
&gl_token,
)?;
let _ = self.gitlab.set(result); let _ = self.gitlab.set(result);
Ok(self.gitlab.get().unwrap()) Ok(self.gitlab.get().unwrap())
// TODO: ensure the token works? // TODO: ensure the token works?
@ -158,14 +152,7 @@ impl Tasks {
} }
}; };
let result = Jira::try_new( let result = Jira::try_new(&format!("{}", self.config.jira.url), &jira_token)?;
&format!(
"{}",
self.config
.require_or_prompt_and_set::<String>("jira.url")?
),
&jira_token,
)?;
let _ = self.jira.set(result); let _ = self.jira.set(result);
Ok(self.jira.get().unwrap()) Ok(self.jira.get().unwrap())
// TODO: ensure the token works? // TODO: ensure the token works?