|
1 | 1 | 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}; |
4 | 7 |
|
5 | 8 | #[derive(Parser)]
|
6 | 9 | #[command(version, about, long_about = None)]
|
7 | 10 | pub struct Cli {
|
8 | 11 | /// 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, |
11 | 20 |
|
12 | 21 | #[command(flatten)]
|
13 | 22 | logging: Logging,
|
@@ -42,6 +51,21 @@ enum Commands {
|
42 | 51 | Source(ManageSources),
|
43 | 52 | }
|
44 | 53 |
|
| 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 | + |
45 | 69 | #[cfg(test)]
|
46 | 70 | mod tests {
|
47 | 71 | use super::*;
|
|
0 commit comments