Skip to content

Commit b95820c

Browse files
committed
Add default configuration path
1 parent 96d2958 commit b95820c

File tree

2 files changed

+29
-5
lines changed

2 files changed

+29
-5
lines changed

Cargo.toml

+1-1
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ edition = "2021"
88
[dependencies]
99
async-trait = "0.1.79"
1010
chrono = "0.4.37"
11-
clap = { version = "4.5.4", features = ["derive"] }
11+
clap = { version = "4.5.4", features = ["derive", "env", "string"] }
1212
figment = { version = "0.10.16", features = ["toml"] }
1313
reqwest = { version = "0.12.2", features = ["json"] }
1414
serde = { version = "1.0.197", features = ["derive"] }

src/cli/main.rs

+28-4
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,22 @@
11
use super::{manage_signers::ManageSigners, manage_sources::ManageSources};
2-
use clap::{Args, Parser, Subcommand};
3-
use std::path::PathBuf;
2+
use clap::{
3+
builder::{OsStr, Resettable},
4+
Args, Parser, Subcommand,
5+
};
6+
use std::{env, path::PathBuf};
47

58
#[derive(Parser)]
69
#[command(version, about, long_about = None)]
710
pub struct Cli {
811
/// The path to the configuration file.
9-
#[arg(short, long, value_name = "FILE")]
10-
config: Option<PathBuf>,
12+
#[arg(
13+
short,
14+
long,
15+
value_name = "FILE",
16+
env = "HANKO_CONFIG",
17+
default_value = default_config_path()
18+
)]
19+
pub config: PathBuf,
1120

1221
#[command(flatten)]
1322
logging: Logging,
@@ -42,6 +51,21 @@ enum Commands {
4251
Source(ManageSources),
4352
}
4453

54+
/// The default configuration file path according to the XDG Base Directory Specification.
55+
/// If neither `$XDG_CONFIG_HOME` nor `$HOME` are set, `Resettable::Reset` is returned, forcing the user to specify the path.
56+
fn default_config_path() -> Resettable<OsStr> {
57+
let dirname = env!("CARGO_PKG_NAME");
58+
let filename = "config.toml";
59+
60+
if let Ok(xdg_config_home) = env::var("XDG_CONFIG_HOME") {
61+
Resettable::Value(format!("{}/{}/{}", xdg_config_home, dirname, filename).into())
62+
} else if let Ok(home) = env::var("HOME") {
63+
Resettable::Value(format!("{}/.config/{}/{}", home, dirname, filename).into())
64+
} else {
65+
Resettable::Reset
66+
}
67+
}
68+
4569
#[cfg(test)]
4670
mod tests {
4771
use super::*;

0 commit comments

Comments
 (0)