summaryrefslogtreecommitdiffstats
path: root/src/command/client/history.rs
blob: 8767429ba2beecf3fc0f48888c732ebce12e3a70 (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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
use std::{
    env,
    fmt::{self, Display},
    io::{StdoutLock, Write},
    time::Duration,
};

use atuin_common::utils;
use clap::Subcommand;
use eyre::Result;
use runtime_format::{FormatKey, FormatKeyError, ParsedFmt};

use atuin_client::{
    database::{current_context, Database},
    history::History,
    settings::Settings,
};

#[cfg(feature = "sync")]
use atuin_client::sync;
use log::debug;

use super::search::format_duration;
use super::search::format_duration_into;

#[derive(Subcommand)]
#[command(infer_subcommands = true)]
pub enum Cmd {
    /// Begins a new command in the history
    Start { command: Vec<String> },

    /// Finishes a new command in the history (adds time, exit code)
    End {
        id: String,
        #[arg(long, short)]
        exit: i64,
    },

    /// List all items in history
    List {
        #[arg(long, short)]
        cwd: bool,

        #[arg(long, short)]
        session: bool,

        #[arg(long)]
        human: bool,

        /// Show only the text of the command
        #[arg(long)]
        cmd_only: bool,

        /// Available variables: {command}, {directory}, {duration}, {user}, {host} and {time}.
        /// Example: --format "{time} - [{duration}] - {directory}$\t{command}"
        #[arg(long, short)]
        format: Option<String>,
    },

    /// Get the last command ran
    Last {
        #[arg(long)]
        human: bool,

        /// Show only the text of the command
        #[arg(long)]
        cmd_only: bool,

        /// Available variables: {command}, {directory}, {duration}, {user}, {host} and {time}.
        /// Example: --format "{time} - [{duration}] - {directory}$\t{command}"
        #[arg(long, short)]
        format: Option<String>,
    },
}

#[derive(Clone, Copy, Debug)]
pub enum ListMode {
    Human,
    CmdOnly,
    Regular,
}

impl ListMode {
    pub const fn from_flags(human: bool, cmd_only: bool) -> Self {
        if human {
            ListMode::Human
        } else if cmd_only {
            ListMode::CmdOnly
        } else {
            ListMode::Regular
        }
    }
}

#[allow(clippy::cast_sign_loss)]
pub fn print_list<'h>(
    h: impl DoubleEndedIterator<Item = &'h History>,
    list_mode: ListMode,
    format: Option<&str>,
) {
    let w = std::io::stdout();
    let mut w = w.lock();

    match list_mode {
        ListMode::Human => print_human_list(&mut w, h, format),
        ListMode::CmdOnly => print_cmd_only(&mut w, h),
        ListMode::Regular => print_regular(&mut w, h, format),
    }

    w.flush().expect("failed to flush history");
}

/// type wrapper around `History` so we can implement traits
struct FmtHistory<'a>(&'a History);

/// defines how to format the history
impl FormatKey for FmtHistory<'_> {
    #[allow(clippy::cast_sign_loss)]
    fn fmt(&self, key: &str, f: &mut fmt::Formatter<'_>) -> Result<(), FormatKeyError> {
        match key {
            "command" => f.write_str(self.0.command.trim())?,
            "directory" => f.write_str(self.0.cwd.trim())?,
            "exit" => f.write_str(&self.0.exit.to_string())?,
            "duration" => {
                let dur = Duration::from_nanos(std::cmp::max(self.0.duration, 0) as u64);
                format_duration_into(dur, f)?;
            }
            "time" => self.0.timestamp.format("%Y-%m-%d %H:%M:%S").fmt(f)?,
            "relativetime" => {
                let since = chrono::Utc::now() - self.0.timestamp;
                let time = format_duration(since.to_std().unwrap_or_default());
                f.write_str(&time)?;
            }
            "host" => f.write_str(
                self.0
                    .hostname
                    .split_once(':')
                    .map_or(&self.0.hostname, |(host, _)| host),
            )?,
            "user" => f.write_str(self.0.hostname.split_once(':').map_or("", |(_, user)| user))?,
            _ => return Err(FormatKeyError::UnknownKey),
        }
        Ok(())
    }
}

fn print_list_with<'h>(
    w: &mut StdoutLock,
    h: impl DoubleEndedIterator<Item = &'h History>,
    format: &str,
) {
    let fmt = match ParsedFmt::new(format) {
        Ok(fmt) => fmt,
        Err(err) => {
            eprintln!("ERROR: History formatting failed with the following error: {err}");
            println!("If your formatting string contains curly braces (eg: {{var}}) you need to escape them this way: {{{{var}}.");
            std::process::exit(1)
        }
    };

    for h in h.rev() {
        writeln!(w, "{}", fmt.with_args(&FmtHistory(h))).expect("failed to write history");
    }
}

pub fn print_human_list<'h>(
    w: &mut StdoutLock,
    h: impl DoubleEndedIterator<Item = &'h History>,
    format: Option<&str>,
) {
    let format = format
        .unwrap_or("{time} · {duration}\t{command}")
        .replace("\\t", "\t");
    print_list_with(w, h, &format);
}

pub fn print_regular<'h>(
    w: &mut StdoutLock,
    h: impl DoubleEndedIterator<Item = &'h History>,
    format: Option<&str>,
) {
    let format = format
        .unwrap_or("{time}\t{command}\t{duration}")
        .replace("\\t", "\t");
    print_list_with(w, h, &format);
}

pub fn print_cmd_only<'h>(w: &mut StdoutLock, h: impl DoubleEndedIterator<Item = &'h History>) {
    for h in h.rev() {
        writeln!(w, "{}", h.command.trim()).expect("failed to write history");
    }
}

impl Cmd {
    #[allow(clippy::too_many_lines)]
    pub async fn run(&self, settings: &Settings, db: &mut impl Database) -> Result<()> {
        let context = current_context();

        match self {
            Self::Start { command: words } => {
                let command = words.join(" ");

                if command.starts_with(' ') || settings.history_filter.is_match(&command) {
                    return Ok(());
                }

                // It's better for atuin to silently fail here and attempt to
                // store whatever is ran, than to throw an error to the terminal
                let cwd = utils::get_current_dir();

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

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

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

                let mut h = db.load(id).await?;

                if h.duration > 0 {
                    debug!("cannot end history - already has duration");

                    // returning OK as this can occur if someone Ctrl-c a prompt
                    return Ok(());
                }

                h.exit = *exit;
                h.duration = chrono::Utc::now().timestamp_nanos() - h.timestamp.timestamp_nanos();

                db.update(&h).await?;

                if settings.should_sync()? {
                    #[cfg(feature = "sync")]
                    {
                        debug!("running periodic background sync");
                        sync::sync(settings, fals