use std::path::PathBuf; use clap::{Subcommand, Parser, ValueHint}; use std::env; #[derive(Debug, Parser)] #[command(version, about = "A simple debt manager", long_about = None)] pub struct Cli { /// file path where data is stored [default: /// $XDG_DATA_HOME/debt/debt.db #[arg(short, long, env="DEBT_DB", value_hint = ValueHint::FilePath)] pub database_path: Option, #[command(subcommand)] pub action: Commands } #[derive(Debug, Subcommand)] pub enum Commands { /// Initialize Database Init, /// Register a transaction Register { /// person to register the transaction person: String, /// amount of money amount: u32, /// additional notes note: Option, /// Register the transaction as a payment #[arg(short, long)] payment: bool }, /// View Registered data View { /// Filter history data (only works with -H) filter: Option, /// View register history #[arg(short='H', long, conflicts_with = "total")] history: bool, /// Transaction accumulation by person #[arg(short, long, conflicts_with = "history")] total: bool }, /// Add a new agent to lend or pay Add { name: String, }, } impl Cli { pub fn new() -> Self { let mut cli = Cli::parse(); load_datapath(&mut cli); cli } } fn load_datapath(cli: &mut Cli) { let config_path = cli .database_path .clone() .or_else(|| { xdg::BaseDirectories::with_prefix("debt") .ok() .and_then(|x| { x.find_data_file("cache.db") }) }).or_else(|| { if let Ok(home) = env::var("HOME") { let fallback = PathBuf::from(&home).join(".cache.db"); if fallback.exists() { return Some(fallback) } } None }); cli.database_path = config_path; }