-
-
Notifications
You must be signed in to change notification settings - Fork 508
/
history.rs
291 lines (245 loc) · 8.62 KB
/
history.rs
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
use std::{
env,
fmt::{self, Display},
io::{StdoutLock, Write},
time::Duration,
};
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_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: &[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())?,
"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)?,
"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(w: &mut StdoutLock, 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.iter().rev() {
writeln!(w, "{}", fmt.with_args(&FmtHistory(h))).expect("failed to write history");
}
}
pub fn print_human_list(w: &mut StdoutLock, 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(w: &mut StdoutLock, 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(w: &mut StdoutLock, h: &[History]) {
for h in h.iter().rev() {
writeln!(w, "{}", h.command.trim()).expect("failed to write history");
}
}
impl Cmd {
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(' ') {
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 = env::current_dir()
.map_or_else(|_| String::new(), |dir| 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).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, false, db).await?;
}
#[cfg(not(feature = "sync"))]
debug!("not compiled with sync support");
} else {
debug!("sync disabled! not syncing");
}
Ok(())
}
Self::List {
session,
cwd,
human,
cmd_only,
format,
} => {
let session = if *session {
Some(env::var("ATUIN_SESSION")?)
} else {
None
};
let cwd = if *cwd {
Some(env::current_dir()?.display().to_string())
} else {
None
};
let history = match (session, cwd) {
(None, None) => db.list(settings.filter_mode, &context, None, false).await?,
(None, Some(cwd)) => {
let query = format!("select * from history where cwd = '{cwd}';");
db.query_history(&query).await?
}
(Some(session), None) => {
let query = format!("select * from history where session = '{session}';");
db.query_history(&query).await?
}
(Some(session), Some(cwd)) => {
let query = format!(
"select * from history where cwd = '{cwd}' and session = '{session}';",
);
db.query_history(&query).await?
}
};
print_list(
&history,
ListMode::from_flags(*human, *cmd_only),
format.as_deref(),
);
Ok(())
}
Self::Last {
human,
cmd_only,
format,
} => {
let last = db.last().await?;
print_list(
&[last],
ListMode::from_flags(*human, *cmd_only),
format.as_deref(),
);
Ok(())
}
}
}
}