aboutsummaryrefslogtreecommitdiffstats
path: root/src/command/history.rs
blob: 2b691bacc43fe7eee7e0b8e7373aca2163fdcf19 (plain) (blame)
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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
use std::env;

use eyre::Result;
use fork::{fork, Fork};
use structopt::StructOpt;

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

#[derive(StructOpt)]
pub enum Cmd {
    #[structopt(
        about="begins a new command in the history",
        aliases=&["s", "st", "sta", "star"],
    )]
    Start { command: Vec<String> },

    #[structopt(
        about="finishes a new command in the history (adds time, exit code)",
        aliases=&["e", "en"],
    )]
    End {
        id: String,
        #[structopt(long, short)]
        exit: i64,
    },

    #[structopt(
        about="list all items in history",
        aliases=&["l", "li", "lis"],
    )]
    List {
        #[structopt(long, short)]
        cwd: bool,

        #[structopt(long, short)]
        session: bool,
    },

    #[structopt(
        about="search for a command",
        aliases=&["se", "sea", "sear", "searc"],
    )]
    Search { query: Vec<String> },
}

fn print_list(h: &[History]) {
    for i in h {
        println!("{}", i.command);
    }
}

impl Cmd {
    pub async fn run(&self, settings: &Settings, db: &mut (impl Database + Send)) -> Result<()> {
        match self {
            Self::Start { command: words } => {
                let command = words.join(" ");
                let cwd = env::current_dir()?.display().to_string();

                let h = History::new(chrono::Utc::now(), command, cwd, -1, -1, None, None);

                // print the ID
                // we use this as the key for calling end
                println!("{}", h.id);
                db.save(&h)?;
                Ok(())
            }

            Self::End { id, exit } => {
                if id.trim() == "" {
                    return Ok(());
                }

                let mut h = db.load(id)?;
                h.exit = *exit;
                h.duration = chrono::Utc::now().timestamp_nanos() - h.timestamp.timestamp_nanos();

                db.update(&h)?;

                if settings.should_sync()? {
                    match fork() {
                        Ok(Fork::Parent(child)) => {
                            debug!("launched sync background process with PID {}", child);
                        }
                        Ok(Fork::Child) => {
                            debug!("running periodic background sync");
                            sync::sync(settings, false, db).await?;
                        }
                        Err(_) => println!("Fork failed"),
                    }
                }

                Ok(())
            }

            Self::List { session, cwd, .. } => {
                const QUERY_SESSION: &str = "select * from history where session = ?;";
                const QUERY_DIR: &str = "select * from history where cwd = ?;";
                const QUERY_SESSION_DIR: &str =
                    "select * from history where cwd = ?1 and session = ?2;";

                let params = (session, cwd);

                let cwd = env::current_dir()?.display().to_string();
                let session = env::var("ATUIN_SESSION")?;

                let history = match params {
                    (false, false) => db.list()?,
                    (true, false) => db.query(QUERY_SESSION, &[session.as_str()])?,
                    (false, true) => db.query(QUERY_DIR, &[cwd.as_str()])?,
                    (true, true) => {
                        db.query(QUERY_SESSION_DIR, &[cwd.as_str(), session.as_str()])?
                    }
                };

                print_list(&history);

                Ok(())
            }

            Self::Search { query } => {
                let history = db.prefix_search(&query.join(""))?;
                print_list(&history);

                Ok(())
            }
        }
    }
}