1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
|
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<PathBuf>,
#[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<String>,
/// Register the transaction as a payment
#[arg(short, long)]
payment: bool
},
/// View Registered data
View {
/// Filter registers by agent
agent: Option<String>,
/// View register history
#[arg(short='H', long, conflicts_with = "total")]
history: bool,
/// Sum registers by agent
#[arg(short, long, conflicts_with = "history")]
total: bool,
/// Filter registers by note (sql match syntax)
#[arg(short='n', long)]
filter_note: Option<Vec<String>>,
/// Filter registers by month
#[arg(short='m', long)]
month: Option<String>,
},
/// Add, update or remove an agent
Agent {
name: String,
/// Add a new agent (default)
#[arg(short,long)]
add: bool,
/// Delete a registered agent
#[arg(short,long, conflicts_with_all = ["add", "update"])]
delete: bool,
/// Update a registered agent
#[arg(short,long, conflicts_with_all = ["add", "delete"], value_name = "NEW_NAME")]
update: Option<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;
}
|