Skip to content

Commit

Permalink
new: --config PATH option
Browse files Browse the repository at this point in the history
To use a custom config file path
  • Loading branch information
marcelohdez committed Jun 17, 2024
1 parent 66e4c2d commit e49d8c5
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 11 deletions.
21 changes: 12 additions & 9 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use std::{fs::File, io::read_to_string, process, thread, time::Duration};
use std::{borrow::Cow, fs::File, io::read_to_string, path::Path, process, thread, time::Duration};

use anyhow::{anyhow, bail, Context};
use clap::Parser;
Expand All @@ -20,7 +20,7 @@ fn main() -> anyhow::Result<()> {
return Ok(());
}

let opts = match get_config()? {
let opts = match get_config(args.config.as_deref())? {
Some(config) => config.merge_onto_self(args),
None => args,
};
Expand All @@ -47,20 +47,23 @@ fn main() -> anyhow::Result<()> {
Err(anyhow!("Some user input was detected!"))
}

fn get_config() -> anyhow::Result<Option<DimOpts>> {
let Some(dirs) = ProjectDirs::from("com", "marcelohdez", "dim") else {
fn get_config(dir: Option<&Path>) -> anyhow::Result<Option<DimOpts>> {
let project_dirs = ProjectDirs::from("com", "marcelohdez", "dim");

let Some(dir): Option<Cow<Path>> = dir
.map(Cow::Borrowed)
.or(project_dirs.map(|dirs| Cow::Owned(dirs.config_dir().join(CONFIG_FILENAME))))
else {
bail!("Could not generate project directories on this OS?");
};
let config_dir = dirs.config_dir().join(CONFIG_FILENAME);

if !config_dir.exists() {
if !dir.exists() {
info!("No config found!");
return Ok(None);
}

debug!("Config file found at {config_dir:?}");

let file = File::open(config_dir)?;
debug!("Config file found at {dir:?}");
let file = File::open(dir).context("Failed to open config file")?;
let config: DimOpts = toml::from_str(&read_to_string(file)?)?;

debug!("Config: {config:?}");
Expand Down
6 changes: 4 additions & 2 deletions src/opts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,10 @@ pub struct DimOpts {
#[serde(skip)]
#[arg(long, value_name = "PATH", help = "Generate completions at given path")]
pub gen_completions: Option<PathBuf>,

#[serde(skip)]
#[arg(short, long, value_name = "PATH", help = "Use config at path")]
pub config: Option<PathBuf>,
}

impl DimOpts {
Expand All @@ -39,9 +43,7 @@ impl DimOpts {

Ok(())
}
}

impl DimOpts {
/// Merge other onto self, with other's values taking precedent
pub fn merge_onto_self(self, other: DimOpts) -> Self {
Self {
Expand Down

0 comments on commit e49d8c5

Please sign in to comment.