summaryrefslogtreecommitdiffstats
path: root/src/command/stats.rs
blob: 6aa54a2c25c43476ae0e85e04155cae00d4d9670 (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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
use std::collections::HashMap;

use chrono::prelude::*;
use chrono::Duration;
use chrono_english::{parse_date_string, Dialect};

use cli_table::{format::Justify, print_stdout, Cell, Style, Table};
use eyre::{eyre, Result};
use structopt::StructOpt;

use atuin_client::database::Database;
use atuin_client::history::History;
use atuin_client::settings::Settings;

#[derive(StructOpt)]
pub enum Cmd {
    #[structopt(
        about="compute statistics for all of time",
        aliases=&["d", "da"],
    )]
    All,

    #[structopt(
        about="compute statistics for a single day",
        aliases=&["d", "da"],
    )]
    Day { words: Vec<String> },
}

fn compute_stats(history: &[History]) -> Result<()> {
    let mut commands = HashMap::<String, i64>::new();

    for i in history {
        *commands.entry(i.command.clone()).or_default() += 1;
    }

    let most_common_command = commands.iter().max_by(|a, b| a.1.cmp(b.1));

    if most_common_command.is_none() {
        return Err(eyre!("No commands found"));
    }

    let table = vec![
        vec![
            "Most used command".cell(),
            most_common_command
                .unwrap()
                .0
                .cell()
                .justify(Justify::Right),
        ],
        vec![
            "Commands ran".cell(),
            history.len().to_string().cell().justify(Justify::Right),
        ],
        vec![
            "Unique commands ran".cell(),
            commands.len().to_string().cell().justify(Justify::Right),
        ],
    ]
    .table()
    .title(vec![
        "Statistic".cell().bold(true),
        "Value".cell().bold(true),
    ])
    .bold(true);

    print_stdout(table)?;

    Ok(())
}

impl Cmd {
    pub async fn run(
        &self,
        db: &mut (impl Database + Send + Sync),
        settings: &Settings,
    ) -> Result<()> {
        match self {
            Self::Day { words } => {
                let words = if words.is_empty() {
                    String::from("yesterday")
                } else {
                    words.join(" ")
                };

                let start = match settings.dialect.to_lowercase().as_str() {
                    "uk" => parse_date_string(&words, Local::now(), Dialect::Uk)?,
                    _ => parse_date_string(&words, Local::now(), Dialect::Us)?,
                };
                let end = start + Duration::days(1);

                let history = db.range(start.into(), end.into()).await?;

                compute_stats(&history)?;

                Ok(())
            }

            Self::All => {
                let history = db.list(None, false).await?;

                compute_stats(&history)?;

                Ok(())
            }
        }
    }
}