aboutsummaryrefslogtreecommitdiff
path: root/src/cli.rs
blob: 38ac648a39567b7e40b6a851010be3e57bd81dfb (plain)
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
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 history data (only works with -H)
        filter: Option<String>,
        /// 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;
}
Feel free to download, copy and edit any repo