repo
string | pull_number
int64 | instance_id
string | issue_numbers
list | base_commit
string | patch
string | test_patch
string | problem_statement
string | hints_text
string | created_at
string | version
string | updated_at
string | environment_setup_commit
string | FAIL_TO_PASS
list | PASS_TO_PASS
list | FAIL_TO_FAIL
list | PASS_TO_FAIL
list | source_dir
string |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
dtolnay/async-trait
| 90
|
dtolnay__async-trait-90
|
[
"89"
] |
05c24928d08c46ee1a916b1dff7f6dd389b21c94
|
diff --git a/src/expand.rs b/src/expand.rs
--- a/src/expand.rs
+++ b/src/expand.rs
@@ -342,8 +342,17 @@ fn transform_block(
};
}
Context::Impl { receiver, .. } => {
+ let mut ty = quote!(#receiver);
+ if let Type::TraitObject(trait_object) = receiver {
+ if trait_object.dyn_token.is_none() {
+ ty = quote!(dyn #ty);
+ }
+ if trait_object.bounds.len() > 1 {
+ ty = quote!((#ty));
+ }
+ }
*arg = parse_quote! {
- #under_self: &#lifetime #mutability #receiver
+ #under_self: &#lifetime #mutability #ty
};
}
}
|
diff --git a/tests/test.rs b/tests/test.rs
--- a/tests/test.rs
+++ b/tests/test.rs
@@ -622,3 +622,30 @@ pub mod issue87 {
}
}
}
+
+// https://github.com/dtolnay/async-trait/issues/89
+pub mod issue89 {
+ #![allow(bare_trait_objects)]
+
+ use async_trait::async_trait;
+
+ #[async_trait]
+ trait Trait {
+ async fn f(&self);
+ }
+
+ #[async_trait]
+ impl Trait for Send + Sync {
+ async fn f(&self) {}
+ }
+
+ #[async_trait]
+ impl Trait for dyn Fn(i8) + Send + Sync {
+ async fn f(&self) {}
+ }
+
+ #[async_trait]
+ impl Trait for (dyn Fn(u8) + Send + Sync) {
+ async fn f(&self) {}
+ }
+}
diff --git /dev/null b/tests/ui/bare-trait-object.rs
new file mode 100644
--- /dev/null
+++ b/tests/ui/bare-trait-object.rs
@@ -0,0 +1,15 @@
+#![deny(bare_trait_objects)]
+
+use async_trait::async_trait;
+
+#[async_trait]
+trait Trait {
+ async fn f(&self);
+}
+
+#[async_trait]
+impl Trait for Send + Sync {
+ async fn f(&self) {}
+}
+
+fn main() {}
diff --git /dev/null b/tests/ui/bare-trait-object.stderr
new file mode 100644
--- /dev/null
+++ b/tests/ui/bare-trait-object.stderr
@@ -0,0 +1,11 @@
+error: trait objects without an explicit `dyn` are deprecated
+ --> $DIR/bare-trait-object.rs:11:16
+ |
+11 | impl Trait for Send + Sync {
+ | ^^^^^^^^^^^ help: use `dyn`: `dyn Send + Sync`
+ |
+note: the lint level is defined here
+ --> $DIR/bare-trait-object.rs:1:9
+ |
+1 | #![deny(bare_trait_objects)]
+ | ^^^^^^^^^^^^^^^^^^
|
Forgetting "dyn" before Fn() + Trait causes panic
In non-async-trait code, this is currently legal, though it emits a warning that it should have the `dyn` keyword:
```
impl<F> Foo for Fn(i8) -> F + Send + Sync
where F: ... {}
```
In async-trait code, this causes a panic:
```
#[async_trait::async_trait]
impl<F> RequestHandler for Fn(&Request) -> F + Send + Sync
where F: ... {}
```
```
error: custom attribute panicked
--> src/lib.rs:15:1
|
15 | #[async_trait::async_trait]
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
= help: message: unexpected token
```
[A full example in the Playground](https://play.rust-lang.org/?version=nightly&mode=debug&edition=2018&gist=9807f69a0c79b48c21cafb6c9b84357f)
I'm not sure whether the code should be *accepted*, given that the current compiler warns that the `impl` w/o the `dyn` is deprecated, but I figure `async_trait` might want to either accept w/ a similar warning, or at the very least reject with a clearer error message.
(I mostly stumbled into this; I do not think the `impl` is anything _close_ to what I actually want in my real-world use case. The compiler's insistence on `dyn` is nice though, since it clued me in that I'm barking up the wrong syntactical tree.)
|
2020-04-07T03:09:00Z
|
0.1
|
2020-04-07T03:12:34Z
|
f8e5bb43181450a17068f160e8a51d410ede1705
|
[
"src/lib.rs - (line 10)",
"src/lib.rs - (line 160)",
"src/lib.rs - (line 121)",
"src/lib.rs - (line 281)",
"src/lib.rs - (line 181)",
"src/lib.rs - (line 260)",
"src/lib.rs - (line 42)",
"src/lib.rs - (line 206)"
] |
[] |
[] |
[] |
auto_2025-06-06
|
|
dtolnay/async-trait
| 160
|
dtolnay__async-trait-160
|
[
"158"
] |
6bff4e0c5935b30b4d5af42bb06d9972866c752d
|
diff --git a/src/receiver.rs b/src/receiver.rs
--- a/src/receiver.rs
+++ b/src/receiver.rs
@@ -2,7 +2,7 @@ use proc_macro2::{Group, Span, TokenStream, TokenTree};
use std::iter::FromIterator;
use syn::visit_mut::{self, VisitMut};
use syn::{
- Block, ExprPath, Ident, Item, Macro, Pat, PatIdent, PatPath, Receiver, Signature, Token,
+ Block, ExprPath, Ident, Item, Macro, Pat, PatIdent, PatPath, Path, Receiver, Signature, Token,
TypePath,
};
diff --git a/src/receiver.rs b/src/receiver.rs
--- a/src/receiver.rs
+++ b/src/receiver.rs
@@ -139,6 +139,16 @@ impl VisitMut for ReplaceSelf {
self.prepend_underscore_to_self(i);
}
+ fn visit_path_mut(&mut self, p: &mut Path) {
+ if p.segments.len() == 1 {
+ // Replace `self`, but not `self::function`.
+ self.visit_ident_mut(&mut p.segments[0].ident);
+ }
+ for segment in &mut p.segments {
+ self.visit_path_arguments_mut(&mut segment.arguments);
+ }
+ }
+
fn visit_item_mut(&mut self, i: &mut Item) {
// Visit `macro_rules!` because locally defined macros can refer to
// `self`. Otherwise, do not recurse into nested items.
|
diff --git a/tests/test.rs b/tests/test.rs
--- a/tests/test.rs
+++ b/tests/test.rs
@@ -1321,3 +1321,17 @@ pub mod issue154 {
}
}
}
+
+// https://github.com/dtolnay/async-trait/issues/158
+pub mod issue158 {
+ use async_trait::async_trait;
+
+ fn f() {}
+
+ #[async_trait]
+ pub trait Trait {
+ async fn f(&self) {
+ self::f()
+ }
+ }
+}
|
Failed to resolve `self` in path
Macro doesn't handle when `self` is used as path.
```rust
use async_trait::async_trait; // 0.1.48
fn bar() {}
#[async_trait]
trait Foo {
async fn bar(&self) {
self::bar()
}
}
```
```rust
error[E0433]: failed to resolve: use of undeclared crate or module `__self`
--> src/lib.rs:8:9
|
8 | self::bar()
| ^^^^ use of undeclared crate or module `__self`
```
[Playground](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=9567f3a7c893e1eb8da5256043246c9b)
|
2021-04-14T06:06:02Z
|
0.1
|
2021-04-14T06:09:19Z
|
f8e5bb43181450a17068f160e8a51d410ede1705
|
[
"drop_order::test_drop_order",
"issue45::tracing",
"src/lib.rs - (line 15)",
"src/lib.rs - (line 165)",
"src/lib.rs - (line 126)",
"src/lib.rs - (line 186)",
"src/lib.rs - (line 286)",
"src/lib.rs - (line 265)",
"src/lib.rs - (line 47)",
"src/lib.rs - (line 211)"
] |
[] |
[] |
[] |
auto_2025-06-06
|
|
dtolnay/async-trait
| 150
|
dtolnay__async-trait-150
|
[
"149"
] |
2c4cde7ce826c77fe08a8f67d6fdc47b023adf0f
|
diff --git a/src/expand.rs b/src/expand.rs
--- a/src/expand.rs
+++ b/src/expand.rs
@@ -350,6 +350,9 @@ fn transform_block(sig: &mut Signature, block: &mut Block) {
let _: () = { #(#decls)* #(#stmts)* };
},
ReturnType::Type(_, ret) => quote_spanned! {block.brace_token.span=>
+ if let ::core::option::Option::Some(__ret) = ::core::option::Option::None::<#ret> {
+ return __ret;
+ }
let __ret: #ret = { #(#decls)* #(#stmts)* };
#[allow(unreachable_code)]
__ret
|
diff --git a/tests/test.rs b/tests/test.rs
--- a/tests/test.rs
+++ b/tests/test.rs
@@ -1258,3 +1258,23 @@ pub mod issue147 {
}
}
}
+
+// https://github.com/dtolnay/async-trait/issues/149
+pub mod issue149 {
+ use async_trait::async_trait;
+
+ pub struct Thing;
+ pub trait Ret {}
+ impl Ret for Thing {}
+
+ pub async fn ok() -> &'static dyn Ret {
+ return &Thing;
+ }
+
+ #[async_trait]
+ pub trait Trait {
+ async fn fail() -> &'static dyn Ret {
+ return &Thing;
+ }
+ }
+}
|
Unsize coercion fails if end of method is unreachable
The following async trait fails to compile. Notice that the same method body is fine in an ordinary async fn outside of an async trait.
This worked prior to #143.
```rust
use async_trait::async_trait;
struct Thing;
trait Ret {}
impl Ret for Thing {}
async fn ok() -> &'static dyn Ret {
return &Thing;
}
#[async_trait]
trait Trait {
async fn fail() -> &'static dyn Ret {
return &Thing;
}
}
```
```console
error[E0308]: mismatched types
--> src/main.rs:13:41
|
13 | async fn fail() -> &'static dyn Ret {
| _________________________________________^
14 | | return &Thing;
15 | | }
| |_____^ expected struct `Thing`, found trait object `dyn Ret`
|
= note: expected type `&Thing`
found reference `&'static (dyn Ret + 'static)`
note: return type inferred to be `&Thing` here
--> src/main.rs:14:16
|
14 | return &Thing;
| ^^^^^^
error[E0271]: type mismatch resolving `<impl Future as Future>::Output == &'static (dyn Ret + 'static)`
--> src/main.rs:13:41
|
13 | async fn fail() -> &'static dyn Ret {
| _________________________________________^
14 | | return &Thing;
15 | | }
| |_____^ expected trait object `dyn Ret`, found struct `Thing`
|
= note: expected reference `&'static (dyn Ret + 'static)`
found reference `&Thing`
= note: required for the cast to the object type `dyn Future<Output = &'static (dyn Ret + 'static)> + Send`
```
|
2021-03-07T05:06:30Z
|
0.1
|
2021-03-07T05:12:13Z
|
f8e5bb43181450a17068f160e8a51d410ede1705
|
[
"issue45::tracing",
"drop_order::test_drop_order",
"src/lib.rs - (line 15)",
"src/lib.rs - (line 165)",
"src/lib.rs - (line 286)",
"src/lib.rs - (line 211)",
"src/lib.rs - (line 186)",
"src/lib.rs - (line 47)",
"src/lib.rs - (line 265)",
"src/lib.rs - (line 126)"
] |
[] |
[] |
[] |
auto_2025-06-06
|
|
dtolnay/async-trait
| 227
|
dtolnay__async-trait-227
|
[
"226"
] |
6050c94ca7be287be1657fcefd299165e39c7ef2
|
diff --git a/src/expand.rs b/src/expand.rs
--- a/src/expand.rs
+++ b/src/expand.rs
@@ -362,6 +362,12 @@ fn transform_block(context: Context, sig: &mut Signature, block: &mut Block) {
quote!(let #mutability #ident = #self_token;)
}
FnArg::Typed(arg) => {
+ // If there is a `#[cfg(..)]` attribute that selectively
+ // enables the parameter, forward it to the variable.
+ //
+ // This is currently not applied to the `self` parameter
+ let attrs = arg.attrs.iter();
+
if let Pat::Ident(PatIdent {
ident, mutability, ..
}) = &*arg.pat
diff --git a/src/expand.rs b/src/expand.rs
--- a/src/expand.rs
+++ b/src/expand.rs
@@ -371,15 +377,24 @@ fn transform_block(context: Context, sig: &mut Signature, block: &mut Block) {
let prefixed = Ident::new("__self", ident.span());
quote!(let #mutability #prefixed = #ident;)
} else {
- quote!(let #mutability #ident = #ident;)
+ quote!(
+ #(#attrs)*
+ let #mutability #ident = #ident;
+ )
}
} else {
let pat = &arg.pat;
let ident = positional_arg(i, pat);
if let Pat::Wild(_) = **pat {
- quote!(let #ident = #ident;)
+ quote!(
+ #(#attrs)*
+ let #ident = #ident;
+ )
} else {
- quote!(let #pat = #ident;)
+ quote!(
+ #(#attrs)*
+ let #pat = #ident;
+ )
}
}
}
|
diff --git a/tests/test.rs b/tests/test.rs
--- a/tests/test.rs
+++ b/tests/test.rs
@@ -54,6 +54,10 @@ trait Trait {
async fn calls_mut(&mut self) {
self.selfmut().await;
}
+
+ async fn cfg_param(&self, param: u8);
+ async fn cfg_param_wildcard(&self, _: u8);
+ async fn cfg_param_tuple(&self, (left, right): (u8, u8));
}
struct Struct;
diff --git a/tests/test.rs b/tests/test.rs
--- a/tests/test.rs
+++ b/tests/test.rs
@@ -87,6 +91,17 @@ impl Trait for Struct {
async fn calls_mut(&mut self) {
self.selfmut().await;
}
+
+ async fn cfg_param(&self, #[cfg(any())] param: u8, #[cfg(all())] _unused: u8) {}
+
+ async fn cfg_param_wildcard(&self, #[cfg(any())] _: u8, #[cfg(all())] _: u8) {}
+
+ async fn cfg_param_tuple(
+ &self,
+ #[cfg(any())] (left, right): (u8, u8),
+ #[cfg(all())] (_left, _right): (u8, u8),
+ ) {
+ }
}
pub async fn test() {
|
Attributes on impl parameters are not forwarded to body
Heya, I was implementing a trait function with `#[cfg(..)]` in its parameters, and encountered the following error:
```rust
// within trait impl
async fn cfg_param(
&self,
#[cfg(not(feature = "something"))] param: u8,
#[cfg(feature = "something")] _unused: u8,
// ^^^^^^^
// cannot find value `_unused` in this scope
) -> u8 {
#[cfg(not(feature = "something"))]
{ param }
#[cfg(feature = "something")]
{ 1 }
}
```
The expanded code body shows:
```rust
let __self = self;
let param = param;
let _unused = _unused;
let __ret: u8 = { #[cfg(not(feature = "something"))] { param } };
#[allow(unreachable_code)] __ret
```
Since `_unused` is not present in the function signature, the expanded code should likely just omit it.
#227 forwards the attributes, such that the expanded code returns:
```rust
let __self = self;
#[cfg(not(feature = "something"))]
let param = param;
let __ret: u8 = { #[cfg(not(feature = "something"))] { param } };
#[allow(unreachable_code)] __ret
```
The `_unused` statement isn't present since it's been removed by the expansion.
|
2023-01-06T01:44:31Z
|
0.1
|
2023-01-06T22:57:17Z
|
f8e5bb43181450a17068f160e8a51d410ede1705
|
[
"drop_order::test_drop_order",
"issue199::test",
"issue45::tracing",
"src/lib.rs - (line 15) - compile fail",
"src/lib.rs - (line 165) - compile fail",
"src/lib.rs - (line 126)",
"src/lib.rs - (line 186)",
"src/lib.rs - (line 265)",
"src/lib.rs - (line 286)",
"src/lib.rs - (line 47)",
"src/lib.rs - (line 211)"
] |
[] |
[] |
[] |
auto_2025-06-06
|
|
dtolnay/async-trait
| 223
|
dtolnay__async-trait-223
|
[
"210"
] |
9ed6489ee0cedf31fef8a06a1dcd1f18b4afdd39
|
diff --git a/src/expand.rs b/src/expand.rs
--- a/src/expand.rs
+++ b/src/expand.rs
@@ -9,9 +9,9 @@ use std::mem;
use syn::punctuated::Punctuated;
use syn::visit_mut::{self, VisitMut};
use syn::{
- parse_quote, parse_quote_spanned, Attribute, Block, FnArg, GenericParam, Generics, Ident,
- ImplItem, Lifetime, LifetimeDef, Pat, PatIdent, Receiver, ReturnType, Signature, Stmt, Token,
- TraitItem, Type, TypePath, WhereClause,
+ parse_quote, parse_quote_spanned, Attribute, Block, FnArg, GenericArgument, GenericParam,
+ Generics, Ident, ImplItem, Lifetime, LifetimeDef, Pat, PatIdent, PathArguments, Receiver,
+ ReturnType, Signature, Stmt, Token, TraitItem, Type, TypePath, WhereClause,
};
impl ToTokens for Item {
diff --git a/src/expand.rs b/src/expand.rs
--- a/src/expand.rs
+++ b/src/expand.rs
@@ -229,23 +229,46 @@ fn transform_sig(
.push(parse_quote_spanned!(default_span=> 'async_trait));
if has_self {
- let bounds = match sig.inputs.iter().next() {
+ let bounds: &[InferredBound] = match sig.inputs.iter().next() {
Some(FnArg::Receiver(Receiver {
reference: Some(_),
mutability: None,
..
- })) => [InferredBound::Sync],
+ })) => &[InferredBound::Sync],
Some(FnArg::Typed(arg))
- if match (arg.pat.as_ref(), arg.ty.as_ref()) {
- (Pat::Ident(pat), Type::Reference(ty)) => {
- pat.ident == "self" && ty.mutability.is_none()
- }
+ if match arg.pat.as_ref() {
+ Pat::Ident(pat) => pat.ident == "self",
_ => false,
} =>
{
- [InferredBound::Sync]
+ match arg.ty.as_ref() {
+ // self: &Self
+ Type::Reference(ty) if ty.mutability.is_none() => &[InferredBound::Sync],
+ // self: Arc<Self>
+ Type::Path(ty)
+ if {
+ let segment = ty.path.segments.last().unwrap();
+ segment.ident == "Arc"
+ && match &segment.arguments {
+ PathArguments::AngleBracketed(arguments) => {
+ arguments.args.len() == 1
+ && match &arguments.args[0] {
+ GenericArgument::Type(Type::Path(arg)) => {
+ arg.path.is_ident("Self")
+ }
+ _ => false,
+ }
+ }
+ _ => false,
+ }
+ } =>
+ {
+ &[InferredBound::Sync, InferredBound::Send]
+ }
+ _ => &[InferredBound::Send],
+ }
}
- _ => [InferredBound::Send],
+ _ => &[InferredBound::Send],
};
let bounds = bounds.iter().filter_map(|bound| {
|
diff --git a/tests/test.rs b/tests/test.rs
--- a/tests/test.rs
+++ b/tests/test.rs
@@ -1450,3 +1450,14 @@ pub mod issue204 {
async fn g(arg: *const impl Trait);
}
}
+
+// https://github.com/dtolnay/async-trait/issues/210
+pub mod issue210 {
+ use async_trait::async_trait;
+ use std::sync::Arc;
+
+ #[async_trait]
+ pub trait Trait {
+ async fn f(self: Arc<Self>) {}
+ }
+}
|
Defaulted method with `self: Arc<Self>` doesn't work
`Arc` generates a `where Self: Send` bound, but for `Arc` it is not enough - it requires also `T: Sync` to be `Send`. This make the following code failing to compile:
```rust
#[async_trait]
trait Trait {
async fn foo(self: Arc<Self>) {}
}
```
https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=add1c3d15459405538a453e3c9a504a6
```
error: future cannot be sent between threads safely
--> src/lib.rs:7:35
|
7 | async fn foo(self: Arc<Self>) {}
| ^^ future created by async block is not `Send`
|
note: captured value is not `Send`
--> src/lib.rs:7:18
|
7 | async fn foo(self: Arc<Self>) {}
| ^^^^ has type `Arc<Self>` which is not `Send`
= note: required for the cast to the object type `dyn Future<Output = ()> + Send`
```
[Adding `Sync` as a supertrait works](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=0c2bccdc20c8df461d014bd9a25b131e), but ideally the macro should also add a `Self: Sync` bound (even though I don't know how it can identify `Arc` being used), or at least document that.
|
2022-11-29T08:05:19Z
|
0.1
|
2022-11-29T08:11:36Z
|
f8e5bb43181450a17068f160e8a51d410ede1705
|
[
"drop_order::test_drop_order",
"issue199::test",
"issue45::tracing",
"src/lib.rs - (line 165) - compile fail",
"src/lib.rs - (line 15) - compile fail",
"src/lib.rs - (line 126)",
"src/lib.rs - (line 286)",
"src/lib.rs - (line 265)",
"src/lib.rs - (line 186)",
"src/lib.rs - (line 47)",
"src/lib.rs - (line 211)"
] |
[] |
[] |
[] |
auto_2025-06-06
|
|
dtolnay/async-trait
| 201
|
dtolnay__async-trait-201
|
[
"177"
] |
9a323ed6dad1dfc651147814d4d418cf09d6e17b
|
diff --git a/Cargo.toml b/Cargo.toml
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -17,7 +17,7 @@ proc-macro = true
[dependencies]
proc-macro2 = "1.0"
quote = "1.0"
-syn = { version = "1.0.84", features = ["full", "visit-mut"] }
+syn = { version = "1.0.96", features = ["full", "visit-mut"] }
[dev-dependencies]
futures = "0.3"
diff --git a/src/expand.rs b/src/expand.rs
--- a/src/expand.rs
+++ b/src/expand.rs
@@ -1,4 +1,4 @@
-use crate::lifetime::CollectLifetimes;
+use crate::lifetime::{AddLifetimeToImplTrait, CollectLifetimes};
use crate::parse::Item;
use crate::receiver::{has_self_in_block, has_self_in_sig, mut_pat, ReplaceSelf};
use proc_macro2::TokenStream;
diff --git a/src/expand.rs b/src/expand.rs
--- a/src/expand.rs
+++ b/src/expand.rs
@@ -283,6 +283,7 @@ fn transform_sig(
let m = mut_pat(&mut arg.pat);
arg.pat = parse_quote!(#m #positional);
}
+ AddLifetimeToImplTrait.visit_type_mut(&mut arg.ty);
}
}
}
diff --git a/src/lifetime.rs b/src/lifetime.rs
--- a/src/lifetime.rs
+++ b/src/lifetime.rs
@@ -1,6 +1,8 @@
use proc_macro2::Span;
use syn::visit_mut::{self, VisitMut};
-use syn::{GenericArgument, Lifetime, Receiver, TypeReference};
+use syn::{
+ parse_quote_spanned, Expr, GenericArgument, Lifetime, Receiver, TypeImplTrait, TypeReference,
+};
pub struct CollectLifetimes {
pub elided: Vec<Lifetime>,
diff --git a/src/lifetime.rs b/src/lifetime.rs
--- a/src/lifetime.rs
+++ b/src/lifetime.rs
@@ -62,3 +64,22 @@ impl VisitMut for CollectLifetimes {
visit_mut::visit_generic_argument_mut(self, gen);
}
}
+
+pub struct AddLifetimeToImplTrait;
+
+impl VisitMut for AddLifetimeToImplTrait {
+ fn visit_type_impl_trait_mut(&mut self, ty: &mut TypeImplTrait) {
+ let span = ty.impl_token.span;
+ let lifetime = parse_quote_spanned!(span=> 'async_trait);
+ ty.bounds.insert(0, lifetime);
+ if let Some(punct) = ty.bounds.pairs_mut().next().unwrap().punct_mut() {
+ punct.span = span;
+ }
+ }
+
+ fn visit_expr_mut(&mut self, _e: &mut Expr) {
+ // Do not recurse into impl Traits inside of an array length expression.
+ //
+ // fn outer(arg: [u8; { fn inner(_: impl Trait) {}; 0 }]);
+ }
+}
|
diff --git a/tests/test.rs b/tests/test.rs
--- a/tests/test.rs
+++ b/tests/test.rs
@@ -1374,6 +1374,23 @@ pub mod issue169 {
pub fn test(_t: &dyn Trait) {}
}
+// https://github.com/dtolnay/async-trait/issues/177
+pub mod issue177 {
+ use async_trait::async_trait;
+
+ #[async_trait]
+ pub trait Trait {
+ async fn foo(&self, _callback: impl FnMut(&str) + Send) {}
+ }
+
+ pub struct Struct;
+
+ #[async_trait]
+ impl Trait for Struct {
+ async fn foo(&self, _callback: impl FnMut(&str) + Send) {}
+ }
+}
+
// https://github.com/dtolnay/async-trait/issues/183
pub mod issue183 {
#![deny(clippy::shadow_same)]
|
Lifetime issue when using "impl FnMut" as argument type
**Case 1:**
```rust
async fn foo(&self, mut callback: impl FnMut(&str) + Send)
```
expands to:
```rust
fn foo<'life0, 'life1, 'async_trait>(
&'life0 self,
callback: impl FnMut(&'life1 str) + Send,
) -> ::core::pin::Pin<
Box<dyn ::core::future::Future<Output = ()> + ::core::marker::Send + 'async_trait>,
>
where
'life0: 'async_trait,
'life1: 'async_trait,
Self: ::core::marker::Sync + 'async_trait,
```
which is not functioning as expected.
**Case 2**:
```rust
async fn foo<C: FnMut(&str) + Send>(&self, mut callback: C)
```
works however.
The Rust reference states for [anonymous type parameters](https://doc.rust-lang.org/stable/reference/types/impl-trait.html#anonymous-type-parameters):
> That is, `impl Trait` in argument position is syntactic sugar for a generic type parameter like `<T: Trait>`, except that the type is anonymous and doesn't appear in the *GenericParams* list.
It can thus be very surprising that Case 2 is alright, but Case 1 fails.
See also [this discussion](https://users.rust-lang.org/t/surprising-behavior-with-async-trait-impl-trait-in-argument-position/65827) in the Rust users Forum for an idea what should/could be done about it.
Alternatively, this surprising behavior could be mentioned in the documentation.
|
I would accept a PR to support this as suggested in the forum thread (`callback: impl 'async_trait + FnMut(&str) + Send`).
|
2022-06-02T20:27:22Z
|
0.1
|
2022-06-02T20:33:38Z
|
f8e5bb43181450a17068f160e8a51d410ede1705
|
[
"drop_order::test_drop_order",
"issue45::tracing",
"src/lib.rs - (line 15) - compile fail",
"src/lib.rs - (line 165) - compile fail",
"src/lib.rs - (line 126)",
"src/lib.rs - (line 186)",
"src/lib.rs - (line 286)",
"src/lib.rs - (line 265)",
"src/lib.rs - (line 47)",
"src/lib.rs - (line 211)"
] |
[] |
[] |
[] |
auto_2025-06-06
|
dtolnay/async-trait
| 143
|
dtolnay__async-trait-143
|
[
"126"
] |
c490ccdd4d81ea19523f47bd48f8a384f3026375
|
diff --git a/Cargo.toml b/Cargo.toml
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -24,5 +24,8 @@ tracing-attributes = "0.1.8"
tracing-futures = "0.2"
trybuild = { version = "1.0.19", features = ["diff"] }
+[build-dependencies]
+version_check = "0.9"
+
[package.metadata.docs.rs]
targets = ["x86_64-unknown-linux-gnu"]
diff --git /dev/null b/build.rs
new file mode 100644
--- /dev/null
+++ b/build.rs
@@ -0,0 +1,5 @@
+fn main() {
+ if let Some(true) = version_check::is_max_version("1.46") {
+ println!("cargo:rustc-cfg=self_span_hack");
+ }
+}
diff --git a/src/expand.rs b/src/expand.rs
--- a/src/expand.rs
+++ b/src/expand.rs
@@ -1,19 +1,23 @@
-use crate::lifetime::{has_async_lifetime, CollectLifetimes};
+use crate::lifetime::CollectLifetimes;
use crate::parse::Item;
-use crate::receiver::{
- has_self_in_block, has_self_in_sig, has_self_in_where_predicate, ReplaceReceiver,
-};
+use crate::receiver::{ mut_pat, has_self_in_block, has_self_in_sig, ReplaceSelf};
use proc_macro2::{Span, TokenStream};
use quote::{format_ident, quote, quote_spanned, ToTokens};
-use std::mem;
use syn::punctuated::Punctuated;
+use syn::spanned::Spanned;
use syn::visit_mut::VisitMut;
use syn::{
parse_quote, Block, FnArg, GenericParam, Generics, Ident, ImplItem, Lifetime, Pat, PatIdent,
- Path, Receiver, ReturnType, Signature, Stmt, Token, TraitItem, Type, TypeParam, TypeParamBound,
+ Receiver, ReturnType, Signature, Stmt, Token, TraitItem, Type, TypeParamBound,
WhereClause,
};
+macro_rules! parse_quote_spanned {
+ ($span:expr => $($t:tt)*) => (
+ syn::parse2(quote_spanned!($span => $($t)*)).unwrap()
+ )
+}
+
impl ToTokens for Item {
fn to_tokens(&self, tokens: &mut TokenStream) {
match self {
diff --git a/src/expand.rs b/src/expand.rs
--- a/src/expand.rs
+++ b/src/expand.rs
@@ -26,14 +30,11 @@ impl ToTokens for Item {
#[derive(Clone, Copy)]
enum Context<'a> {
Trait {
- name: &'a Ident,
generics: &'a Generics,
supertraits: &'a Supertraits,
},
Impl {
impl_generics: &'a Generics,
- receiver: &'a Type,
- as_trait: &'a Path,
},
}
diff --git a/src/expand.rs b/src/expand.rs
--- a/src/expand.rs
+++ b/src/expand.rs
@@ -51,15 +52,33 @@ impl Context<'_> {
}
})
}
+
+ fn generics_span(&self) -> Span {
+ match self {
+ Context::Trait { generics, .. } => generics.span(),
+ Context::Impl { impl_generics } => impl_generics.span(),
+ }
+ }
}
type Supertraits = Punctuated<TypeParamBound, Token![+]>;
pub fn expand(input: &mut Item, is_local: bool) {
+ let inner_method_attrs = &[
+ parse_quote!(#[allow(clippy::used_underscore_binding)]),
+ parse_quote!(#[allow(clippy::type_repetition_in_bounds)]),
+ parse_quote!(#[allow(clippy::let_unit_value)]),
+ ];
+
+ let trait_method_attrs = &[
+ parse_quote!(#[must_use]),
+ parse_quote!(#[allow(clippy::type_repetition_in_bounds)]),
+ parse_quote!(#[allow(clippy::let_unit_value)]),
+ ];
+
match input {
Item::Trait(input) => {
let context = Context::Trait {
- name: &input.ident,
generics: &input.generics,
supertraits: &input.supertraits,
};
diff --git a/src/expand.rs b/src/expand.rs
--- a/src/expand.rs
+++ b/src/expand.rs
@@ -71,20 +90,18 @@ pub fn expand(input: &mut Item, is_local: bool) {
let mut has_self = has_self_in_sig(sig);
if let Some(block) = block {
has_self |= has_self_in_block(block);
- transform_block(context, sig, block, has_self, is_local);
- method
- .attrs
- .push(parse_quote!(#[allow(clippy::used_underscore_binding)]));
+ transform_block(sig, block);
+ method.attrs.extend_from_slice(inner_method_attrs);
}
let has_default = method.default.is_some();
transform_sig(context, sig, has_self, has_default, is_local);
- method.attrs.push(parse_quote!(#[must_use]));
+ method.attrs.extend_from_slice(trait_method_attrs);
}
}
}
}
Item::Impl(input) => {
- let mut lifetimes = CollectLifetimes::new("'impl");
+ let mut lifetimes = CollectLifetimes::new("'impl", input.generics.span());
lifetimes.visit_type_mut(&mut *input.self_ty);
lifetimes.visit_path_mut(&mut input.trait_.as_mut().unwrap().1);
let params = &input.generics.params;
diff --git a/src/expand.rs b/src/expand.rs
--- a/src/expand.rs
+++ b/src/expand.rs
@@ -93,8 +110,6 @@ pub fn expand(input: &mut Item, is_local: bool) {
let context = Context::Impl {
impl_generics: &input.generics,
- receiver: &input.self_ty,
- as_trait: &input.trait_.as_ref().unwrap().1,
};
for inner in &mut input.items {
if let ImplItem::Method(method) = inner {
diff --git a/src/expand.rs b/src/expand.rs
--- a/src/expand.rs
+++ b/src/expand.rs
@@ -102,11 +117,9 @@ pub fn expand(input: &mut Item, is_local: bool) {
if sig.asyncness.is_some() {
let block = &mut method.block;
let has_self = has_self_in_sig(sig) || has_self_in_block(block);
- transform_block(context, sig, block, has_self, is_local);
+ transform_block(sig, block);
transform_sig(context, sig, has_self, false, is_local);
- method
- .attrs
- .push(parse_quote!(#[allow(clippy::used_underscore_binding)]));
+ method.attrs.extend_from_slice(inner_method_attrs);
}
}
}
diff --git a/src/expand.rs b/src/expand.rs
--- a/src/expand.rs
+++ b/src/expand.rs
@@ -141,7 +154,11 @@ fn transform_sig(
ReturnType::Type(_, ret) => quote!(#ret),
};
- let mut lifetimes = CollectLifetimes::new("'life");
+ let default_span = sig.ident.span()
+ .join(sig.paren_token.span)
+ .unwrap_or_else(|| sig.ident.span());
+
+ let mut lifetimes = CollectLifetimes::new("'life", default_span);
for arg in sig.inputs.iter_mut() {
match arg {
FnArg::Receiver(arg) => lifetimes.visit_receiver_mut(arg),
diff --git a/src/expand.rs b/src/expand.rs
--- a/src/expand.rs
+++ b/src/expand.rs
@@ -149,13 +166,6 @@ fn transform_sig(
}
}
- let where_clause = sig
- .generics
- .where_clause
- .get_or_insert_with(|| WhereClause {
- where_token: Default::default(),
- predicates: Punctuated::new(),
- });
for param in sig
.generics
.params
diff --git a/src/expand.rs b/src/expand.rs
--- a/src/expand.rs
+++ b/src/expand.rs
@@ -165,33 +175,41 @@ fn transform_sig(
match param {
GenericParam::Type(param) => {
let param = ¶m.ident;
- where_clause
+ let span = param.span();
+ where_clause_or_default(&mut sig.generics.where_clause)
.predicates
- .push(parse_quote!(#param: 'async_trait));
+ .push(parse_quote_spanned!(span => #param: 'async_trait));
}
GenericParam::Lifetime(param) => {
let param = ¶m.lifetime;
- where_clause
+ let span = param.span();
+ where_clause_or_default(&mut sig.generics.where_clause)
.predicates
- .push(parse_quote!(#param: 'async_trait));
+ .push(parse_quote_spanned!(span => #param: 'async_trait));
}
GenericParam::Const(_) => {}
}
}
+
for elided in lifetimes.elided {
- sig.generics.params.push(parse_quote!(#elided));
- where_clause
+ push_param(&mut sig.generics, parse_quote!(#elided));
+ where_clause_or_default(&mut sig.generics.where_clause)
.predicates
- .push(parse_quote!(#elided: 'async_trait));
+ .push(parse_quote_spanned!(elided.span() => #elided: 'async_trait));
}
- sig.generics.params.push(parse_quote!('async_trait));
+
+ push_param(&mut sig.generics, parse_quote_spanned!(default_span => 'async_trait));
+
+ let first_bound = where_clause_or_default(&mut sig.generics.where_clause).predicates.first();
+ let bound_span = first_bound.map_or(default_span, Spanned::span);
+
if has_self {
let bound: Ident = match sig.inputs.iter().next() {
Some(FnArg::Receiver(Receiver {
reference: Some(_),
mutability: None,
..
- })) => parse_quote!(Sync),
+ })) => parse_quote_spanned!(bound_span => Sync),
Some(FnArg::Typed(arg))
if match (arg.pat.as_ref(), arg.ty.as_ref()) {
(Pat::Ident(pat), Type::Reference(ty)) => {
diff --git a/src/expand.rs b/src/expand.rs
--- a/src/expand.rs
+++ b/src/expand.rs
@@ -200,18 +218,21 @@ fn transform_sig(
_ => false,
} =>
{
- parse_quote!(Sync)
+ parse_quote_spanned!(bound_span => Sync)
}
- _ => parse_quote!(Send),
+ _ => parse_quote_spanned!(bound_span => Send),
};
+
let assume_bound = match context {
Context::Trait { supertraits, .. } => !has_default || has_bound(supertraits, &bound),
Context::Impl { .. } => true,
};
+
+ let where_clause = where_clause_or_default(&mut sig.generics.where_clause);
where_clause.predicates.push(if assume_bound || is_local {
- parse_quote!(Self: 'async_trait)
+ parse_quote_spanned!(bound_span => Self: 'async_trait)
} else {
- parse_quote!(Self: ::core::marker::#bound + 'async_trait)
+ parse_quote_spanned!(bound_span => Self: ::core::marker::#bound + 'async_trait)
});
}
diff --git a/src/expand.rs b/src/expand.rs
--- a/src/expand.rs
+++ b/src/expand.rs
@@ -226,17 +247,19 @@ fn transform_sig(
ident.by_ref = None;
ident.mutability = None;
} else {
- let positional = positional_arg(i);
- *arg.pat = parse_quote!(#positional);
+ let span = arg.pat.span();
+ let positional = positional_arg(i, span);
+ let m = mut_pat(&mut arg.pat);
+ arg.pat = parse_quote!(#m #positional);
}
}
}
}
let bounds = if is_local {
- quote!('async_trait)
+ quote_spanned!(context.generics_span() => 'async_trait)
} else {
- quote!(::core::marker::Send + 'async_trait)
+ quote_spanned!(context.generics_span() => ::core::marker::Send + 'async_trait)
};
sig.output = parse_quote! {
diff --git a/src/expand.rs b/src/expand.rs
--- a/src/expand.rs
+++ b/src/expand.rs
@@ -247,21 +270,25 @@ fn transform_sig(
}
// Input:
-// async fn f<T>(&self, x: &T) -> Ret {
-// self + x
+// async fn f<T>(&self, x: &T, (a, b): (A, B)) -> Ret {
+// self + x + a + b
// }
//
// Output:
-// async fn f<T, AsyncTrait>(_self: &AsyncTrait, x: &T) -> Ret {
-// _self + x
-// }
-// Box::pin(async_trait_method::<T, Self>(self, x))
+// Box::pin(async move {
+// let ___ret: Ret = {
+// let __self = self;
+// let x = x;
+// let (a, b) = __arg1;
+//
+// __self + x + a + b
+// };
+//
+// ___ret
+// })
fn transform_block(
- context: Context,
sig: &mut Signature,
block: &mut Block,
- has_self: bool,
- is_local: bool,
) {
if let Some(Stmt::Item(syn::Item::Verbatim(item))) = block.stmts.first() {
if block.stmts.len() == 1 && item.to_string() == ";" {
diff --git a/src/expand.rs b/src/expand.rs
--- a/src/expand.rs
+++ b/src/expand.rs
@@ -269,225 +296,61 @@ fn transform_block(
}
}
- let inner = format_ident!("__{}", sig.ident);
- let args = sig.inputs.iter().enumerate().map(|(i, arg)| match arg {
- FnArg::Receiver(Receiver { self_token, .. }) => quote!(#self_token),
- FnArg::Typed(arg) => {
- if let Pat::Ident(PatIdent { ident, .. }) = &*arg.pat {
- quote!(#ident)
- } else {
- positional_arg(i).into_token_stream()
- }
- }
- });
-
- let mut standalone = sig.clone();
- standalone.ident = inner.clone();
-
- let generics = match context {
- Context::Trait { generics, .. } => generics,
- Context::Impl { impl_generics, .. } => impl_generics,
- };
-
- let mut outer_generics = generics.clone();
- for p in &mut outer_generics.params {
- match p {
- GenericParam::Type(t) => t.default = None,
- GenericParam::Const(c) => c.default = None,
- GenericParam::Lifetime(_) => {}
- }
- }
- if !has_self {
- if let Some(mut where_clause) = outer_generics.where_clause {
- where_clause.predicates = where_clause
- .predicates
- .into_iter()
- .filter_map(|mut pred| {
- if has_self_in_where_predicate(&mut pred) {
- None
- } else {
- Some(pred)
- }
- })
- .collect();
- outer_generics.where_clause = Some(where_clause);
- }
- }
-
- let fn_generics = mem::replace(&mut standalone.generics, outer_generics);
- standalone.generics.params.extend(fn_generics.params);
- if let Some(where_clause) = fn_generics.where_clause {
- standalone
- .generics
- .make_where_clause()
- .predicates
- .extend(where_clause.predicates);
- }
-
- if has_async_lifetime(&mut standalone, block) {
- standalone.generics.params.push(parse_quote!('async_trait));
- }
-
- let mut types = standalone
- .generics
- .type_params()
- .map(|param| param.ident.clone())
- .collect::<Vec<_>>();
-
- let mut self_bound = None::<TypeParamBound>;
- match standalone.inputs.iter_mut().next() {
- Some(
- arg @ FnArg::Receiver(Receiver {
- reference: Some(_), ..
- }),
- ) => {
- let (lifetime, mutability, self_token) = match arg {
- FnArg::Receiver(Receiver {
- reference: Some((_, lifetime)),
- mutability,
- self_token,
- ..
- }) => (lifetime, mutability, self_token),
- _ => unreachable!(),
- };
- let under_self = Ident::new("_self", self_token.span);
- match context {
- Context::Trait { .. } => {
- self_bound = Some(match mutability {
- Some(_) => parse_quote!(::core::marker::Send),
- None => parse_quote!(::core::marker::Sync),
- });
- *arg = parse_quote! {
- #under_self: &#lifetime #mutability AsyncTrait
- };
- }
- Context::Impl { receiver, .. } => {
- let mut ty = quote!(#receiver);
- if let Type::TraitObject(trait_object) = receiver {
- if trait_object.dyn_token.is_none() {
- ty = quote!(dyn #ty);
- }
- if trait_object.bounds.len() > 1 {
- ty = quote!((#ty));
- }
- }
- *arg = parse_quote! {
- #under_self: &#lifetime #mutability #ty
- };
- }
- }
- }
- Some(arg @ FnArg::Receiver(_)) => {
- let (self_token, mutability) = match arg {
- FnArg::Receiver(Receiver {
- self_token,
- mutability,
- ..
- }) => (self_token, mutability),
- _ => unreachable!(),
- };
- let under_self = Ident::new("_self", self_token.span);
- match context {
- Context::Trait { .. } => {
- self_bound = Some(parse_quote!(::core::marker::Send));
- *arg = parse_quote! {
- #mutability #under_self: AsyncTrait
- };
- }
- Context::Impl { receiver, .. } => {
- *arg = parse_quote! {
- #mutability #under_self: #receiver
- };
- }
- }
+ let self_prefix = "__";
+ let mut self_span = None;
+ let decls = sig.inputs.iter().enumerate().map(|(i, arg)| match arg {
+ FnArg::Receiver(Receiver { self_token, mutability, .. }) => {
+ let mut ident = format_ident!("{}self", self_prefix);
+ ident.set_span(self_token.span());
+ self_span = Some(self_token.span());
+ quote!(let #mutability #ident = #self_token;)
}
- Some(FnArg::Typed(arg)) => {
- if let Pat::Ident(arg) = &mut *arg.pat {
- if arg.ident == "self" {
- arg.ident = Ident::new("_self", arg.ident.span());
+ FnArg::Typed(arg) => {
+ if let Pat::Ident(PatIdent { ident, mutability, .. }) = &*arg.pat {
+ if ident == "self" {
+ self_span = Some(ident.span());
+ let prefixed = format_ident!("{}{}", self_prefix, ident);
+ quote!(let #mutability #prefixed = #ident;)
+ } else {
+ quote!(let #mutability #ident = #ident;)
}
+ } else {
+ let pat = &arg.pat;
+ let ident = positional_arg(i, pat.span());
+ quote!(let #pat = #ident;)
}
}
- _ => {}
- }
-
- if let Context::Trait { name, generics, .. } = context {
- if has_self {
- let (_, generics, _) = generics.split_for_impl();
- let mut self_param: TypeParam = parse_quote!(AsyncTrait: ?Sized + #name #generics);
- if !is_local {
- self_param.bounds.extend(self_bound);
- }
- let count = standalone
- .generics
- .params
- .iter()
- .take_while(|param| {
- if let GenericParam::Const(_) = param {
- false
- } else {
- true
- }
- })
- .count();
- standalone
- .generics
- .params
- .insert(count, GenericParam::Type(self_param));
- types.push(Ident::new("Self", Span::call_site()));
- }
- }
+ }).collect::<Vec<_>>();
- if let Some(where_clause) = &mut standalone.generics.where_clause {
- // Work around an input bound like `where Self::Output: Send` expanding
- // to `where <AsyncTrait>::Output: Send` which is illegal syntax because
- // `where<T>` is reserved for future use... :(
- where_clause.predicates.insert(0, parse_quote!((): Sized));
+ if let Some(span) = self_span {
+ let mut replace_self = ReplaceSelf(self_prefix, span);
+ replace_self.visit_block_mut(block);
}
- let mut replace = match context {
- Context::Trait { .. } => ReplaceReceiver::with(parse_quote!(AsyncTrait)),
- Context::Impl {
- receiver, as_trait, ..
- } => ReplaceReceiver::with_as_trait(receiver.clone(), as_trait.clone()),
+ let stmts = &block.stmts;
+ let ret_ty = match &sig.output {
+ ReturnType::Default => quote_spanned!(block.span()=>()),
+ ReturnType::Type(_, ret) => quote!(#ret),
};
- replace.visit_signature_mut(&mut standalone);
- replace.visit_block_mut(block);
- let mut generics = types;
- let consts = standalone
- .generics
- .const_params()
- .map(|param| param.ident.clone());
- generics.extend(consts);
+ let box_pin = quote_spanned!(ret_ty.span()=>
+ Box::pin(async move {
+ let __ret: #ret_ty = {
+ #(#decls)*
+ let __async_trait: ();
+ #(#stmts)*
+ };
- let allow_non_snake_case = if sig.ident != sig.ident.to_string().to_lowercase() {
- Some(quote!(non_snake_case,))
- } else {
- None
- };
+ #[allow(unreachable_code)]
+ __ret
+ })
+ );
- let brace = block.brace_token;
- let box_pin = quote_spanned!(brace.span=> {
- #[allow(
- #allow_non_snake_case
- unused_parens, // https://github.com/dtolnay/async-trait/issues/118
- clippy::missing_docs_in_private_items,
- clippy::needless_lifetimes,
- clippy::ptr_arg,
- clippy::trivially_copy_pass_by_ref,
- clippy::type_repetition_in_bounds,
- clippy::used_underscore_binding,
- )]
- #standalone #block
- Box::pin(#inner::<#(#generics),*>(#(#args),*))
- });
- *block = parse_quote!(#box_pin);
- block.brace_token = brace;
+ block.stmts = parse_quote!(#box_pin);
}
-fn positional_arg(i: usize) -> Ident {
- format_ident!("__arg{}", i)
+fn positional_arg(i: usize, span: Span) -> Ident {
+ format_ident!("__arg{}", i, span = span)
}
fn has_bound(supertraits: &Supertraits, marker: &Ident) -> bool {
diff --git a/src/expand.rs b/src/expand.rs
--- a/src/expand.rs
+++ b/src/expand.rs
@@ -500,3 +363,20 @@ fn has_bound(supertraits: &Supertraits, marker: &Ident) -> bool {
}
false
}
+
+fn where_clause_or_default(clause: &mut Option<WhereClause>) -> &mut WhereClause {
+ clause.get_or_insert_with(|| WhereClause {
+ where_token: Default::default(),
+ predicates: Punctuated::new(),
+ })
+}
+
+fn push_param(generics: &mut Generics, param: GenericParam) {
+ let span = param.span();
+ if generics.params.is_empty() {
+ generics.lt_token = parse_quote_spanned!(span => <);
+ generics.gt_token = parse_quote_spanned!(span => >);
+ }
+
+ generics.params.push(param);
+}
diff --git a/src/lib.rs b/src/lib.rs
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -321,7 +321,6 @@ mod expand;
mod lifetime;
mod parse;
mod receiver;
-mod respan;
use crate::args::Args;
use crate::expand::expand;
diff --git a/src/lifetime.rs b/src/lifetime.rs
--- a/src/lifetime.rs
+++ b/src/lifetime.rs
@@ -1,59 +1,44 @@
use proc_macro2::Span;
+use syn::spanned::Spanned;
use syn::visit_mut::{self, VisitMut};
-use syn::{Block, GenericArgument, Item, Lifetime, Receiver, Signature, TypeReference};
-
-pub fn has_async_lifetime(sig: &mut Signature, block: &mut Block) -> bool {
- let mut visitor = HasAsyncLifetime(false);
- visitor.visit_signature_mut(sig);
- visitor.visit_block_mut(block);
- visitor.0
-}
-
-struct HasAsyncLifetime(bool);
-
-impl VisitMut for HasAsyncLifetime {
- fn visit_lifetime_mut(&mut self, life: &mut Lifetime) {
- self.0 |= life.to_string() == "'async_trait";
- }
-
- fn visit_item_mut(&mut self, _: &mut Item) {
- // Do not recurse into nested items.
- }
-}
+use syn::{GenericArgument, Lifetime, Receiver, TypeReference};
pub struct CollectLifetimes {
pub elided: Vec<Lifetime>,
pub explicit: Vec<Lifetime>,
pub name: &'static str,
+ pub default_span: Span,
}
impl CollectLifetimes {
- pub fn new(name: &'static str) -> Self {
+ pub fn new(name: &'static str, default_span: Span) -> Self {
CollectLifetimes {
elided: Vec::new(),
explicit: Vec::new(),
name,
+ default_span,
}
}
fn visit_opt_lifetime(&mut self, lifetime: &mut Option<Lifetime>) {
match lifetime {
- None => *lifetime = Some(self.next_lifetime()),
+ None => *lifetime = Some(self.next_lifetime(None)),
Some(lifetime) => self.visit_lifetime(lifetime),
}
}
fn visit_lifetime(&mut self, lifetime: &mut Lifetime) {
if lifetime.ident == "_" {
- *lifetime = self.next_lifetime();
+ *lifetime = self.next_lifetime(lifetime.span());
} else {
self.explicit.push(lifetime.clone());
}
}
- fn next_lifetime(&mut self) -> Lifetime {
+ fn next_lifetime<S: Into<Option<Span>>>(&mut self, span: S) -> Lifetime {
let name = format!("{}{}", self.name, self.elided.len());
- let life = Lifetime::new(&name, Span::call_site());
+ let span = span.into().unwrap_or(self.default_span);
+ let life = Lifetime::new(&name, span);
self.elided.push(life.clone());
life
}
diff --git a/src/receiver.rs b/src/receiver.rs
--- a/src/receiver.rs
+++ b/src/receiver.rs
@@ -1,14 +1,8 @@
-use crate::respan::respan;
-use proc_macro2::{Group, Spacing, Span, TokenStream, TokenTree};
-use quote::{quote, quote_spanned};
-use std::iter::FromIterator;
-use std::mem;
-use syn::punctuated::Punctuated;
+use proc_macro2::{Group, Span, TokenStream, TokenTree};
use syn::visit_mut::{self, VisitMut};
use syn::{
- parse_quote, Block, Error, ExprPath, ExprStruct, Ident, Item, Macro, PatPath, PatStruct,
- PatTupleStruct, Path, PathArguments, QSelf, Receiver, Signature, Token, Type, TypePath,
- WherePredicate,
+ Block, ExprPath, Ident, Item, Macro, PatPath, PatIdent, Pat, Receiver,
+ Signature, Token, TypePath,
};
pub fn has_self_in_sig(sig: &mut Signature) -> bool {
diff --git a/src/receiver.rs b/src/receiver.rs
--- a/src/receiver.rs
+++ b/src/receiver.rs
@@ -17,12 +11,6 @@ pub fn has_self_in_sig(sig: &mut Signature) -> bool {
visitor.0
}
-pub fn has_self_in_where_predicate(where_predicate: &mut WherePredicate) -> bool {
- let mut visitor = HasSelf(false);
- visitor.visit_where_predicate_mut(where_predicate);
- visitor.0
-}
-
pub fn has_self_in_block(block: &mut Block) -> bool {
let mut visitor = HasSelf(false);
visitor.visit_block_mut(block);
diff --git a/src/receiver.rs b/src/receiver.rs
--- a/src/receiver.rs
+++ b/src/receiver.rs
@@ -37,6 +25,32 @@ fn has_self_in_token_stream(tokens: TokenStream) -> bool {
})
}
+pub fn mut_pat(pat: &mut Pat) -> Option<Token![mut]> {
+ let mut visitor = HasMutPat(None);
+ visitor.visit_pat_mut(pat);
+ visitor.0
+}
+
+fn contains_fn(tokens: TokenStream) -> bool {
+ tokens.into_iter().any(|tt| match tt {
+ TokenTree::Ident(ident) => ident == "fn",
+ TokenTree::Group(group) => contains_fn(group.stream()),
+ _ => false,
+ })
+}
+
+struct HasMutPat(Option<Token![mut]>);
+
+impl VisitMut for HasMutPat {
+ fn visit_pat_ident_mut(&mut self, i: &mut PatIdent) {
+ if let Some(m) = i.mutability {
+ self.0 = Some(m);
+ } else {
+ visit_mut::visit_pat_ident_mut(self, i);
+ }
+ }
+}
+
struct HasSelf(bool);
impl VisitMut for HasSelf {
diff --git a/src/receiver.rs b/src/receiver.rs
--- a/src/receiver.rs
+++ b/src/receiver.rs
@@ -70,252 +84,49 @@ impl VisitMut for HasSelf {
}
}
-pub struct ReplaceReceiver {
- pub with: Type,
- pub as_trait: Option<Path>,
-}
-
-impl ReplaceReceiver {
- pub fn with(ty: Type) -> Self {
- ReplaceReceiver {
- with: ty,
- as_trait: None,
- }
- }
-
- pub fn with_as_trait(ty: Type, as_trait: Path) -> Self {
- ReplaceReceiver {
- with: ty,
- as_trait: Some(as_trait),
- }
- }
-
- fn self_ty(&self, span: Span) -> Type {
- respan(&self.with, span)
- }
-
- fn self_to_qself_type(&self, qself: &mut Option<QSelf>, path: &mut Path) {
- let include_as_trait = true;
- self.self_to_qself(qself, path, include_as_trait);
- }
-
- fn self_to_qself_expr(&self, qself: &mut Option<QSelf>, path: &mut Path) {
- let include_as_trait = false;
- self.self_to_qself(qself, path, include_as_trait);
- }
-
- fn self_to_qself(&self, qself: &mut Option<QSelf>, path: &mut Path, include_as_trait: bool) {
- if path.leading_colon.is_some() {
- return;
- }
-
- let first = &path.segments[0];
- if first.ident != "Self" || !first.arguments.is_empty() {
- return;
- }
-
- if path.segments.len() == 1 {
- self.self_to_expr_path(path);
- return;
- }
-
- let span = first.ident.span();
- *qself = Some(QSelf {
- lt_token: Token,
- ty: Box::new(self.self_ty(span)),
- position: 0,
- as_token: None,
- gt_token: Token,
- });
-
- if include_as_trait && self.as_trait.is_some() {
- let as_trait = self.as_trait.as_ref().unwrap().clone();
- path.leading_colon = as_trait.leading_colon;
- qself.as_mut().unwrap().position = as_trait.segments.len();
-
- let segments = mem::replace(&mut path.segments, as_trait.segments);
- path.segments.push_punct(Default::default());
- path.segments.extend(segments.into_pairs().skip(1));
- } else {
- path.leading_colon = Some(**path.segments.pairs().next().unwrap().punct().unwrap());
-
- let segments = mem::replace(&mut path.segments, Punctuated::new());
- path.segments = segments.into_pairs().skip(1).collect();
- }
- }
+pub struct ReplaceSelf<'a>(pub &'a str, pub Span);
- fn self_to_expr_path(&self, path: &mut Path) {
- if path.leading_colon.is_some() {
- return;
- }
-
- let first = &path.segments[0];
- if first.ident != "Self" || !first.arguments.is_empty() {
- return;
- }
-
- if let Type::Path(self_ty) = self.self_ty(first.ident.span()) {
- let variant = mem::replace(path, self_ty.path);
- for segment in &mut path.segments {
- if let PathArguments::AngleBracketed(bracketed) = &mut segment.arguments {
- if bracketed.colon2_token.is_none() && !bracketed.args.is_empty() {
- bracketed.colon2_token = Some(Default::default());
- }
- }
- }
- if variant.segments.len() > 1 {
- path.segments.push_punct(Default::default());
- path.segments.extend(variant.segments.into_pairs().skip(1));
+impl ReplaceSelf<'_> {
+ fn visit_token_stream(&mut self, tt: TokenStream) -> TokenStream {
+ tt.into_iter().map(|tt| match tt {
+ TokenTree::Ident(mut ident) => {
+ self.visit_ident_mut(&mut ident);
+ TokenTree::Ident(ident)
}
- } else {
- let span = path.segments[0].ident.span();
- let msg = "Self type of this impl is unsupported in expression position";
- let error = Error::new(span, msg).to_compile_error();
- *path = parse_quote!(::core::marker::PhantomData::<#error>);
- }
- }
-
- fn visit_token_stream(&self, tokens: &mut TokenStream) -> bool {
- let mut out = Vec::new();
- let mut modified = false;
- let mut iter = tokens.clone().into_iter().peekable();
- while let Some(tt) = iter.next() {
- match tt {
- TokenTree::Ident(mut ident) => {
- modified |= prepend_underscore_to_self(&mut ident);
- if ident == "Self" {
- modified = true;
- if self.as_trait.is_none() {
- let ident = Ident::new("AsyncTrait", ident.span());
- out.push(TokenTree::Ident(ident));
- } else {
- let self_ty = self.self_ty(ident.span());
- match iter.peek() {
- Some(TokenTree::Punct(p))
- if p.as_char() == ':' && p.spacing() == Spacing::Joint =>
- {
- let next = iter.next().unwrap();
- match iter.peek() {
- Some(TokenTree::Punct(p)) if p.as_char() == ':' => {
- let span = ident.span();
- out.extend(quote_spanned!(span=> <#self_ty>));
- }
- _ => out.extend(quote!(#self_ty)),
- }
- out.push(next);
- }
- _ => out.extend(quote!(#self_ty)),
- }
- }
- } else {
- out.push(TokenTree::Ident(ident));
- }
- }
- TokenTree::Group(group) => {
- let mut content = group.stream();
- modified |= self.visit_token_stream(&mut content);
- let mut new = Group::new(group.delimiter(), content);
- new.set_span(group.span());
- out.push(TokenTree::Group(new));
- }
- other => out.push(other),
+ TokenTree::Group(group) => {
+ let tt = self.visit_token_stream(group.stream());
+ let mut new = Group::new(group.delimiter(), tt);
+ new.set_span(group.span());
+ TokenTree::Group(new)
}
- }
- if modified {
- *tokens = TokenStream::from_iter(out);
- }
- modified
+ tt => tt,
+ }).collect()
}
}
-impl VisitMut for ReplaceReceiver {
- // `Self` -> `Receiver`
- fn visit_type_mut(&mut self, ty: &mut Type) {
- if let Type::Path(node) = ty {
- if node.qself.is_none() && node.path.is_ident("Self") {
- *ty = self.self_ty(node.path.segments[0].ident.span());
- } else {
- self.visit_type_path_mut(node);
- }
- } else {
- visit_mut::visit_type_mut(self, ty);
- }
- }
-
- // `Self::Assoc` -> `<Receiver>::Assoc`
- fn visit_type_path_mut(&mut self, ty: &mut TypePath) {
- if ty.qself.is_none() {
- self.self_to_qself_type(&mut ty.qself, &mut ty.path);
- }
- visit_mut::visit_type_path_mut(self, ty);
- }
-
- // `Self::method` -> `<Receiver>::method`
- fn visit_expr_path_mut(&mut self, expr: &mut ExprPath) {
- if expr.qself.is_none() {
- prepend_underscore_to_self(&mut expr.path.segments[0].ident);
- self.self_to_qself_expr(&mut expr.qself, &mut expr.path);
- }
- visit_mut::visit_expr_path_mut(self, expr);
- }
-
- fn visit_expr_struct_mut(&mut self, expr: &mut ExprStruct) {
- self.self_to_expr_path(&mut expr.path);
- visit_mut::visit_expr_struct_mut(self, expr);
- }
-
- fn visit_pat_path_mut(&mut self, pat: &mut PatPath) {
- if pat.qself.is_none() {
- self.self_to_qself_expr(&mut pat.qself, &mut pat.path);
+impl VisitMut for ReplaceSelf<'_> {
+ fn visit_ident_mut(&mut self, i: &mut Ident) {
+ if i == "self" {
+ *i = quote::format_ident!("{}{}", self.0, i);
+ #[cfg(self_span_hack)]
+ i.set_span(self.1);
}
- visit_mut::visit_pat_path_mut(self, pat);
- }
-
- fn visit_pat_struct_mut(&mut self, pat: &mut PatStruct) {
- self.self_to_expr_path(&mut pat.path);
- visit_mut::visit_pat_struct_mut(self, pat);
- }
- fn visit_pat_tuple_struct_mut(&mut self, pat: &mut PatTupleStruct) {
- self.self_to_expr_path(&mut pat.path);
- visit_mut::visit_pat_tuple_struct_mut(self, pat);
+ visit_mut::visit_ident_mut(self, i);
}
fn visit_item_mut(&mut self, i: &mut Item) {
- match i {
- // Visit `macro_rules!` because locally defined macros can refer to `self`.
- Item::Macro(i) if i.mac.path.is_ident("macro_rules") => {
+ // Visit `macro_rules!` because locally defined macros can refer to
+ // `self`. Otherwise, do not recurse into nested items.
+ if let Item::Macro(i) = i {
+ if i.mac.path.is_ident("macro_rules") {
self.visit_macro_mut(&mut i.mac)
}
- // Otherwise, do not recurse into nested items.
- _ => {}
}
}
fn visit_macro_mut(&mut self, mac: &mut Macro) {
- // We can't tell in general whether `self` inside a macro invocation
- // refers to the self in the argument list or a different self
- // introduced within the macro. Heuristic: if the macro input contains
- // `fn`, then `self` is more likely to refer to something other than the
- // outer function's self argument.
- if !contains_fn(mac.tokens.clone()) {
- self.visit_token_stream(&mut mac.tokens);
- }
- }
-}
-
-fn contains_fn(tokens: TokenStream) -> bool {
- tokens.into_iter().any(|tt| match tt {
- TokenTree::Ident(ident) => ident == "fn",
- TokenTree::Group(group) => contains_fn(group.stream()),
- _ => false,
- })
-}
-
-fn prepend_underscore_to_self(ident: &mut Ident) -> bool {
- let modified = ident == "self";
- if modified {
- *ident = Ident::new("_self", ident.span());
+ mac.tokens = self.visit_token_stream(mac.tokens.clone());
+ visit_mut::visit_macro_mut(self, mac);
}
- modified
}
diff --git a/src/respan.rs /dev/null
--- a/src/respan.rs
+++ /dev/null
@@ -1,22 +0,0 @@
-use proc_macro2::{Span, TokenStream};
-use quote::ToTokens;
-use syn::parse::Parse;
-
-pub(crate) fn respan<T>(node: &T, span: Span) -> T
-where
- T: ToTokens + Parse,
-{
- let tokens = node.to_token_stream();
- let respanned = respan_tokens(tokens, span);
- syn::parse2(respanned).unwrap()
-}
-
-fn respan_tokens(tokens: TokenStream, span: Span) -> TokenStream {
- tokens
- .into_iter()
- .map(|mut token| {
- token.set_span(span);
- token
- })
- .collect()
-}
|
diff --git a/tests/executor/mod.rs b/tests/executor/mod.rs
--- a/tests/executor/mod.rs
+++ b/tests/executor/mod.rs
@@ -4,6 +4,7 @@ use std::ptr;
use std::task::{Context, Poll, RawWaker, RawWakerVTable, Waker};
// Executor for a future that resolves immediately (test only).
+#[allow(clippy::missing_panics_doc)]
pub fn block_on_simple<F: Future>(mut fut: F) -> F::Output {
unsafe fn clone(_null: *const ()) -> RawWaker {
unimplemented!()
diff --git a/tests/test.rs b/tests/test.rs
--- a/tests/test.rs
+++ b/tests/test.rs
@@ -157,6 +157,73 @@ pub(crate) unsafe trait UnsafeTraitPubCrate {}
#[async_trait]
unsafe trait UnsafeTraitPrivate {}
+pub async fn test_can_destruct() {
+ #[async_trait]
+ trait CanDestruct {
+ async fn f(&self, foos: (u8, u8, u8, u8));
+ }
+
+ #[async_trait]
+ impl CanDestruct for Struct {
+ async fn f(&self, (a, ref mut b, ref c, d): (u8, u8, u8, u8)) {
+ let _a: u8 = a;
+ let _b: &mut u8 = b;
+ let _c: &u8 = c;
+ let _d: u8 = d;
+ }
+ }
+}
+
+pub async fn test_self_in_macro() {
+ #[async_trait]
+ trait Trait {
+ async fn a(self);
+ async fn b(&mut self);
+ async fn c(&self);
+ }
+
+ #[async_trait]
+ impl Trait for String {
+ async fn a(self) { println!("{}", self); }
+ async fn b(&mut self) { println!("{}", self); }
+ async fn c(&self) { println!("{}", self); }
+ }
+}
+
+pub async fn test_inference() {
+ #[async_trait]
+ pub trait Trait {
+ async fn f() -> Box<dyn Iterator<Item = ()>> {
+ Box::new(std::iter::empty())
+ }
+ }
+}
+
+pub async fn test_internal_items() {
+ #[async_trait]
+ #[allow(dead_code, clippy::items_after_statements)]
+ pub trait Trait: Sized {
+ async fn f(self) {
+ struct Struct;
+
+ impl Struct {
+ fn f(self) {
+ let _ = self;
+ }
+ }
+ }
+ }
+}
+
+pub async fn test_unimplemented() {
+ #[async_trait]
+ pub trait Trait {
+ async fn f() {
+ unimplemented!()
+ }
+ }
+}
+
// https://github.com/dtolnay/async-trait/issues/1
pub mod issue1 {
use async_trait::async_trait;
diff --git a/tests/test.rs b/tests/test.rs
--- a/tests/test.rs
+++ b/tests/test.rs
@@ -542,6 +609,7 @@ pub mod issue45 {
}
#[test]
+ #[should_panic]
fn tracing() {
// Create the future outside of the subscriber, as no call to tracing
// should be made until the future is polled.
diff --git a/tests/test.rs b/tests/test.rs
--- a/tests/test.rs
+++ b/tests/test.rs
@@ -1083,3 +1151,64 @@ pub mod issue134 {
}
}
}
+
+// https://github.com/dtolnay/async-trait/pull/125#pullrequestreview-491880881
+pub mod drop_order {
+ use std::sync::atomic::{AtomicBool, Ordering};
+ use async_trait::async_trait;
+ use crate::executor;
+
+ struct Flagger<'a>(&'a AtomicBool);
+
+ impl Drop for Flagger<'_> {
+ fn drop(&mut self) {
+ self.0.fetch_xor(true, Ordering::AcqRel);
+ }
+ }
+
+ #[async_trait]
+ trait Trait {
+ async fn async_trait(_: Flagger<'_>, flag: &AtomicBool);
+ }
+
+ struct Struct;
+
+ #[async_trait]
+ impl Trait for Struct {
+ async fn async_trait(_: Flagger<'_>, flag: &AtomicBool) {
+ flag.fetch_or(true, Ordering::AcqRel);
+ }
+ }
+
+ async fn standalone(_: Flagger<'_>, flag: &AtomicBool) {
+ flag.fetch_or(true, Ordering::AcqRel);
+ }
+
+ #[async_trait]
+ trait SelfTrait {
+ async fn async_trait(self, flag: &AtomicBool);
+ }
+
+ #[async_trait]
+ impl SelfTrait for Flagger<'_> {
+ async fn async_trait(self, flag: &AtomicBool) {
+ flag.fetch_or(true, Ordering::AcqRel);
+ }
+ }
+
+ #[test]
+ fn test_drop_order() {
+ // 0 : 0 ^ 1 = 1 | 1 = 1 (if flagger then block)
+ // 0 : 0 | 1 = 1 ^ 1 = 0 (if block then flagger)
+
+ let flag = AtomicBool::new(false);
+ executor::block_on_simple(standalone(Flagger(&flag), &flag));
+ assert!(!flag.load(Ordering::Acquire));
+
+ executor::block_on_simple(Struct::async_trait(Flagger(&flag), &flag));
+ assert!(!flag.load(Ordering::Acquire));
+
+ executor::block_on_simple(Flagger(&flag).async_trait(&flag));
+ assert!(!flag.load(Ordering::Acquire));
+ }
+}
diff --git a/tests/ui/delimiter-span.rs b/tests/ui/delimiter-span.rs
--- a/tests/ui/delimiter-span.rs
+++ b/tests/ui/delimiter-span.rs
@@ -1,7 +1,7 @@
use async_trait::async_trait;
macro_rules! picky {
- (ident) => {};
+ ($(t:tt)*) => {};
}
#[async_trait]
diff --git a/tests/ui/delimiter-span.rs b/tests/ui/delimiter-span.rs
--- a/tests/ui/delimiter-span.rs
+++ b/tests/ui/delimiter-span.rs
@@ -14,6 +14,7 @@ struct Struct;
#[async_trait]
impl Trait for Struct {
async fn method() {
+ picky!({ 123, self });
picky!({ 123 });
}
}
diff --git a/tests/ui/delimiter-span.stderr b/tests/ui/delimiter-span.stderr
--- a/tests/ui/delimiter-span.stderr
+++ b/tests/ui/delimiter-span.stderr
@@ -4,5 +4,14 @@ error: no rules expected the token `{`
3 | macro_rules! picky {
| ------------------ when calling this macro
...
-17 | picky!({ 123 });
+17 | picky!({ 123, self });
+ | ^ no rules expected this token in macro call
+
+error: no rules expected the token `{`
+ --> $DIR/delimiter-span.rs:18:16
+ |
+3 | macro_rules! picky {
+ | ------------------ when calling this macro
+...
+18 | picky!({ 123 });
| ^ no rules expected this token in macro call
diff --git /dev/null b/tests/ui/lifetime-span.rs
new file mode 100644
--- /dev/null
+++ b/tests/ui/lifetime-span.rs
@@ -0,0 +1,36 @@
+use async_trait::async_trait;
+
+struct A;
+struct B;
+
+#[async_trait]
+pub trait Trait<'r> {
+ async fn method(&'r self);
+}
+
+#[async_trait]
+impl Trait for A {
+ async fn method(&self) { }
+}
+
+#[async_trait]
+impl<'r> Trait<'r> for B {
+ async fn method(&self) { }
+}
+
+#[async_trait]
+pub trait Trait2 {
+ async fn method<'r>(&'r self);
+}
+
+#[async_trait]
+impl Trait2 for A {
+ async fn method(&self) { }
+}
+
+#[async_trait]
+impl<'r> Trait2<'r> for B {
+ async fn method(&'r self) { }
+}
+
+fn main() {}
diff --git /dev/null b/tests/ui/lifetime-span.stderr
new file mode 100644
--- /dev/null
+++ b/tests/ui/lifetime-span.stderr
@@ -0,0 +1,46 @@
+error[E0726]: implicit elided lifetime not allowed here
+ --> $DIR/lifetime-span.rs:12:6
+ |
+12 | impl Trait for A {
+ | ^^^^^- help: indicate the anonymous lifetime: `<'_>`
+
+error[E0107]: this trait takes 0 lifetime arguments but 1 lifetime argument was supplied
+ --> $DIR/lifetime-span.rs:32:10
+ |
+32 | impl<'r> Trait2<'r> for B {
+ | ^^^^^^---- help: remove these generics
+ | |
+ | expected 0 lifetime arguments
+ |
+note: trait defined here, with 0 lifetime parameters
+ --> $DIR/lifetime-span.rs:22:11
+ |
+22 | pub trait Trait2 {
+ | ^^^^^^
+
+error[E0195]: lifetime parameters or bounds on method `method` do not match the trait declaration
+ --> $DIR/lifetime-span.rs:13:14
+ |
+8 | async fn method(&'r self);
+ | ---------------- lifetimes in impl do not match this method in trait
+...
+13 | async fn method(&self) { }
+ | ^^^^^^^^^^^^^ lifetimes do not match method in trait
+
+error[E0195]: lifetime parameters or bounds on method `method` do not match the trait declaration
+ --> $DIR/lifetime-span.rs:18:14
+ |
+8 | async fn method(&'r self);
+ | ---------------- lifetimes in impl do not match this method in trait
+...
+18 | async fn method(&self) { }
+ | ^^^^^^^^^^^^^ lifetimes do not match method in trait
+
+error[E0195]: lifetime parameters or bounds on method `method` do not match the trait declaration
+ --> $DIR/lifetime-span.rs:33:14
+ |
+23 | async fn method<'r>(&'r self);
+ | ---- lifetimes in impl do not match this method in trait
+...
+33 | async fn method(&'r self) { }
+ | ^^^^^^^^^^^^^^^^ lifetimes do not match method in trait
diff --git a/tests/ui/self-span.stderr b/tests/ui/self-span.stderr
--- a/tests/ui/self-span.stderr
+++ b/tests/ui/self-span.stderr
@@ -1,12 +1,3 @@
-error[E0423]: expected value, found struct `S`
- --> $DIR/self-span.rs:18:23
- |
-3 | pub struct S {}
- | --------------- `S` defined here
-...
-18 | let _: Self = Self;
- | ^^^^ help: use struct literal syntax instead: `S {}`
-
error[E0308]: mismatched types
--> $DIR/self-span.rs:17:21
|
diff --git a/tests/ui/self-span.stderr b/tests/ui/self-span.stderr
--- a/tests/ui/self-span.stderr
+++ b/tests/ui/self-span.stderr
@@ -15,6 +6,12 @@ error[E0308]: mismatched types
| |
| expected due to this
+error: the `Self` constructor can only be used with tuple or unit structs
+ --> $DIR/self-span.rs:18:23
+ |
+18 | let _: Self = Self;
+ | ^^^^ help: use curly brackets: `Self { /* fields */ }`
+
error[E0308]: mismatched types
--> $DIR/self-span.rs:25:21
|
diff --git a/tests/ui/send-not-implemented.stderr b/tests/ui/send-not-implemented.stderr
--- a/tests/ui/send-not-implemented.stderr
+++ b/tests/ui/send-not-implemented.stderr
@@ -7,7 +7,7 @@ error: future cannot be sent between threads safely
10 | | let _guard = mutex.lock().unwrap();
11 | | f().await;
12 | | }
- | |_____^ future returned by `__test` is not `Send`
+ | |_____^ future created by async block is not `Send`
|
= help: within `impl Future`, the trait `Send` is not implemented for `MutexGuard<'_, ()>`
note: future is not `Send` as this value is used across an await
diff --git /dev/null b/tests/ui/unreachable.rs
new file mode 100644
--- /dev/null
+++ b/tests/ui/unreachable.rs
@@ -0,0 +1,20 @@
+#![deny(warnings)]
+
+use async_trait::async_trait;
+
+#[async_trait]
+pub trait Trait {
+ async fn f() {
+ unimplemented!()
+ }
+}
+
+#[async_trait]
+pub trait TraitFoo {
+ async fn f() {
+ let y = unimplemented!();
+ let z = y;
+ }
+}
+
+fn main() {}
diff --git /dev/null b/tests/ui/unreachable.stderr
new file mode 100644
--- /dev/null
+++ b/tests/ui/unreachable.stderr
@@ -0,0 +1,14 @@
+error: unreachable statement
+ --> $DIR/unreachable.rs:16:9
+ |
+15 | let y = unimplemented!();
+ | ---------------- any code following this expression is unreachable
+16 | let z = y;
+ | ^^^^^^^^^^ unreachable statement
+ |
+note: the lint level is defined here
+ --> $DIR/unreachable.rs:1:9
+ |
+1 | #![deny(warnings)]
+ | ^^^^^^^^
+ = note: `#[deny(unreachable_code)]` implied by `#[deny(warnings)]`
diff --git a/tests/ui/unsupported-self.stderr b/tests/ui/unsupported-self.stderr
--- a/tests/ui/unsupported-self.stderr
+++ b/tests/ui/unsupported-self.stderr
@@ -1,4 +1,4 @@
-error: Self type of this impl is unsupported in expression position
+error: the `Self` constructor can only be used with tuple or unit structs
--> $DIR/unsupported-self.rs:11:17
|
11 | let _ = Self;
|
default impl for methods with `impl trait` arguments?
Given the code:
```
use async_trait::async_trait; // 0.1.36
use tokio; // 0.2.21
#[async_trait]
trait MyTrait {
async fn blah(&self, values: impl Iterator<Item = i32> + Send + 'async_trait) {
println!("this is the default");
}
}
struct S;
#[async_trait]
impl MyTrait for S {
async fn blah(&self, values: impl Iterator<Item = i32> + Send + 'async_trait) {
for value in values {
println!("{}", value);
}
}
}
#[tokio::main]
async fn main() {
let s = S;
s.blah([1, 2, 3].iter().cloned()).await;
}
```
this fails to compile with the error:
```
error[E0632]: cannot provide explicit generic arguments when `impl Trait` is used in argument position
--> src/main.rs:4:1
|
4 | #[async_trait]
| ^^^^^^^^^^^^^^ explicit generic argument not allowed
|
= note: this error originates in an attribute macro (in Nightly builds, run with -Z macro-backtrace for more info)
```
If I remove the default body, it works.
Is this intended to be supported? I can work around it by boxing and using `dyn`, i.e. `values: Box<dyn Iterator<Item=i32> + Send + 'async_trait>` but that's not ideal.
Thanks for this crate!
|
Looks like the expanded code is: (cleaned up a little)
```
trait MyTrait {
#[must_use]
fn blah<'life0, 'async_trait>(&'life0 self, values: impl Iterator<Item = i32> + Send + 'async_trait)
-> Pin<Box<dyn Future<Output = ()> + Send + 'async_trait>>
where 'life0: 'async_trait,
Self: Sync + 'async_trait
{
async fn __blah<'async_trait, AsyncTrait: ?Sized + MyTrait + Sync>(
_self: &AsyncTrait,
values: impl Iterator<Item = i32> + Send + 'async_trait,
) {
println!( ... );
}
Box::pin(__blah::<Self>(self, values))
}
}
```
and rustc does not like the explicit generic argument in `__blah::<Self>(self, values)`. Simply removing that `::<Self>` turbofish works for this case at least.
Same issue.
|
2021-02-03T06:12:37Z
|
0.1
|
2021-03-05T05:09:49Z
|
f8e5bb43181450a17068f160e8a51d410ede1705
|
[
"issue45::tracing"
] |
[
"drop_order::test_drop_order",
"src/lib.rs - (line 15)",
"src/lib.rs - (line 165)",
"src/lib.rs - (line 186)",
"src/lib.rs - (line 286)",
"src/lib.rs - (line 126)",
"src/lib.rs - (line 211)",
"src/lib.rs - (line 47)",
"src/lib.rs - (line 265)"
] |
[] |
[] |
auto_2025-06-06
|
atuinsh/atuin
| 71
|
atuinsh__atuin-71
|
[
"66"
] |
725ea9b16b1e3596b394fa7e47e02a9331de10cf
|
diff --git a/atuin-client/src/import/bash.rs b/atuin-client/src/import/bash.rs
--- a/atuin-client/src/import/bash.rs
+++ b/atuin-client/src/import/bash.rs
@@ -1,63 +1,77 @@
-use std::io::{BufRead, BufReader};
-use std::{fs::File, path::Path};
+use std::{
+ fs::File,
+ io::{BufRead, BufReader, Read, Seek},
+ path::{Path, PathBuf},
+};
+use directories::UserDirs;
use eyre::{eyre, Result};
-use super::count_lines;
+use super::{count_lines, Importer};
use crate::history::History;
#[derive(Debug)]
-pub struct Bash {
- file: BufReader<File>,
-
- pub loc: u64,
- pub counter: i64,
+pub struct Bash<R> {
+ file: BufReader<R>,
+ strbuf: String,
+ loc: usize,
+ counter: i64,
}
-impl Bash {
- pub fn new(path: impl AsRef<Path>) -> Result<Self> {
- let file = File::open(path)?;
- let mut buf = BufReader::new(file);
+impl<R: Read + Seek> Bash<R> {
+ fn new(r: R) -> Result<Self> {
+ let mut buf = BufReader::new(r);
let loc = count_lines(&mut buf)?;
Ok(Self {
file: buf,
- loc: loc as u64,
+ strbuf: String::new(),
+ loc,
counter: 0,
})
}
+}
- fn read_line(&mut self) -> Option<Result<String>> {
- let mut line = String::new();
+impl Importer for Bash<File> {
+ const NAME: &'static str = "bash";
- match self.file.read_line(&mut line) {
- Ok(0) => None,
- Ok(_) => Some(Ok(line)),
- Err(e) => Some(Err(eyre!("failed to read line: {}", e))), // we can skip past things like invalid utf8
- }
+ fn histpath() -> Result<PathBuf> {
+ let user_dirs = UserDirs::new().unwrap();
+ let home_dir = user_dirs.home_dir();
+
+ Ok(home_dir.join(".bash_history"))
+ }
+
+ fn parse(path: impl AsRef<Path>) -> Result<Self> {
+ Self::new(File::open(path)?)
}
}
-impl Iterator for Bash {
+impl<R: Read> Iterator for Bash<R> {
type Item = Result<History>;
fn next(&mut self) -> Option<Self::Item> {
- let line = self.read_line()?;
-
- if let Err(e) = line {
- return Some(Err(e)); // :(
+ self.strbuf.clear();
+ match self.file.read_line(&mut self.strbuf) {
+ Ok(0) => return None,
+ Ok(_) => (),
+ Err(e) => return Some(Err(eyre!("failed to read line: {}", e))), // we can skip past things like invalid utf8
}
- let mut line = line.unwrap();
+ self.loc -= 1;
- while line.ends_with("\\\n") {
- let next_line = self.read_line()?;
-
- if next_line.is_err() {
+ while self.strbuf.ends_with("\\\n") {
+ if self.file.read_line(&mut self.strbuf).is_err() {
+ // There's a chance that the last line of a command has invalid
+ // characters, the only safe thing to do is break :/
+ // usually just invalid utf8 or smth
+ // however, we really need to avoid missing history, so it's
+ // better to have some items that should have been part of
+ // something else, than to miss things. So break.
break;
- }
+ };
- line.push_str(next_line.unwrap().as_str());
+ self.loc -= 1;
}
let time = chrono::Utc::now();
diff --git a/atuin-client/src/import/bash.rs b/atuin-client/src/import/bash.rs
--- a/atuin-client/src/import/bash.rs
+++ b/atuin-client/src/import/bash.rs
@@ -68,7 +82,7 @@ impl Iterator for Bash {
Some(Ok(History::new(
time,
- line.trim_end().to_string(),
+ self.strbuf.trim_end().to_string(),
String::from("unknown"),
-1,
-1,
diff --git a/atuin-client/src/import/mod.rs b/atuin-client/src/import/mod.rs
--- a/atuin-client/src/import/mod.rs
+++ b/atuin-client/src/import/mod.rs
@@ -1,16 +1,24 @@
-use std::fs::File;
-use std::io::{BufRead, BufReader, Seek, SeekFrom};
+use std::io::{BufRead, BufReader, Read, Seek, SeekFrom};
+use std::path::{Path, PathBuf};
use eyre::Result;
+use crate::history::History;
+
pub mod bash;
pub mod resh;
pub mod zsh;
// this could probably be sped up
-fn count_lines(buf: &mut BufReader<File>) -> Result<usize> {
+fn count_lines(buf: &mut BufReader<impl Read + Seek>) -> Result<usize> {
let lines = buf.lines().count();
buf.seek(SeekFrom::Start(0))?;
Ok(lines)
}
+
+pub trait Importer: IntoIterator<Item = Result<History>> + Sized {
+ const NAME: &'static str;
+ fn histpath() -> Result<PathBuf>;
+ fn parse(path: impl AsRef<Path>) -> Result<Self>;
+}
diff --git a/atuin-client/src/import/resh.rs b/atuin-client/src/import/resh.rs
--- a/atuin-client/src/import/resh.rs
+++ b/atuin-client/src/import/resh.rs
@@ -1,91 +1,156 @@
+use std::{
+ fs::File,
+ io::{BufRead, BufReader},
+ path::{Path, PathBuf},
+};
+
+use atuin_common::utils::uuid_v4;
+use chrono::{TimeZone, Utc};
+use directories::UserDirs;
+use eyre::{eyre, Result};
use serde::Deserialize;
+use super::{count_lines, Importer};
+use crate::history::History;
+
#[derive(Deserialize, Debug)]
+#[serde(rename_all = "camelCase")]
pub struct ReshEntry {
- #[serde(rename = "cmdLine")]
pub cmd_line: String,
- #[serde(rename = "exitCode")]
pub exit_code: i64,
pub shell: String,
pub uname: String,
- #[serde(rename = "sessionId")]
pub session_id: String,
pub home: String,
pub lang: String,
- #[serde(rename = "lcAll")]
pub lc_all: String,
pub login: String,
pub pwd: String,
- #[serde(rename = "pwdAfter")]
pub pwd_after: String,
- #[serde(rename = "shellEnv")]
pub shell_env: String,
pub term: String,
- #[serde(rename = "realPwd")]
pub real_pwd: String,
- #[serde(rename = "realPwdAfter")]
pub real_pwd_after: String,
pub pid: i64,
- #[serde(rename = "sessionPid")]
pub session_pid: i64,
pub host: String,
pub hosttype: String,
pub ostype: String,
pub machtype: String,
pub shlvl: i64,
- #[serde(rename = "timezoneBefore")]
pub timezone_before: String,
- #[serde(rename = "timezoneAfter")]
pub timezone_after: String,
- #[serde(rename = "realtimeBefore")]
pub realtime_before: f64,
- #[serde(rename = "realtimeAfter")]
pub realtime_after: f64,
- #[serde(rename = "realtimeBeforeLocal")]
pub realtime_before_local: f64,
- #[serde(rename = "realtimeAfterLocal")]
pub realtime_after_local: f64,
- #[serde(rename = "realtimeDuration")]
pub realtime_duration: f64,
- #[serde(rename = "realtimeSinceSessionStart")]
pub realtime_since_session_start: f64,
- #[serde(rename = "realtimeSinceBoot")]
pub realtime_since_boot: f64,
- #[serde(rename = "gitDir")]
pub git_dir: String,
- #[serde(rename = "gitRealDir")]
pub git_real_dir: String,
- #[serde(rename = "gitOriginRemote")]
pub git_origin_remote: String,
- #[serde(rename = "gitDirAfter")]
pub git_dir_after: String,
- #[serde(rename = "gitRealDirAfter")]
pub git_real_dir_after: String,
- #[serde(rename = "gitOriginRemoteAfter")]
pub git_origin_remote_after: String,
- #[serde(rename = "machineId")]
pub machine_id: String,
- #[serde(rename = "osReleaseId")]
pub os_release_id: String,
- #[serde(rename = "osReleaseVersionId")]
pub os_release_version_id: String,
- #[serde(rename = "osReleaseIdLike")]
pub os_release_id_like: String,
- #[serde(rename = "osReleaseName")]
pub os_release_name: String,
- #[serde(rename = "osReleasePrettyName")]
pub os_release_pretty_name: String,
- #[serde(rename = "reshUuid")]
pub resh_uuid: String,
- #[serde(rename = "reshVersion")]
pub resh_version: String,
- #[serde(rename = "reshRevision")]
pub resh_revision: String,
- #[serde(rename = "partsMerged")]
pub parts_merged: bool,
pub recalled: bool,
- #[serde(rename = "recallLastCmdLine")]
pub recall_last_cmd_line: String,
pub cols: String,
pub lines: String,
}
+
+#[derive(Debug)]
+pub struct Resh {
+ file: BufReader<File>,
+ strbuf: String,
+ loc: usize,
+ counter: i64,
+}
+
+impl Importer for Resh {
+ const NAME: &'static str = "resh";
+
+ fn histpath() -> Result<PathBuf> {
+ let user_dirs = UserDirs::new().unwrap();
+ let home_dir = user_dirs.home_dir();
+
+ Ok(home_dir.join(".resh_history.json"))
+ }
+
+ fn parse(path: impl AsRef<Path>) -> Result<Self> {
+ let file = File::open(path)?;
+ let mut buf = BufReader::new(file);
+ let loc = count_lines(&mut buf)?;
+
+ Ok(Self {
+ file: buf,
+ strbuf: String::new(),
+ loc,
+ counter: 0,
+ })
+ }
+}
+
+impl Iterator for Resh {
+ type Item = Result<History>;
+
+ fn next(&mut self) -> Option<Self::Item> {
+ self.strbuf.clear();
+ match self.file.read_line(&mut self.strbuf) {
+ Ok(0) => return None,
+ Ok(_) => (),
+ Err(e) => return Some(Err(eyre!("failed to read line: {}", e))), // we can skip past things like invalid utf8
+ }
+
+ let entry = match serde_json::from_str::<ReshEntry>(&self.strbuf) {
+ Ok(e) => e,
+ Err(e) => {
+ return Some(Err(eyre!(
+ "Invalid entry found in resh_history file: {}",
+ e
+ )))
+ }
+ };
+
+ #[allow(clippy::cast_possible_truncation)]
+ #[allow(clippy::cast_sign_loss)]
+ let timestamp = {
+ let secs = entry.realtime_before.floor() as i64;
+ let nanosecs = (entry.realtime_before.fract() * 1_000_000_000_f64).round() as u32;
+ Utc.timestamp(secs, nanosecs)
+ };
+ #[allow(clippy::cast_possible_truncation)]
+ #[allow(clippy::cast_sign_loss)]
+ let duration = {
+ let secs = entry.realtime_after.floor() as i64;
+ let nanosecs = (entry.realtime_after.fract() * 1_000_000_000_f64).round() as u32;
+ let difference = Utc.timestamp(secs, nanosecs) - timestamp;
+ difference.num_nanoseconds().unwrap_or(0)
+ };
+
+ Some(Ok(History {
+ id: uuid_v4(),
+ timestamp,
+ duration,
+ exit: entry.exit_code,
+ command: entry.cmd_line,
+ cwd: entry.pwd,
+ session: uuid_v4(),
+ hostname: entry.host,
+ }))
+ }
+
+ fn size_hint(&self) -> (usize, Option<usize>) {
+ (self.loc, Some(self.loc))
+ }
+}
diff --git a/atuin-client/src/import/zsh.rs b/atuin-client/src/import/zsh.rs
--- a/atuin-client/src/import/zsh.rs
+++ b/atuin-client/src/import/zsh.rs
@@ -1,50 +1,73 @@
// import old shell history!
// automatically hoover up all that we can find
-use std::io::{BufRead, BufReader};
-use std::{fs::File, path::Path};
+use std::{
+ fs::File,
+ io::{BufRead, BufReader, Read, Seek},
+ path::{Path, PathBuf},
+};
use chrono::prelude::*;
use chrono::Utc;
+use directories::UserDirs;
use eyre::{eyre, Result};
use itertools::Itertools;
-use super::count_lines;
+use super::{count_lines, Importer};
use crate::history::History;
#[derive(Debug)]
-pub struct Zsh {
- file: BufReader<File>,
-
- pub loc: u64,
- pub counter: i64,
+pub struct Zsh<R> {
+ file: BufReader<R>,
+ strbuf: String,
+ loc: usize,
+ counter: i64,
}
-impl Zsh {
- pub fn new(path: impl AsRef<Path>) -> Result<Self> {
- let file = File::open(path)?;
- let mut buf = BufReader::new(file);
+impl<R: Read + Seek> Zsh<R> {
+ fn new(r: R) -> Result<Self> {
+ let mut buf = BufReader::new(r);
let loc = count_lines(&mut buf)?;
Ok(Self {
file: buf,
- loc: loc as u64,
+ strbuf: String::new(),
+ loc,
counter: 0,
})
}
+}
- fn read_line(&mut self) -> Option<Result<String>> {
- let mut line = String::new();
-
- match self.file.read_line(&mut line) {
- Ok(0) => None,
- Ok(_) => Some(Ok(line)),
- Err(e) => Some(Err(eyre!("failed to read line: {}", e))), // we can skip past things like invalid utf8
+impl Importer for Zsh<File> {
+ const NAME: &'static str = "zsh";
+
+ fn histpath() -> Result<PathBuf> {
+ // oh-my-zsh sets HISTFILE=~/.zhistory
+ // zsh has no default value for this var, but uses ~/.zhistory.
+ // we could maybe be smarter about this in the future :)
+ let user_dirs = UserDirs::new().unwrap();
+ let home_dir = user_dirs.home_dir();
+
+ let mut candidates = [".zhistory", ".zsh_history"].iter();
+ loop {
+ match candidates.next() {
+ Some(candidate) => {
+ let histpath = home_dir.join(candidate);
+ if histpath.exists() {
+ break Ok(histpath);
+ }
+ }
+ None => break Err(eyre!("Could not find history file. Try setting $HISTFILE")),
+ }
}
}
+
+ fn parse(path: impl AsRef<Path>) -> Result<Self> {
+ Self::new(File::open(path)?)
+ }
}
-impl Iterator for Zsh {
+impl<R: Read> Iterator for Zsh<R> {
type Item = Result<History>;
fn next(&mut self) -> Option<Self::Item> {
diff --git a/atuin-client/src/import/zsh.rs b/atuin-client/src/import/zsh.rs
--- a/atuin-client/src/import/zsh.rs
+++ b/atuin-client/src/import/zsh.rs
@@ -52,18 +75,17 @@ impl Iterator for Zsh {
// These lines begin with :
// So, if the line begins with :, parse it. Otherwise it's just
// the command
- let line = self.read_line()?;
-
- if let Err(e) = line {
- return Some(Err(e)); // :(
+ self.strbuf.clear();
+ match self.file.read_line(&mut self.strbuf) {
+ Ok(0) => return None,
+ Ok(_) => (),
+ Err(e) => return Some(Err(eyre!("failed to read line: {}", e))), // we can skip past things like invalid utf8
}
- let mut line = line.unwrap();
-
- while line.ends_with("\\\n") {
- let next_line = self.read_line()?;
+ self.loc -= 1;
- if next_line.is_err() {
+ while self.strbuf.ends_with("\\\n") {
+ if self.file.read_line(&mut self.strbuf).is_err() {
// There's a chance that the last line of a command has invalid
// characters, the only safe thing to do is break :/
// usually just invalid utf8 or smth
diff --git a/atuin-client/src/import/zsh.rs b/atuin-client/src/import/zsh.rs
--- a/atuin-client/src/import/zsh.rs
+++ b/atuin-client/src/import/zsh.rs
@@ -71,19 +93,19 @@ impl Iterator for Zsh {
// better to have some items that should have been part of
// something else, than to miss things. So break.
break;
- }
+ };
- line.push_str(next_line.unwrap().as_str());
+ self.loc -= 1;
}
// We have to handle the case where a line has escaped newlines.
// Keep reading until we have a non-escaped newline
- let extended = line.starts_with(':');
+ let extended = self.strbuf.starts_with(':');
if extended {
self.counter += 1;
- Some(Ok(parse_extended(line.as_str(), self.counter)))
+ Some(Ok(parse_extended(&self.strbuf, self.counter)))
} else {
let time = chrono::Utc::now();
let offset = chrono::Duration::seconds(self.counter);
diff --git a/atuin-client/src/import/zsh.rs b/atuin-client/src/import/zsh.rs
--- a/atuin-client/src/import/zsh.rs
+++ b/atuin-client/src/import/zsh.rs
@@ -93,7 +115,7 @@ impl Iterator for Zsh {
Some(Ok(History::new(
time,
- line.trim_end().to_string(),
+ self.strbuf.trim_end().to_string(),
String::from("unknown"),
-1,
-1,
diff --git a/atuin-client/src/import/zsh.rs b/atuin-client/src/import/zsh.rs
--- a/atuin-client/src/import/zsh.rs
+++ b/atuin-client/src/import/zsh.rs
@@ -102,6 +124,10 @@ impl Iterator for Zsh {
)))
}
}
+
+ fn size_hint(&self) -> (usize, Option<usize>) {
+ (0, Some(self.loc))
+ }
}
fn parse_extended(line: &str, counter: i64) -> History {
diff --git a/src/command/import.rs b/src/command/import.rs
--- a/src/command/import.rs
+++ b/src/command/import.rs
@@ -1,15 +1,11 @@
-use std::env;
-use std::path::PathBuf;
+use std::{env, path::PathBuf};
-use atuin_common::utils::uuid_v4;
-use chrono::{TimeZone, Utc};
-use directories::UserDirs;
use eyre::{eyre, Result};
use structopt::StructOpt;
-use atuin_client::history::History;
use atuin_client::import::{bash::Bash, zsh::Zsh};
-use atuin_client::{database::Database, import::resh::ReshEntry};
+use atuin_client::{database::Database, import::Importer};
+use atuin_client::{history::History, import::resh::Resh};
use indicatif::ProgressBar;
#[derive(StructOpt)]
diff --git a/src/command/import.rs b/src/command/import.rs
--- a/src/command/import.rs
+++ b/src/command/import.rs
@@ -39,6 +35,8 @@ pub enum Cmd {
Resh,
}
+const BATCH_SIZE: usize = 100;
+
impl Cmd {
pub async fn run(&self, db: &mut (impl Database + Send + Sync)) -> Result<()> {
println!(" Atuin ");
|
diff --git a/atuin-client/src/import/bash.rs b/atuin-client/src/import/bash.rs
--- a/atuin-client/src/import/bash.rs
+++ b/atuin-client/src/import/bash.rs
@@ -76,4 +90,45 @@ impl Iterator for Bash {
None,
)))
}
+
+ fn size_hint(&self) -> (usize, Option<usize>) {
+ (0, Some(self.loc))
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use std::io::Cursor;
+
+ use super::Bash;
+
+ #[test]
+ fn test_parse_file() {
+ let input = r"cargo install atuin
+cargo install atuin; \
+cargo update
+cargo :b̷i̶t̴r̵o̴t̴ ̵i̷s̴ ̷r̶e̵a̸l̷
+";
+
+ let cursor = Cursor::new(input);
+ let mut bash = Bash::new(cursor).unwrap();
+ assert_eq!(bash.loc, 4);
+ assert_eq!(bash.size_hint(), (0, Some(4)));
+
+ assert_eq!(
+ &bash.next().unwrap().unwrap().command,
+ "cargo install atuin"
+ );
+ assert_eq!(
+ &bash.next().unwrap().unwrap().command,
+ "cargo install atuin; \\\ncargo update"
+ );
+ assert_eq!(
+ &bash.next().unwrap().unwrap().command,
+ "cargo :b̷i̶t̴r̵o̴t̴ ̵i̷s̴ ̷r̶e̵a̸l̷"
+ );
+ assert!(bash.next().is_none());
+
+ assert_eq!(bash.size_hint(), (0, Some(0)));
+ }
}
diff --git a/atuin-client/src/import/zsh.rs b/atuin-client/src/import/zsh.rs
--- a/atuin-client/src/import/zsh.rs
+++ b/atuin-client/src/import/zsh.rs
@@ -133,10 +159,12 @@ fn parse_extended(line: &str, counter: i64) -> History {
#[cfg(test)]
mod test {
+ use std::io::Cursor;
+
use chrono::prelude::*;
use chrono::Utc;
- use super::parse_extended;
+ use super::*;
#[test]
fn test_parse_extended_simple() {
diff --git a/atuin-client/src/import/zsh.rs b/atuin-client/src/import/zsh.rs
--- a/atuin-client/src/import/zsh.rs
+++ b/atuin-client/src/import/zsh.rs
@@ -164,4 +192,31 @@ mod test {
assert_eq!(parsed.duration, 10_000_000_000);
assert_eq!(parsed.timestamp, Utc.timestamp(1_613_322_469, 0));
}
+
+ #[test]
+ fn test_parse_file() {
+ let input = r": 1613322469:0;cargo install atuin
+: 1613322469:10;cargo install atuin; \
+cargo update
+: 1613322469:10;cargo :b̷i̶t̴r̵o̴t̴ ̵i̷s̴ ̷r̶e̵a̸l̷
+";
+
+ let cursor = Cursor::new(input);
+ let mut zsh = Zsh::new(cursor).unwrap();
+ assert_eq!(zsh.loc, 4);
+ assert_eq!(zsh.size_hint(), (0, Some(4)));
+
+ assert_eq!(&zsh.next().unwrap().unwrap().command, "cargo install atuin");
+ assert_eq!(
+ &zsh.next().unwrap().unwrap().command,
+ "cargo install atuin; \\\ncargo update"
+ );
+ assert_eq!(
+ &zsh.next().unwrap().unwrap().command,
+ "cargo :b̷i̶t̴r̵o̴t̴ ̵i̷s̴ ̷r̶e̵a̸l̷"
+ );
+ assert!(zsh.next().is_none());
+
+ assert_eq!(zsh.size_hint(), (0, Some(0)));
+ }
}
diff --git a/src/command/import.rs b/src/command/import.rs
--- a/src/command/import.rs
+++ b/src/command/import.rs
@@ -55,216 +53,117 @@ impl Cmd {
if shell.ends_with("/zsh") {
println!("Detected ZSH");
- import_zsh(db).await
+ import::<Zsh<_>, _>(db, BATCH_SIZE).await
} else {
println!("cannot import {} history", shell);
Ok(())
}
}
- Self::Zsh => import_zsh(db).await,
- Self::Bash => import_bash(db).await,
- Self::Resh => import_resh(db).await,
- }
- }
-}
-
-async fn import_resh(db: &mut (impl Database + Send + Sync)) -> Result<()> {
- let histpath = std::path::Path::new(std::env::var("HOME")?.as_str()).join(".resh_history.json");
-
- println!("Parsing .resh_history.json...");
- #[allow(clippy::filter_map)]
- let history = std::fs::read_to_string(histpath)?
- .split('\n')
- .map(str::trim)
- .map(|x| serde_json::from_str::<ReshEntry>(x))
- .filter_map(|x| match x {
- Ok(x) => Some(x),
- Err(e) => {
- if e.is_eof() {
- None
- } else {
- warn!("Invalid entry found in resh_history file: {}", e);
- None
- }
- }
- })
- .map(|x| {
- #[allow(clippy::cast_possible_truncation)]
- #[allow(clippy::cast_sign_loss)]
- let timestamp = {
- let secs = x.realtime_before.floor() as i64;
- let nanosecs = (x.realtime_before.fract() * 1_000_000_000_f64).round() as u32;
- Utc.timestamp(secs, nanosecs)
- };
- #[allow(clippy::cast_possible_truncation)]
- #[allow(clippy::cast_sign_loss)]
- let duration = {
- let secs = x.realtime_after.floor() as i64;
- let nanosecs = (x.realtime_after.fract() * 1_000_000_000_f64).round() as u32;
- let difference = Utc.timestamp(secs, nanosecs) - timestamp;
- difference.num_nanoseconds().unwrap_or(0)
- };
-
- History {
- id: uuid_v4(),
- timestamp,
- duration,
- exit: x.exit_code,
- command: x.cmd_line,
- cwd: x.pwd,
- session: uuid_v4(),
- hostname: x.host,
- }
- })
- .collect::<Vec<_>>();
- println!("Updating database...");
-
- let progress = ProgressBar::new(history.len() as u64);
-
- let buf_size = 100;
- let mut buf = Vec::<_>::with_capacity(buf_size);
-
- for i in history {
- buf.push(i);
-
- if buf.len() == buf_size {
- db.save_bulk(&buf).await?;
- progress.inc(buf.len() as u64);
-
- buf.clear();
+ Self::Zsh => import::<Zsh<_>, _>(db, BATCH_SIZE).await,
+ Self::Bash => import::<Bash<_>, _>(db, BATCH_SIZE).await,
+ Self::Resh => import::<Resh, _>(db, BATCH_SIZE).await,
}
}
-
- if !buf.is_empty() {
- db.save_bulk(&buf).await?;
- progress.inc(buf.len() as u64);
- }
- Ok(())
}
-async fn import_zsh(db: &mut (impl Database + Send + Sync)) -> Result<()> {
- // oh-my-zsh sets HISTFILE=~/.zhistory
- // zsh has no default value for this var, but uses ~/.zhistory.
- // we could maybe be smarter about this in the future :)
-
- let histpath = env::var("HISTFILE");
-
- let histpath = if let Ok(p) = histpath {
- let histpath = PathBuf::from(p);
-
- if !histpath.exists() {
- return Err(eyre!(
- "Could not find history file {:?}. try updating $HISTFILE",
- histpath
- ));
- }
-
- histpath
+async fn import<I: Importer + Send, DB: Database + Send + Sync>(
+ db: &mut DB,
+ buf_size: usize,
+) -> Result<()>
+where
+ I::IntoIter: Send,
+{
+ println!("Importing history from {}", I::NAME);
+
+ let histpath = get_histpath::<I>()?;
+ let contents = I::parse(histpath)?;
+
+ let iter = contents.into_iter();
+ let progress = if let (_, Some(upper_bound)) = iter.size_hint() {
+ ProgressBar::new(upper_bound as u64)
} else {
- let user_dirs = UserDirs::new().unwrap();
- let home_dir = user_dirs.home_dir();
-
- let mut candidates = [".zhistory", ".zsh_history"].iter();
- loop {
- match candidates.next() {
- Some(candidate) => {
- let histpath = home_dir.join(candidate);
- if histpath.exists() {
- break histpath;
- }
- }
- None => return Err(eyre!("Could not find history file. try setting $HISTFILE")),
- }
- }
+ ProgressBar::new_spinner()
};
- let zsh = Zsh::new(histpath)?;
-
- let progress = ProgressBar::new(zsh.loc);
-
- let buf_size = 100;
let mut buf = Vec::<History>::with_capacity(buf_size);
+ let mut iter = progress.wrap_iter(iter);
+ loop {
+ // fill until either no more entries
+ // or until the buffer is full
+ let done = fill_buf(&mut buf, &mut iter);
- for i in zsh
- .filter_map(Result::ok)
- .filter(|x| !x.command.trim().is_empty())
- {
- buf.push(i);
-
- if buf.len() == buf_size {
- db.save_bulk(&buf).await?;
- progress.inc(buf.len() as u64);
+ // flush
+ db.save_bulk(&buf).await?;
- buf.clear();
+ if done {
+ break;
}
}
- if !buf.is_empty() {
- db.save_bulk(&buf).await?;
- progress.inc(buf.len() as u64);
- }
-
- progress.finish();
println!("Import complete!");
Ok(())
}
-// TODO: don't just copy paste this lol
-async fn import_bash(db: &mut (impl Database + Send + Sync)) -> Result<()> {
- // oh-my-zsh sets HISTFILE=~/.zhistory
- // zsh has no default value for this var, but uses ~/.zhistory.
- // we could maybe be smarter about this in the future :)
-
- let histpath = env::var("HISTFILE");
-
- let histpath = if let Ok(p) = histpath {
- let histpath = PathBuf::from(p);
-
- if !histpath.exists() {
- return Err(eyre!(
- "Could not find history file {:?}. try updating $HISTFILE",
- histpath
- ));
- }
-
- histpath
+fn get_histpath<I: Importer>() -> Result<PathBuf> {
+ if let Ok(p) = env::var("HISTFILE") {
+ is_file(PathBuf::from(p))
} else {
- let user_dirs = UserDirs::new().unwrap();
- let home_dir = user_dirs.home_dir();
-
- home_dir.join(".bash_history")
- };
-
- let bash = Bash::new(histpath)?;
-
- let progress = ProgressBar::new(bash.loc);
-
- let buf_size = 100;
- let mut buf = Vec::<History>::with_capacity(buf_size);
+ is_file(I::histpath()?)
+ }
+}
- for i in bash
- .filter_map(Result::ok)
- .filter(|x| !x.command.trim().is_empty())
- {
- buf.push(i);
+fn is_file(p: PathBuf) -> Result<PathBuf> {
+ if p.is_file() {
+ Ok(p)
+ } else {
+ Err(eyre!(
+ "Could not find history file {:?}. Try setting $HISTFILE",
+ p
+ ))
+ }
+}
- if buf.len() == buf_size {
- db.save_bulk(&buf).await?;
- progress.inc(buf.len() as u64);
+fn fill_buf<T, E>(buf: &mut Vec<T>, iter: &mut impl Iterator<Item = Result<T, E>>) -> bool {
+ buf.clear();
+ loop {
+ match iter.next() {
+ Some(Ok(t)) => buf.push(t),
+ Some(Err(_)) => (),
+ None => break true,
+ }
- buf.clear();
+ if buf.len() == buf.capacity() {
+ break false;
}
}
+}
- if !buf.is_empty() {
- db.save_bulk(&buf).await?;
- progress.inc(buf.len() as u64);
+#[cfg(test)]
+mod tests {
+ use super::fill_buf;
+
+ #[test]
+ fn test_fill_buf() {
+ let mut buf = Vec::with_capacity(4);
+ let mut iter = vec![
+ Ok(1),
+ Err(2),
+ Ok(3),
+ Ok(4),
+ Err(5),
+ Ok(6),
+ Ok(7),
+ Err(8),
+ Ok(9),
+ ]
+ .into_iter();
+
+ assert!(!fill_buf(&mut buf, &mut iter));
+ assert_eq!(buf, vec![1, 3, 4, 6]);
+
+ assert!(fill_buf(&mut buf, &mut iter));
+ assert_eq!(buf, vec![7, 9]);
}
-
- progress.finish();
- println!("Import complete!");
-
- Ok(())
}
|
Very long history import time with 132k line zsh history file
About 17 hours ago (!), I ran `atuin import zsh`, with `$HISTFILE` set to `$HOME/.zshrc`. My history file has 132,450 raw lines (115,029 actual entries, because of multiline commands). Each command has the timestamp (e.g. 1600602281) and the run duration in seconds.
The format for each entry is—
```
: 1600602281:0;command --args
```
FYI—Some of the commands have strange text in (this output is from `less`):
```
<BA>Ã<A9>© <BA>Ã<A9>®´ <BA>Ã<A9>®Ã<A9>⃨<AB>⃨<83><BA>Ã<A9>©¬©¬¨⃨<83><BA>Ã<A9>¶ <BA>Ã<A9>®Ã<A9>⃨<AB>⃨<83><BA>Ã<A9>©⃨<83><BA>Ã<A9>øcxxxxxxxjjjjjjjjjj <BA>Ã<A4>Ã<A9>⃨<AB>⃨<83><BA>Ã<A9>§⃨<83><BA>Ã<A9>© <BA>Ã<A9>®´ <BA>Ã<A9>®Ã<A9>⃨<AB>⃨<83><BA>Ã<A9>©
¬Ã<BF> <BA>Ã<A9>®Ã<A9>⃨<AB>⃨<83><BA>Ã<A9>©¬
```
It's still going. Any way to fix this and get my 115k zsh history entries into atuin?
|
Wow I hadn't tested on anything quite that large :O Though I have about 15k and it's done in a few seconds, so it shouldn't be taking that long :thinking:
Firstly, you have the ZSH extended history format. It has to be parsed, but that shouldn't be slowing things down in an actually noticeable way. The "strange text" can result from binary being cat-ed, or can sometimes happen if your shell doesn't properly write to the file (power loss or something).
Here's the function that parses each line: https://github.com/ellie/atuin/blob/main/atuin-client/src/import/zsh.rs#L107
We batch inserts into transactions, and commit about 100 at a time. The transaction size is set here: https://github.com/ellie/atuin/blob/main/src/command/import.rs#L103
I'd planned on making that configurable, but didn't think it would ever end up being slow enough that this is required.
Would you be able to change [this](https://github.com/ellie/atuin/blob/main/src/command/import.rs#L103) to a larger value - say, 1000 - and see how that works out?
Alternatively, perhaps the indices are slowing things down. Could definitely do with improving the logging so we can narrow things down a bit better!
Also some more information about your hardware would be fantastic. Is it an SSD?
Ooop! 🤦🏻♂️
@ellie I just discovered that the reason it wasn't working is because my `$HISTFILE` was set **`$HISTILE/.zsh_sessions/`** (which is a _directory_). As soon as I changed it to `.zsh_history`, it imported quickly and beautifully. 🤣
Ahaha, fantastic! Could probably do with checking that $HISTFILE is *actually a file* then, but otherwise I'm glad this is sorted :)
|
2021-05-08T17:42:54Z
|
0.6
|
2021-05-09T17:34:55Z
|
725ea9b16b1e3596b394fa7e47e02a9331de10cf
|
[
"encryption::test::test_encrypt_decrypt",
"import::zsh::test::test_parse_extended_simple"
] |
[] |
[] |
[] |
auto_2025-06-06
|
atuinsh/atuin
| 747
|
atuinsh__atuin-747
|
[
"745"
] |
d46e3ad47d03e53232269973806fb9da2248ba19
|
diff --git a/atuin-client/src/import/bash.rs b/atuin-client/src/import/bash.rs
--- a/atuin-client/src/import/bash.rs
+++ b/atuin-client/src/import/bash.rs
@@ -1,8 +1,10 @@
-use std::{fs::File, io::Read, path::PathBuf};
+use std::{fs::File, io::Read, path::PathBuf, str};
use async_trait::async_trait;
+use chrono::{DateTime, Duration, NaiveDateTime, Utc};
use directories::UserDirs;
use eyre::{eyre, Result};
+use itertools::Itertools;
use super::{get_histpath, unix_byte_lines, Importer, Loader};
use crate::history::History;
diff --git a/atuin-client/src/import/bash.rs b/atuin-client/src/import/bash.rs
--- a/atuin-client/src/import/bash.rs
+++ b/atuin-client/src/import/bash.rs
@@ -32,37 +34,54 @@ impl Importer for Bash {
}
async fn entries(&mut self) -> Result<usize> {
- Ok(super::count_lines(&self.bytes))
+ let count = unix_byte_lines(&self.bytes)
+ .map(LineType::from)
+ .filter(|line| matches!(line, LineType::Command(_)))
+ .count();
+ Ok(count)
}
async fn load(self, h: &mut impl Loader) -> Result<()> {
- let now = chrono::Utc::now();
- let mut line = String::new();
-
- for (i, b) in unix_byte_lines(&self.bytes).enumerate() {
- let s = match std::str::from_utf8(b) {
- Ok(s) => s,
- Err(_) => continue, // we can skip past things like invalid utf8
- };
-
- if let Some(s) = s.strip_suffix('\\') {
- line.push_str(s);
- line.push_str("\\\n");
- } else {
- line.push_str(s);
- let command = std::mem::take(&mut line);
-
- let offset = chrono::Duration::seconds(i as i64);
- h.push(History::new(
- now - offset, // preserve ordering
- command,
- String::from("unknown"),
- -1,
- -1,
- None,
- None,
- ))
- .await?;
+ let lines = unix_byte_lines(&self.bytes)
+ .map(LineType::from)
+ .filter(|line| !matches!(line, LineType::NotUtf8)) // invalid utf8 are ignored
+ .collect_vec();
+
+ let (commands_before_first_timestamp, first_timestamp) = lines
+ .iter()
+ .enumerate()
+ .find_map(|(i, line)| match line {
+ LineType::Timestamp(t) => Some((i, *t)),
+ _ => None,
+ })
+ // if no known timestamps, use now as base
+ .unwrap_or((lines.len(), Utc::now()));
+
+ // if no timestamp is recorded, then use this increment to set an arbitrary timestamp
+ // to preserve ordering
+ let timestamp_increment = Duration::seconds(1);
+ // make sure there is a minimum amount of time before the first known timestamp
+ // to fit all commands, given the default increment
+ let mut next_timestamp =
+ first_timestamp - timestamp_increment * commands_before_first_timestamp as i32;
+
+ for line in lines.into_iter() {
+ match line {
+ LineType::NotUtf8 => unreachable!(), // already filtered
+ LineType::Timestamp(t) => next_timestamp = t,
+ LineType::Command(c) => {
+ let entry = History::new(
+ next_timestamp,
+ c.into(),
+ "unknown".into(),
+ -1,
+ -1,
+ None,
+ None,
+ );
+ h.push(entry).await?;
+ next_timestamp += timestamp_increment;
+ }
}
}
diff --git a/atuin-client/src/import/bash.rs b/atuin-client/src/import/bash.rs
--- a/atuin-client/src/import/bash.rs
+++ b/atuin-client/src/import/bash.rs
@@ -89,7 +137,7 @@ cargo :b̷i̶t̴r̵o̴t̴ ̵i̷s̴ ̷r̶e̵a̸l̷
.to_owned();
let mut bash = Bash { bytes };
- assert_eq!(bash.entries().await.unwrap(), 4);
+ assert_eq!(bash.entries().await.unwrap(), 3);
let mut loader = TestLoader::default();
bash.load(&mut loader).await.unwrap();
|
diff --git a/atuin-client/src/import/bash.rs b/atuin-client/src/import/bash.rs
--- a/atuin-client/src/import/bash.rs
+++ b/atuin-client/src/import/bash.rs
@@ -70,18 +89,47 @@ impl Importer for Bash {
}
}
+#[derive(Debug, Clone)]
+enum LineType<'a> {
+ NotUtf8,
+ /// A timestamp line start with a '#', followed immediately by an integer
+ /// that represents seconds since UNIX epoch.
+ Timestamp(DateTime<Utc>),
+ /// Anything that doesn't look like a timestamp.
+ Command(&'a str),
+}
+impl<'a> From<&'a [u8]> for LineType<'a> {
+ fn from(bytes: &'a [u8]) -> Self {
+ let Ok(line) = str::from_utf8(bytes) else {
+ return LineType::NotUtf8;
+ };
+ let parsed = match try_parse_line_as_timestamp(line) {
+ Some(time) => LineType::Timestamp(time),
+ None => LineType::Command(line),
+ };
+ parsed
+ }
+}
+
+fn try_parse_line_as_timestamp(line: &str) -> Option<DateTime<Utc>> {
+ let seconds = line.strip_prefix('#')?.parse().ok()?;
+ let time = NaiveDateTime::from_timestamp(seconds, 0);
+ Some(DateTime::from_utc(time, Utc))
+}
+
#[cfg(test)]
-mod tests {
- use itertools::assert_equal;
+mod test {
+ use std::cmp::Ordering;
+
+ use itertools::{assert_equal, Itertools};
use crate::import::{tests::TestLoader, Importer};
use super::Bash;
#[tokio::test]
- async fn test_parse_file() {
+ async fn parse_no_timestamps() {
let bytes = r"cargo install atuin
-cargo install atuin; \
cargo update
cargo :b̷i̶t̴r̵o̴t̴ ̵i̷s̴ ̷r̶e̵a̸l̷
"
diff --git a/atuin-client/src/import/bash.rs b/atuin-client/src/import/bash.rs
--- a/atuin-client/src/import/bash.rs
+++ b/atuin-client/src/import/bash.rs
@@ -98,9 +146,72 @@ cargo :b̷i̶t̴r̵o̴t̴ ̵i̷s̴ ̷r̶e̵a̸l̷
loader.buf.iter().map(|h| h.command.as_str()),
[
"cargo install atuin",
- "cargo install atuin; \\\ncargo update",
+ "cargo update",
"cargo :b̷i̶t̴r̵o̴t̴ ̵i̷s̴ ̷r̶e̵a̸l̷",
],
);
+ assert!(is_strictly_sorted(
+ loader.buf.iter().map(|h| h.timestamp.timestamp())
+ ))
+ }
+
+ #[tokio::test]
+ async fn parse_with_timestamps() {
+ let bytes = b"#1672918999
+git reset
+#1672919006
+git clean -dxf
+#1672919020
+cd ../
+"
+ .to_vec();
+
+ let mut bash = Bash { bytes };
+ assert_eq!(bash.entries().await.unwrap(), 3);
+
+ let mut loader = TestLoader::default();
+ bash.load(&mut loader).await.unwrap();
+
+ assert_equal(
+ loader.buf.iter().map(|h| h.command.as_str()),
+ ["git reset", "git clean -dxf", "cd ../"],
+ );
+ assert_equal(
+ loader.buf.iter().map(|h| h.timestamp.timestamp()),
+ [1672918999, 1672919006, 1672919020],
+ )
+ }
+
+ #[tokio::test]
+ async fn parse_with_partial_timestamps() {
+ let bytes = b"git reset
+#1672919006
+git clean -dxf
+cd ../
+"
+ .to_vec();
+
+ let mut bash = Bash { bytes };
+ assert_eq!(bash.entries().await.unwrap(), 3);
+
+ let mut loader = TestLoader::default();
+ bash.load(&mut loader).await.unwrap();
+
+ assert_equal(
+ loader.buf.iter().map(|h| h.command.as_str()),
+ ["git reset", "git clean -dxf", "cd ../"],
+ );
+ assert!(is_strictly_sorted(
+ loader.buf.iter().map(|h| h.timestamp.timestamp())
+ ))
+ }
+
+ fn is_strictly_sorted<T>(iter: impl IntoIterator<Item = T>) -> bool
+ where
+ T: Clone + PartialOrd,
+ {
+ iter.into_iter()
+ .tuple_windows()
+ .all(|(a, b)| matches!(a.partial_cmp(&b), Some(Ordering::Less)))
}
}
|
Bash history import issues
I spotted two issues while trying to import my Bash history:
1. Import ordering is incorrectly reversed.
2. `.bash_history` can be configured to store timestamps, a case not handled.
---
## Ordering
In the following snippet, lines from the top of the file will receive the newest timestamp:
https://github.com/cyqsimon/atuin/blob/d46e3ad47d03e53232269973806fb9da2248ba19/atuin-client/src/import/bash.rs#L42-L67
This is incorrect for `.bash_history` - new items are appended to the end of the file, not the start. So the first lines are in fact the oldest commands.
## Stored timestamps
The current import code for Bash assumes that each line is a command. However if `HISTTIMEFORMAT` is set, then a timestamp is recorded for each command (see `man bash`). So `.bash_history` would look something like this:
```
#1672918999
git reset
#1672919006
git clean -dxf
#1672919020
cd ../
```
This case is currently not handled, so the timestamp lines are getting falsely-imported as commands.
---
I am working on a patch that will fix both these issues, so give me a little while and I'll submit a PR.
The reason I'm posing this issue mostly concerns the extent of the ordering problem. Did it happen because
- the original author used a different shell that does store the newest commands at the start of its history file, and wrongly assumed the same for Bash?
- or the original author made a simple arithmetic mistake, and this is an issue for the import code of all shells?
In other words, I'm not that familiar with other shells, so does the import code for them need fixing as well?
|
2023-03-01T16:30:56Z
|
13.0
|
2023-04-05T15:22:17Z
|
edcd477153d00944c5dae16ec3ba69e339e1450c
|
[
"encryption::test::test_encrypt_decrypt",
"import::zsh::test::test_parse_extended_simple",
"import::zsh::test::test_parse_file",
"import::fish::test::parse_complex",
"import::zsh_histdb::test::test_env_vars",
"import::zsh_histdb::test::test_import",
"database::test::test_search_prefix",
"database::test::test_search_reordered_fuzzy",
"database::test::test_search_fulltext",
"database::test::test_search_fuzzy",
"database::test::test_search_bench_dupes"
] |
[] |
[] |
[] |
auto_2025-06-06
|
|
atuinsh/atuin
| 1,238
|
atuinsh__atuin-1238
|
[
"691"
] |
15abf429842969e56598b1922a21693a7253f117
|
diff --git a/atuin-client/src/api_client.rs b/atuin-client/src/api_client.rs
--- a/atuin-client/src/api_client.rs
+++ b/atuin-client/src/api_client.rs
@@ -1,5 +1,6 @@
use std::collections::HashMap;
use std::env;
+use std::time::Duration;
use eyre::{bail, Result};
use reqwest::{
diff --git a/atuin-client/src/api_client.rs b/atuin-client/src/api_client.rs
--- a/atuin-client/src/api_client.rs
+++ b/atuin-client/src/api_client.rs
@@ -115,6 +121,8 @@ impl<'a> Client<'a> {
client: reqwest::Client::builder()
.user_agent(APP_USER_AGENT)
.default_headers(headers)
+ .connect_timeout(Duration::new(connect_timeout, 0))
+ .timeout(Duration::new(timeout, 0))
.build()?,
})
}
diff --git a/atuin-client/src/record/sync.rs b/atuin-client/src/record/sync.rs
--- a/atuin-client/src/record/sync.rs
+++ b/atuin-client/src/record/sync.rs
@@ -22,7 +22,12 @@ pub enum Operation {
}
pub async fn diff(settings: &Settings, store: &mut impl Store) -> Result<(Vec<Diff>, RecordIndex)> {
- let client = Client::new(&settings.sync_address, &settings.session_token)?;
+ let client = Client::new(
+ &settings.sync_address,
+ &settings.session_token,
+ settings.network_connect_timeout,
+ settings.network_timeout,
+ )?;
let local_index = store.tail_records().await?;
let remote_index = client.record_index().await?;
diff --git a/atuin-client/src/record/sync.rs b/atuin-client/src/record/sync.rs
--- a/atuin-client/src/record/sync.rs
+++ b/atuin-client/src/record/sync.rs
@@ -218,7 +223,12 @@ pub async fn sync_remote(
local_store: &mut impl Store,
settings: &Settings,
) -> Result<(i64, i64)> {
- let client = Client::new(&settings.sync_address, &settings.session_token)?;
+ let client = Client::new(
+ &settings.sync_address,
+ &settings.session_token,
+ settings.network_connect_timeout,
+ settings.network_timeout,
+ )?;
let mut uploaded = 0;
let mut downloaded = 0;
diff --git a/atuin-client/src/settings.rs b/atuin-client/src/settings.rs
--- a/atuin-client/src/settings.rs
+++ b/atuin-client/src/settings.rs
@@ -175,6 +175,9 @@ pub struct Settings {
pub workspaces: bool,
pub ctrl_n_shortcuts: bool,
+ pub network_connect_timeout: u64,
+ pub network_timeout: u64,
+
// This is automatically loaded when settings is created. Do not set in
// config! Keep secrets and settings apart.
pub session_token: String,
diff --git a/atuin-client/src/settings.rs b/atuin-client/src/settings.rs
--- a/atuin-client/src/settings.rs
+++ b/atuin-client/src/settings.rs
@@ -371,6 +374,8 @@ impl Settings {
.set_default("workspaces", false)?
.set_default("ctrl_n_shortcuts", false)?
.set_default("secrets_filter", true)?
+ .set_default("network_connect_timeout", 5)?
+ .set_default("network_timeout", 30)?
.add_source(
Environment::with_prefix("atuin")
.prefix_separator("_")
diff --git a/atuin-client/src/sync.rs b/atuin-client/src/sync.rs
--- a/atuin-client/src/sync.rs
+++ b/atuin-client/src/sync.rs
@@ -189,7 +189,12 @@ async fn sync_upload(
}
pub async fn sync(settings: &Settings, force: bool, db: &mut (impl Database + Send)) -> Result<()> {
- let client = api_client::Client::new(&settings.sync_address, &settings.session_token)?;
+ let client = api_client::Client::new(
+ &settings.sync_address,
+ &settings.session_token,
+ settings.network_connect_timeout,
+ settings.network_timeout,
+ )?;
let key = load_key(settings)?; // encryption key
diff --git a/atuin/src/command/client/account/delete.rs b/atuin/src/command/client/account/delete.rs
--- a/atuin/src/command/client/account/delete.rs
+++ b/atuin/src/command/client/account/delete.rs
@@ -9,7 +9,12 @@ pub async fn run(settings: &Settings) -> Result<()> {
bail!("You are not logged in");
}
- let client = api_client::Client::new(&settings.sync_address, &settings.session_token)?;
+ let client = api_client::Client::new(
+ &settings.sync_address,
+ &settings.session_token,
+ settings.network_connect_timeout,
+ settings.network_timeout,
+ )?;
client.delete().await?;
diff --git a/atuin/src/command/client/sync/status.rs b/atuin/src/command/client/sync/status.rs
--- a/atuin/src/command/client/sync/status.rs
+++ b/atuin/src/command/client/sync/status.rs
@@ -4,7 +4,12 @@ use colored::Colorize;
use eyre::Result;
pub async fn run(settings: &Settings, db: &impl Database) -> Result<()> {
- let client = api_client::Client::new(&settings.sync_address, &settings.session_token)?;
+ let client = api_client::Client::new(
+ &settings.sync_address,
+ &settings.session_token,
+ settings.network_connect_timeout,
+ settings.network_timeout,
+ )?;
let status = client.status().await?;
let last_sync = Settings::last_sync()?;
diff --git a/docs/docs/config/config.md b/docs/docs/config/config.md
--- a/docs/docs/config/config.md
+++ b/docs/docs/config/config.md
@@ -280,3 +280,16 @@ macOS does not have an <kbd>Alt</kbd> key, although terminal emulators can often
# Use Ctrl-0 .. Ctrl-9 instead of Alt-0 .. Alt-9 UI shortcuts
ctrl_n_shortcuts = true
```
+
+## network_timeout
+Default: 30
+
+The max amount of time (in seconds) to wait for a network request. If any
+operations with a sync server take longer than this, the code will fail -
+rather than wait indefinitely.
+
+## network_connect_timeout
+Default: 5
+
+The max time (in seconds) we wait for a connection to become established with a
+remote sync server. Any longer than this and the request will fail.
|
diff --git a/atuin-client/src/api_client.rs b/atuin-client/src/api_client.rs
--- a/atuin-client/src/api_client.rs
+++ b/atuin-client/src/api_client.rs
@@ -106,7 +107,12 @@ pub async fn latest_version() -> Result<Version> {
}
impl<'a> Client<'a> {
- pub fn new(sync_addr: &'a str, session_token: &'a str) -> Result<Self> {
+ pub fn new(
+ sync_addr: &'a str,
+ session_token: &'a str,
+ connect_timeout: u64,
+ timeout: u64,
+ ) -> Result<Self> {
let mut headers = HeaderMap::new();
headers.insert(AUTHORIZATION, format!("Token {session_token}").parse()?);
diff --git a/atuin/tests/sync.rs b/atuin/tests/sync.rs
--- a/atuin/tests/sync.rs
+++ b/atuin/tests/sync.rs
@@ -77,7 +77,7 @@ async fn registration() {
.await
.unwrap();
- let client = api_client::Client::new(&address, ®istration_response.session).unwrap();
+ let client = api_client::Client::new(&address, ®istration_response.session, 5, 30).unwrap();
// the session token works
let status = client.status().await.unwrap();
|
atuin hangs at first start in bad network environments
This issue can be reproduced with the following preconditions:
- a really (as in awfully) bad network environment with a rather large-ish (>=98%) packet loss rate
- using atuin to browse the history the first time after boot
Atuin hangs for an indefinite amount of time while trying to make a request to atuin.sh:
```
connect(13, {sa_family=AF_INET, sin_port=htons(443), sin_addr=inet_addr("104.21.80.213")}, 16) = -1 EINPROGRESS (Operation now in progress)
epoll_ctl(5, EPOLL_CTL_ADD, 13, {events=EPOLLIN|EPOLLOUT|EPOLLRDHUP|EPOLLET, data={u32=1, u64=1}}) = 0
write(4, "\1\0\0\0\0\0\0\0", 8) = 8
epoll_wait(3, [{events=EPOLLIN, data={u32=2147483648, u64=2147483648}}], 1024, 249) = 1
epoll_wait(3, [], 1024, 249) = 0
epoll_wait(3, [], 1024, 51) = 0
write(4, "\1\0\0\0\0\0\0\0", 8) = 8
socket(AF_INET6, SOCK_STREAM|SOCK_CLOEXEC, IPPROTO_TCP) = 14
fcntl(14, F_GETFL) = 0x2 (flags O_RDWR)
fcntl(14, F_SETFL, O_RDWR|O_NONBLOCK) = 0
connect(14, {sa_family=AF_INET6, sin6_port=htons(443), sin6_flowinfo=htonl(0), inet_pton(AF_INET6, "2606:4700:3037::6815:50d5", &sin6_addr), sin6_scope_id=0}, 28) = -1 ENETUNREACH (Network is unreachable)
close(14) = 0
socket(AF_INET6, SOCK_STREAM|SOCK_CLOEXEC, IPPROTO_TCP) = 14
fcntl(14, F_GETFL) = 0x2 (flags O_RDWR)
fcntl(14, F_SETFL, O_RDWR|O_NONBLOCK) = 0
connect(14, {sa_family=AF_INET6, sin6_port=htons(443), sin6_flowinfo=htonl(0), inet_pton(AF_INET6, "2606:4700:3030::ac43:9a5a", &sin6_addr), sin6_scope_id=0}, 28) = -1 ENETUNREACH (Network is unreachable)
close(14) = 0
epoll_wait(3, [{events=EPOLLIN, data={u32=2147483648, u64=2147483648}}], 1024, 523979) = 1
epoll_wait(3, 0x564d2b85abe0, 1024, 523979) = -1 EINTR (Interrupted system call)
```
I have configured atuin for offline usage (e.g. am not using the sync server at atuin.sh) so I suspect this happens while querying what the latest version is, calling `latest_version()` as defined in `api_client.rs`. I haven't spend too much time debugging this yet, but suspect that letting the requests timeout after a few seconds should mitigate this issue.
|
Thanks for the report. I reckon I can rewrite this part to get the version lazily
https://user-images.githubusercontent.com/6625462/216926816-fd536a1c-8f35-4a89-b097-8224638960bd.mov
There we go :)
This issue is sort of fixed but there's a related problem. There were 2 issues here:
1. Atuin _was_ blocking on that network request (fixed by @conradludgate )
2. The Atuin client doesn't appear to use a timeout for any requests to the server, so may end up hanging forever in some cases.
I think the fix for the second issue is to add a timeout to all the reqwest clients created in https://github.com/atuinsh/atuin/blob/main/atuin-client/src/api_client.rs
|
2023-09-17T17:26:20Z
|
16.0
|
2023-09-18T07:39:20Z
|
1735be05d71ec21ffb8648866fca83e210cfe31a
|
[
"encryption::test::test_decode_old",
"encryption::test::test_decode",
"encryption::test::key_encodings",
"encryption::test::test_decode_deleted",
"encryption::test::test_encrypt_decrypt",
"kv::tests::encode_decode",
"import::zsh::test::test_parse_extended_simple",
"import::bash::test::parse_with_partial_timestamps",
"import::bash::test::parse_no_timestamps",
"import::bash::test::parse_with_timestamps",
"import::fish::test::parse_complex",
"import::zsh::test::test_parse_file",
"record::encryption::tests::cannot_decrypt_different_key",
"record::encryption::tests::full_record_round_trip",
"record::encryption::tests::cannot_decrypt_different_id",
"record::encryption::tests::round_trip",
"record::encryption::tests::same_entry_different_output",
"record::encryption::tests::full_record_round_trip_fail",
"record::encryption::tests::re_encrypt_round_trip",
"secrets::tests::test_secrets",
"import::zsh_histdb::test::test_env_vars",
"history::tests::disable_secrets",
"record::sqlite_store::tests::create_db",
"record::sqlite_store::tests::get_record",
"record::sqlite_store::tests::len",
"record::sqlite_store::tests::len_different_tags",
"record::sqlite_store::tests::push_record",
"kv::tests::build_kv",
"import::zsh_histdb::test::test_import",
"record::sync::tests::test_basic_diff",
"record::sync::tests::build_two_way_diff",
"database::test::test_search_prefix",
"record::sync::tests::build_complex_diff",
"database::test::test_search_reordered_fuzzy",
"database::test::test_search_fulltext",
"database::test::test_search_fuzzy",
"record::sqlite_store::tests::append_a_bunch",
"history::tests::privacy_test",
"record::sqlite_store::tests::test_chain",
"database::test::test_search_bench_dupes",
"record::sqlite_store::tests::append_a_big_bunch",
"atuin-client/src/history.rs - history::History::capture (line 149) - compile fail",
"atuin-client/src/history.rs - history::History::import (line 116) - compile fail",
"atuin-client/src/history.rs - history::History::from_db (line 167) - compile fail",
"atuin-client/src/history.rs - history::History::import (line 89)",
"atuin-client/src/history.rs - history::History::capture (line 136)",
"atuin-client/src/history.rs - history::History::import (line 100)"
] |
[] |
[] |
[] |
auto_2025-06-06
|
atuinsh/atuin
| 2,200
|
atuinsh__atuin-2200
|
[
"2199"
] |
a223fcb718101ad10d54ce92857472b2a88a8c48
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -18,6 +18,7 @@ All notable changes to this project will be documented in this file.
### Features
+- *(client)* Identify several other GitHub token types as secrets
- *(daemon)* Follow XDG_RUNTIME_DIR if set ([#2171](https://github.com/atuinsh/atuin/issues/2171))
- *(gui)* Automatically install and setup the cli/shell ([#2139](https://github.com/atuinsh/atuin/issues/2139))
- *(gui)* Add activity calendar to the homepage ([#2160](https://github.com/atuinsh/atuin/issues/2160))
|
diff --git a/crates/atuin-client/src/secrets.rs b/crates/atuin-client/src/secrets.rs
--- a/crates/atuin-client/src/secrets.rs
+++ b/crates/atuin-client/src/secrets.rs
@@ -1,76 +1,109 @@
// This file will probably trigger a lot of scanners. Sorry.
+pub enum TestValue<'a> {
+ Single(&'a str),
+ Multiple(&'a [&'a str]),
+}
+
// A list of (name, regex, test), where test should match against regex
-pub static SECRET_PATTERNS: &[(&str, &str, &str)] = &[
+pub static SECRET_PATTERNS: &[(&str, &str, TestValue)] = &[
(
"AWS Access Key ID",
"AKIA[0-9A-Z]{16}",
- "AKIAIOSFODNN7EXAMPLE",
+ TestValue::Single("AKIAIOSFODNN7EXAMPLE"),
),
(
"AWS secret access key env var",
"AWS_ACCESS_KEY_ID",
- "export AWS_ACCESS_KEY_ID=KEYDATA",
+ TestValue::Single("export AWS_ACCESS_KEY_ID=KEYDATA"),
),
(
"AWS secret access key env var",
"AWS_ACCESS_KEY_ID",
- "export AWS_ACCESS_KEY_ID=KEYDATA",
+ TestValue::Single("export AWS_ACCESS_KEY_ID=KEYDATA"),
),
(
"Microsoft Azure secret access key env var",
"AZURE_.*_KEY",
- "export AZURE_STORAGE_ACCOUNT_KEY=KEYDATA",
+ TestValue::Single("export AZURE_STORAGE_ACCOUNT_KEY=KEYDATA"),
),
(
"Google cloud platform key env var",
"GOOGLE_SERVICE_ACCOUNT_KEY",
- "export GOOGLE_SERVICE_ACCOUNT_KEY=KEYDATA",
+ TestValue::Single("export GOOGLE_SERVICE_ACCOUNT_KEY=KEYDATA"),
),
(
"Atuin login",
r"atuin\s+login",
- "atuin login -u mycoolusername -p mycoolpassword -k \"lots of random words\"",
+ TestValue::Single("atuin login -u mycoolusername -p mycoolpassword -k \"lots of random words\""),
),
(
"GitHub PAT (old)",
"ghp_[a-zA-Z0-9]{36}",
- "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", // legit, I expired it
+ TestValue::Single("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"), // legit, I expired it
),
(
"GitHub PAT (new)",
- "github_pat_[a-zA-Z0-9]{22}_[a-zA-Z0-9]{59}",
- "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", // also legit, also expired
+ "gh1_[A-Za-z0-9]{21}_[A-Za-z0-9]{59}|github_pat_[0-9][A-Za-z0-9]{21}_[A-Za-z0-9]{59}",
+ TestValue::Multiple(&[
+ "gh1_1234567890abcdefghijk_1234567890abcdefghijklmnopqrstuvwxyz1234567890abcdefghijklm",
+ "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", // also legit, also expired
+ ])
+ ),
+ (
+ "GitHub OAuth Access Token",
+ "gho_[A-Za-z0-9]{36}",
+ TestValue::Single("gho_1234567890abcdefghijklmnopqrstuvwx000"), // not a real token
+ ),
+ (
+ "GitHub OAuth Access Token (user)",
+ "ghu_[A-Za-z0-9]{36}",
+ TestValue::Single("ghu_1234567890abcdefghijklmnopqrstuvwx000"), // not a real token
+ ),
+ (
+ "GitHub App Installation Access Token",
+ "ghs_[A-Za-z0-9]{36}",
+ TestValue::Single("ghs_1234567890abcdefghijklmnopqrstuvwx000"), // not a real token
+ ),
+ (
+ "GitHub Refresh Token",
+ "ghr_[A-Za-z0-9]{76}",
+ TestValue::Single("ghr_1234567890abcdefghijklmnopqrstuvwx1234567890abcdefghijklmnopqrstuvwx1234567890abcdefghijklmnopqrstuvwx"), // not a real token
+ ),
+ (
+ "GitHub App Installation Access Token v1",
+ "v1\\.[0-9A-Fa-f]{40}",
+ TestValue::Single("v1.1234567890abcdef1234567890abcdef12345678"), // not a real token
),
(
"GitLab PAT",
"glpat-[a-zA-Z0-9_]{20}",
- "glpat-RkE_BG5p_bbjML21WSfy",
+ TestValue::Single("glpat-RkE_BG5p_bbjML21WSfy"),
),
(
"Slack OAuth v2 bot",
"xoxb-[0-9]{11}-[0-9]{11}-[0-9a-zA-Z]{24}",
- "xoxb-17653672481-19874698323-pdFZKVeTuE8sk7oOcBrzbqgy",
+ TestValue::Single("xoxb-17653672481-19874698323-pdFZKVeTuE8sk7oOcBrzbqgy"),
),
(
"Slack OAuth v2 user token",
"xoxp-[0-9]{11}-[0-9]{11}-[0-9a-zA-Z]{24}",
- "xoxp-17653672481-19874698323-pdFZKVeTuE8sk7oOcBrzbqgy",
+ TestValue::Single("xoxp-17653672481-19874698323-pdFZKVeTuE8sk7oOcBrzbqgy"),
),
(
"Slack webhook",
"T[a-zA-Z0-9_]{8}/B[a-zA-Z0-9_]{8}/[a-zA-Z0-9_]{24}",
- "https://hooks.slack.com/services/T00000000/B00000000/XXXXXXXXXXXXXXXXXXXXXXXX",
+ TestValue::Single("https://hooks.slack.com/services/T00000000/B00000000/XXXXXXXXXXXXXXXXXXXXXXXX"),
),
- ("Stripe test key", "sk_test_[0-9a-zA-Z]{24}", "sk_test_1234567890abcdefghijklmnop"),
- ("Stripe live key", "sk_live_[0-9a-zA-Z]{24}", "sk_live_1234567890abcdefghijklmnop"),
+ ("Stripe test key", "sk_test_[0-9a-zA-Z]{24}", TestValue::Single("sk_test_1234567890abcdefghijklmnop")),
+ ("Stripe live key", "sk_live_[0-9a-zA-Z]{24}", TestValue::Single("sk_live_1234567890abcdefghijklmnop")),
];
#[cfg(test)]
mod tests {
use regex::Regex;
- use crate::secrets::SECRET_PATTERNS;
+ use crate::secrets::{TestValue, SECRET_PATTERNS};
#[test]
fn test_secrets() {
diff --git a/crates/atuin-client/src/secrets.rs b/crates/atuin-client/src/secrets.rs
--- a/crates/atuin-client/src/secrets.rs
+++ b/crates/atuin-client/src/secrets.rs
@@ -78,7 +111,19 @@ mod tests {
let re =
Regex::new(regex).unwrap_or_else(|_| panic!("Failed to compile regex for {name}"));
- assert!(re.is_match(test), "{name} test failed!");
+ match test {
+ TestValue::Single(test) => {
+ assert!(re.is_match(test), "{name} test failed!");
+ }
+ TestValue::Multiple(tests) => {
+ for test_str in tests.iter() {
+ assert!(
+ re.is_match(test_str),
+ "{name} test with value \"{test_str}\" failed!"
+ );
+ }
+ }
+ }
}
}
}
|
Expand on the set of GitHub tokens that Atuin will consider secrets
GitHub has multiple token types, not just PATs. It'd be a good idea to filter those out, as well.
|
2024-06-25T17:57:31Z
|
0.3
|
2024-06-25T20:24:32Z
|
6e15286f0c94b89d4c5f9b8fa1e9a72cd209017c
|
[
"record::sqlite_store::tests::create_db",
"kv::tests::build_kv",
"record::sqlite_store::tests::len_tag",
"record::sqlite_store::tests::push_record",
"record::sqlite_store::tests::len",
"record::sqlite_store::tests::get_record",
"record::sqlite_store::tests::first",
"record::sqlite_store::tests::len_different_tags",
"record::sqlite_store::tests::last",
"record::sync::tests::test_basic_diff",
"record::sync::tests::build_two_way_diff",
"database::test::test_search_reordered_fuzzy",
"record::sync::tests::build_complex_diff",
"record::sqlite_store::tests::re_encrypt",
"database::test::test_search_fulltext",
"record::sqlite_store::tests::append_a_bunch",
"record::sqlite_store::tests::append_a_big_bunch"
] |
[
"encryption::test::test_decode",
"encryption::test::test_decode_deleted",
"encryption::test::key_encodings",
"encryption::test::test_decode_old",
"history::store::tests::test_serialize_deserialize_delete",
"history::store::tests::test_serialize_deserialize_create",
"history::tests::test_serialize_deserialize_deleted",
"history::tests::test_serialize_deserialize",
"history::tests::test_serialize_deserialize_version",
"encryption::test::test_encrypt_decrypt",
"import::xonsh::tests::test_hist_dir_xonsh",
"import::xonsh_sqlite::tests::test_db_path_xonsh",
"import::bash::test::parse_with_partial_timestamps",
"import::bash::test::parse_no_timestamps",
"import::fish::test::parse_complex",
"kv::tests::encode_decode",
"import::replxx::test::parse_complex",
"import::bash::test::parse_with_timestamps",
"import::zsh::test::test_parse_extended_simple",
"import::zsh::test::test_parse_metafied",
"import::zsh::test::test_parse_file",
"record::encryption::tests::cannot_decrypt_different_id",
"record::encryption::tests::cannot_decrypt_different_key",
"record::encryption::tests::full_record_round_trip_fail",
"record::encryption::tests::full_record_round_trip",
"record::encryption::tests::round_trip",
"record::encryption::tests::same_entry_different_output",
"settings::tests::can_parse_offset_timezone_spec",
"record::encryption::tests::re_encrypt_round_trip",
"import::xonsh::tests::test_import",
"secrets::tests::test_secrets",
"import::zsh_histdb::test::test_env_vars",
"history::tests::disable_secrets",
"import::xonsh_sqlite::tests::test_import",
"import::zsh_histdb::test::test_import",
"database::test::test_search_prefix",
"database::test::test_search_fuzzy",
"history::tests::privacy_test",
"database::test::test_search_bench_dupes",
"crates/atuin-client/src/history.rs - history::History::from_db (line 352) - compile fail",
"crates/atuin-client/src/history.rs - history::History::daemon (line 332) - compile fail",
"crates/atuin-client/src/history.rs - history::History::capture (line 292) - compile fail",
"crates/atuin-client/src/history.rs - history::History::import (line 259) - compile fail",
"crates/atuin-client/src/history.rs - history::History::capture (line 279)",
"crates/atuin-client/src/history.rs - history::History::daemon (line 317)",
"crates/atuin-client/src/history.rs - history::History::import (line 243)",
"crates/atuin-client/src/history.rs - history::History::import (line 232)"
] |
[] |
[] |
auto_2025-06-06
|
|
atuinsh/atuin
| 1,590
|
atuinsh__atuin-1590
|
[
"1503"
] |
10f465da8ff113819d435b0f8e5066783c5100af
|
diff --git a/atuin-client/config.toml b/atuin-client/config.toml
--- a/atuin-client/config.toml
+++ b/atuin-client/config.toml
@@ -134,6 +134,12 @@ enter_accept = true
## the specified one.
# keymap_mode = "auto"
+# network_connect_timeout = 5
+# network_timeout = 5
+
+## Timeout (in seconds) for acquiring a local database connection (sqlite)
+# local_timeout = 5
+
#[stats]
# Set commands where we should consider the subcommand for statistics. Eg, kubectl get vs just kubectl
#common_subcommands = [
diff --git a/atuin-client/src/database.rs b/atuin-client/src/database.rs
--- a/atuin-client/src/database.rs
+++ b/atuin-client/src/database.rs
@@ -2,6 +2,7 @@ use std::{
env,
path::{Path, PathBuf},
str::FromStr,
+ time::Duration,
};
use async_trait::async_trait;
diff --git a/atuin-client/src/database.rs b/atuin-client/src/database.rs
--- a/atuin-client/src/database.rs
+++ b/atuin-client/src/database.rs
@@ -123,7 +124,7 @@ pub struct Sqlite {
}
impl Sqlite {
- pub async fn new(path: impl AsRef<Path>) -> Result<Self> {
+ pub async fn new(path: impl AsRef<Path>, timeout: f64) -> Result<Self> {
let path = path.as_ref();
debug!("opening sqlite database at {:?}", path);
diff --git a/atuin-client/src/database.rs b/atuin-client/src/database.rs
--- a/atuin-client/src/database.rs
+++ b/atuin-client/src/database.rs
@@ -138,7 +139,10 @@ impl Sqlite {
.journal_mode(SqliteJournalMode::Wal)
.create_if_missing(true);
- let pool = SqlitePoolOptions::new().connect_with(opts).await?;
+ let pool = SqlitePoolOptions::new()
+ .acquire_timeout(Duration::from_secs_f64(timeout))
+ .connect_with(opts)
+ .await?;
Self::setup_db(&pool).await?;
diff --git a/atuin-client/src/record/sqlite_store.rs b/atuin-client/src/record/sqlite_store.rs
--- a/atuin-client/src/record/sqlite_store.rs
+++ b/atuin-client/src/record/sqlite_store.rs
@@ -2,8 +2,8 @@
// Multiple stores of multiple types are all stored in one chonky table (for now), and we just index
// by tag/host
-use std::path::Path;
use std::str::FromStr;
+use std::{path::Path, time::Duration};
use async_trait::async_trait;
use eyre::{eyre, Result};
diff --git a/atuin-client/src/record/sqlite_store.rs b/atuin-client/src/record/sqlite_store.rs
--- a/atuin-client/src/record/sqlite_store.rs
+++ b/atuin-client/src/record/sqlite_store.rs
@@ -27,7 +27,7 @@ pub struct SqliteStore {
}
impl SqliteStore {
- pub async fn new(path: impl AsRef<Path>) -> Result<Self> {
+ pub async fn new(path: impl AsRef<Path>, timeout: f64) -> Result<Self> {
let path = path.as_ref();
debug!("opening sqlite database at {:?}", path);
diff --git a/atuin-client/src/record/sqlite_store.rs b/atuin-client/src/record/sqlite_store.rs
--- a/atuin-client/src/record/sqlite_store.rs
+++ b/atuin-client/src/record/sqlite_store.rs
@@ -44,7 +44,10 @@ impl SqliteStore {
.foreign_keys(true)
.create_if_missing(true);
- let pool = SqlitePoolOptions::new().connect_with(opts).await?;
+ let pool = SqlitePoolOptions::new()
+ .acquire_timeout(Duration::from_secs_f64(timeout))
+ .connect_with(opts)
+ .await?;
Self::setup_db(&pool).await?;
diff --git a/atuin-client/src/settings.rs b/atuin-client/src/settings.rs
--- a/atuin-client/src/settings.rs
+++ b/atuin-client/src/settings.rs
@@ -244,6 +244,7 @@ pub struct Settings {
pub network_connect_timeout: u64,
pub network_timeout: u64,
+ pub local_timeout: f64,
pub enter_accept: bool,
#[serde(default)]
diff --git a/atuin-client/src/settings.rs b/atuin-client/src/settings.rs
--- a/atuin-client/src/settings.rs
+++ b/atuin-client/src/settings.rs
@@ -456,6 +457,7 @@ impl Settings {
.set_default("secrets_filter", true)?
.set_default("network_connect_timeout", 5)?
.set_default("network_timeout", 30)?
+ .set_default("local_timeout", 2.0)?
// enter_accept defaults to false here, but true in the default config file. The dissonance is
// intentional!
// Existing users will get the default "False", so we don't mess with any potential
diff --git a/atuin/src/command/client.rs b/atuin/src/command/client.rs
--- a/atuin/src/command/client.rs
+++ b/atuin/src/command/client.rs
@@ -82,8 +82,8 @@ impl Cmd {
let db_path = PathBuf::from(settings.db_path.as_str());
let record_store_path = PathBuf::from(settings.record_store_path.as_str());
- let db = Sqlite::new(db_path).await?;
- let sqlite_store = SqliteStore::new(record_store_path).await?;
+ let db = Sqlite::new(db_path, settings.local_timeout).await?;
+ let sqlite_store = SqliteStore::new(record_store_path, settings.local_timeout).await?;
match self {
Self::History(history) => history.run(&settings, &db, sqlite_store).await,
|
diff --git a/atuin-client/src/database.rs b/atuin-client/src/database.rs
--- a/atuin-client/src/database.rs
+++ b/atuin-client/src/database.rs
@@ -786,7 +790,7 @@ mod test {
#[tokio::test(flavor = "multi_thread")]
async fn test_search_prefix() {
- let mut db = Sqlite::new("sqlite::memory:").await.unwrap();
+ let mut db = Sqlite::new("sqlite::memory:", 0.1).await.unwrap();
new_history_item(&mut db, "ls /home/ellie").await.unwrap();
assert_search_eq(&db, SearchMode::Prefix, FilterMode::Global, "ls", 1)
diff --git a/atuin-client/src/database.rs b/atuin-client/src/database.rs
--- a/atuin-client/src/database.rs
+++ b/atuin-client/src/database.rs
@@ -802,7 +806,7 @@ mod test {
#[tokio::test(flavor = "multi_thread")]
async fn test_search_fulltext() {
- let mut db = Sqlite::new("sqlite::memory:").await.unwrap();
+ let mut db = Sqlite::new("sqlite::memory:", 0.1).await.unwrap();
new_history_item(&mut db, "ls /home/ellie").await.unwrap();
assert_search_eq(&db, SearchMode::FullText, FilterMode::Global, "ls", 1)
diff --git a/atuin-client/src/database.rs b/atuin-client/src/database.rs
--- a/atuin-client/src/database.rs
+++ b/atuin-client/src/database.rs
@@ -818,7 +822,7 @@ mod test {
#[tokio::test(flavor = "multi_thread")]
async fn test_search_fuzzy() {
- let mut db = Sqlite::new("sqlite::memory:").await.unwrap();
+ let mut db = Sqlite::new("sqlite::memory:", 0.1).await.unwrap();
new_history_item(&mut db, "ls /home/ellie").await.unwrap();
new_history_item(&mut db, "ls /home/frank").await.unwrap();
new_history_item(&mut db, "cd /home/Ellie").await.unwrap();
diff --git a/atuin-client/src/database.rs b/atuin-client/src/database.rs
--- a/atuin-client/src/database.rs
+++ b/atuin-client/src/database.rs
@@ -908,7 +912,7 @@ mod test {
#[tokio::test(flavor = "multi_thread")]
async fn test_search_reordered_fuzzy() {
- let mut db = Sqlite::new("sqlite::memory:").await.unwrap();
+ let mut db = Sqlite::new("sqlite::memory:", 0.1).await.unwrap();
// test ordering of results: we should choose the first, even though it happened longer ago.
new_history_item(&mut db, "curl").await.unwrap();
diff --git a/atuin-client/src/database.rs b/atuin-client/src/database.rs
--- a/atuin-client/src/database.rs
+++ b/atuin-client/src/database.rs
@@ -942,7 +946,7 @@ mod test {
git_root: None,
};
- let mut db = Sqlite::new("sqlite::memory:").await.unwrap();
+ let mut db = Sqlite::new("sqlite::memory:", 0.1).await.unwrap();
for _i in 1..10000 {
new_history_item(&mut db, "i am a duplicated command")
.await
diff --git a/atuin-client/src/kv.rs b/atuin-client/src/kv.rs
--- a/atuin-client/src/kv.rs
+++ b/atuin-client/src/kv.rs
@@ -221,7 +221,7 @@ mod tests {
#[tokio::test]
async fn build_kv() {
- let mut store = SqliteStore::new(":memory:").await.unwrap();
+ let mut store = SqliteStore::new(":memory:", 0.1).await.unwrap();
let kv = KvStore::new();
let key: [u8; 32] = XSalsa20Poly1305::generate_key(&mut OsRng).into();
let host_id = atuin_common::record::HostId(atuin_common::utils::uuid_v7());
diff --git a/atuin-client/src/record/sqlite_store.rs b/atuin-client/src/record/sqlite_store.rs
--- a/atuin-client/src/record/sqlite_store.rs
+++ b/atuin-client/src/record/sqlite_store.rs
@@ -261,7 +264,7 @@ mod tests {
#[tokio::test]
async fn create_db() {
- let db = SqliteStore::new(":memory:").await;
+ let db = SqliteStore::new(":memory:", 0.1).await;
assert!(
db.is_ok(),
diff --git a/atuin-client/src/record/sqlite_store.rs b/atuin-client/src/record/sqlite_store.rs
--- a/atuin-client/src/record/sqlite_store.rs
+++ b/atuin-client/src/record/sqlite_store.rs
@@ -272,7 +275,7 @@ mod tests {
#[tokio::test]
async fn push_record() {
- let db = SqliteStore::new(":memory:").await.unwrap();
+ let db = SqliteStore::new(":memory:", 0.1).await.unwrap();
let record = test_record();
db.push(&record).await.expect("failed to insert record");
diff --git a/atuin-client/src/record/sqlite_store.rs b/atuin-client/src/record/sqlite_store.rs
--- a/atuin-client/src/record/sqlite_store.rs
+++ b/atuin-client/src/record/sqlite_store.rs
@@ -280,7 +283,7 @@ mod tests {
#[tokio::test]
async fn get_record() {
- let db = SqliteStore::new(":memory:").await.unwrap();
+ let db = SqliteStore::new(":memory:", 0.1).await.unwrap();
let record = test_record();
db.push(&record).await.unwrap();
diff --git a/atuin-client/src/record/sqlite_store.rs b/atuin-client/src/record/sqlite_store.rs
--- a/atuin-client/src/record/sqlite_store.rs
+++ b/atuin-client/src/record/sqlite_store.rs
@@ -291,7 +294,7 @@ mod tests {
#[tokio::test]
async fn last() {
- let db = SqliteStore::new(":memory:").await.unwrap();
+ let db = SqliteStore::new(":memory:", 0.1).await.unwrap();
let record = test_record();
db.push(&record).await.unwrap();
diff --git a/atuin-client/src/record/sqlite_store.rs b/atuin-client/src/record/sqlite_store.rs
--- a/atuin-client/src/record/sqlite_store.rs
+++ b/atuin-client/src/record/sqlite_store.rs
@@ -309,7 +312,7 @@ mod tests {
#[tokio::test]
async fn first() {
- let db = SqliteStore::new(":memory:").await.unwrap();
+ let db = SqliteStore::new(":memory:", 0.1).await.unwrap();
let record = test_record();
db.push(&record).await.unwrap();
diff --git a/atuin-client/src/record/sqlite_store.rs b/atuin-client/src/record/sqlite_store.rs
--- a/atuin-client/src/record/sqlite_store.rs
+++ b/atuin-client/src/record/sqlite_store.rs
@@ -327,7 +330,7 @@ mod tests {
#[tokio::test]
async fn len() {
- let db = SqliteStore::new(":memory:").await.unwrap();
+ let db = SqliteStore::new(":memory:", 0.1).await.unwrap();
let record = test_record();
db.push(&record).await.unwrap();
diff --git a/atuin-client/src/record/sqlite_store.rs b/atuin-client/src/record/sqlite_store.rs
--- a/atuin-client/src/record/sqlite_store.rs
+++ b/atuin-client/src/record/sqlite_store.rs
@@ -341,7 +344,7 @@ mod tests {
#[tokio::test]
async fn len_different_tags() {
- let db = SqliteStore::new(":memory:").await.unwrap();
+ let db = SqliteStore::new(":memory:", 0.1).await.unwrap();
// these have different tags, so the len should be the same
// we model multiple stores within one database
diff --git a/atuin-client/src/record/sqlite_store.rs b/atuin-client/src/record/sqlite_store.rs
--- a/atuin-client/src/record/sqlite_store.rs
+++ b/atuin-client/src/record/sqlite_store.rs
@@ -361,7 +364,7 @@ mod tests {
#[tokio::test]
async fn append_a_bunch() {
- let db = SqliteStore::new(":memory:").await.unwrap();
+ let db = SqliteStore::new(":memory:", 0.1).await.unwrap();
let mut tail = test_record();
db.push(&tail).await.expect("failed to push record");
diff --git a/atuin-client/src/record/sqlite_store.rs b/atuin-client/src/record/sqlite_store.rs
--- a/atuin-client/src/record/sqlite_store.rs
+++ b/atuin-client/src/record/sqlite_store.rs
@@ -380,7 +383,7 @@ mod tests {
#[tokio::test]
async fn append_a_big_bunch() {
- let db = SqliteStore::new(":memory:").await.unwrap();
+ let db = SqliteStore::new(":memory:", 0.1).await.unwrap();
let mut records: Vec<Record<EncryptedData>> = Vec::with_capacity(10000);
diff --git a/atuin-client/src/record/sync.rs b/atuin-client/src/record/sync.rs
--- a/atuin-client/src/record/sync.rs
+++ b/atuin-client/src/record/sync.rs
@@ -317,10 +317,10 @@ mod tests {
local_records: Vec<Record<EncryptedData>>,
remote_records: Vec<Record<EncryptedData>>,
) -> (SqliteStore, Vec<Diff>) {
- let local_store = SqliteStore::new(":memory:")
+ let local_store = SqliteStore::new(":memory:", 0.1)
.await
.expect("failed to open in memory sqlite");
- let remote_store = SqliteStore::new(":memory:")
+ let remote_store = SqliteStore::new(":memory:", 0.1)
.await
.expect("failed to open in memory sqlite"); // "remote"
|
atuin makes the shell unresponsive under high I/O pressure
Hi!
Under high I/O pressure on my system, atuin makes my shell hang for a long period, then fail with this error:
```
Error: pool timed out while waiting for an open connection
Location:
atuin/src/command/client.rs:50:22
```
or
```
Error: error returned from database: (code: 5) database is locked
Caused by:
(code: 5) database is locked
Location:
atuin/src/command/client/history.rs:199:17
```
I'd love to see a `register_timeout` in milliseconds, similar to `network_timeout`. So when `atuin` would register a new entry in history, if after `register_timeout` it still hasn't successfully registered the entry, it aborts the transaction and quits.
At least for me, better to have a few entries discarded than having a completely unresponsive shell under high IO/pressure.
What do you think?
|
Sure that makes sense to me! We'd have to ensure that `atuin history end` doesn't break after an aborted `atuin history start`, but otherwise sounds good
Just a small question, did you find a way to "unlock" the shell ? After it's locked, how do you restore the system to a state where it responds to terminal commands again ?
|
2024-01-19T15:34:48Z
|
17.2
|
2024-01-21T13:24:00Z
|
4b20544474088259c580faa015876cb535dbff36
|
[
"encryption::test::key_encodings",
"encryption::test::test_decode_old",
"history::store::tests::test_serialize_deserialize_delete",
"encryption::test::test_decode",
"encryption::test::test_decode_deleted",
"history::store::tests::test_serialize_deserialize_create",
"history::tests::test_serialize_deserialize",
"history::tests::test_serialize_deserialize_deleted",
"history::tests::test_serialize_deserialize_version",
"encryption::test::test_encrypt_decrypt",
"kv::tests::encode_decode",
"import::bash::test::parse_no_timestamps",
"import::bash::test::parse_with_partial_timestamps",
"import::bash::test::parse_with_timestamps",
"import::zsh::test::test_parse_extended_simple",
"import::zsh::test::test_parse_file",
"import::zsh::test::test_parse_metafied",
"import::fish::test::parse_complex",
"record::encryption::tests::cannot_decrypt_different_id",
"record::encryption::tests::cannot_decrypt_different_key",
"record::encryption::tests::full_record_round_trip",
"record::encryption::tests::full_record_round_trip_fail",
"record::encryption::tests::round_trip",
"record::encryption::tests::same_entry_different_output",
"record::encryption::tests::re_encrypt_round_trip",
"secrets::tests::test_secrets",
"history::tests::disable_secrets",
"import::zsh_histdb::test::test_env_vars",
"record::sqlite_store::tests::create_db",
"record::sqlite_store::tests::last",
"record::sqlite_store::tests::first",
"record::sqlite_store::tests::get_record",
"record::sqlite_store::tests::push_record",
"record::sqlite_store::tests::len",
"kv::tests::build_kv",
"import::zsh_histdb::test::test_import",
"record::sqlite_store::tests::len_different_tags",
"record::sync::tests::test_basic_diff",
"history::tests::privacy_test",
"database::test::test_search_fulltext",
"record::sync::tests::build_two_way_diff",
"database::test::test_search_reordered_fuzzy",
"database::test::test_search_prefix",
"record::sync::tests::build_complex_diff",
"database::test::test_search_fuzzy",
"record::sqlite_store::tests::append_a_bunch",
"database::test::test_search_bench_dupes",
"record::sqlite_store::tests::append_a_big_bunch",
"atuin-client/src/history.rs - history::History::capture (line 297) - compile fail",
"atuin-client/src/history.rs - history::History::from_db (line 315) - compile fail",
"atuin-client/src/history.rs - history::History::import (line 264) - compile fail",
"atuin-client/src/history.rs - history::History::import (line 237)",
"atuin-client/src/history.rs - history::History::capture (line 284)",
"atuin-client/src/history.rs - history::History::import (line 248)"
] |
[] |
[] |
[] |
auto_2025-06-06
|
atuinsh/atuin
| 1,296
|
atuinsh__atuin-1296
|
[
"854"
] |
a60d8934c5dfcf0679dfa5f4de5c2080dfd32a5f
|
diff --git a/atuin-client/src/database.rs b/atuin-client/src/database.rs
--- a/atuin-client/src/database.rs
+++ b/atuin-client/src/database.rs
@@ -18,6 +18,8 @@ use sqlx::{
};
use time::OffsetDateTime;
+use crate::history::HistoryStats;
+
use super::{
history::History,
ordering,
diff --git a/atuin-client/src/database.rs b/atuin-client/src/database.rs
--- a/atuin-client/src/database.rs
+++ b/atuin-client/src/database.rs
@@ -109,6 +111,8 @@ pub trait Database: Send + Sync + 'static {
async fn query_history(&self, query: &str) -> Result<Vec<History>>;
async fn all_with_count(&self) -> Result<Vec<(History, i32)>>;
+
+ async fn stats(&self, h: &History) -> Result<HistoryStats>;
}
// Intended for use on a developer machine and not a sync server.
diff --git a/atuin-client/src/history.rs b/atuin-client/src/history.rs
--- a/atuin-client/src/history.rs
+++ b/atuin-client/src/history.rs
@@ -71,6 +71,26 @@ pub struct History {
pub deleted_at: Option<OffsetDateTime>,
}
+#[derive(Debug, Clone, PartialEq, Eq, sqlx::FromRow)]
+pub struct HistoryStats {
+ /// The command that was ran after this one in the session
+ pub next: Option<History>,
+ ///
+ /// The command that was ran before this one in the session
+ pub previous: Option<History>,
+
+ /// How many times has this command been ran?
+ pub total: u64,
+
+ pub average_duration: u64,
+
+ pub exits: Vec<(i64, i64)>,
+
+ pub day_of_week: Vec<(String, i64)>,
+
+ pub duration_over_time: Vec<(String, i64)>,
+}
+
impl History {
#[allow(clippy::too_many_arguments)]
fn new(
diff --git a/atuin/src/command/client/search.rs b/atuin/src/command/client/search.rs
--- a/atuin/src/command/client/search.rs
+++ b/atuin/src/command/client/search.rs
@@ -15,8 +15,10 @@ mod cursor;
mod duration;
mod engines;
mod history_list;
+mod inspector;
mod interactive;
-pub use duration::{format_duration, format_duration_into};
+
+pub use duration::format_duration_into;
#[allow(clippy::struct_excessive_bools, clippy::struct_field_names)]
#[derive(Parser, Debug)]
diff --git a/atuin/src/command/client/search/history_list.rs b/atuin/src/command/client/search/history_list.rs
--- a/atuin/src/command/client/search/history_list.rs
+++ b/atuin/src/command/client/search/history_list.rs
@@ -9,7 +9,7 @@ use ratatui::{
};
use time::OffsetDateTime;
-use super::format_duration;
+use super::duration::format_duration;
pub struct HistoryList<'a> {
history: &'a [History],
diff --git /dev/null b/atuin/src/command/client/search/inspector.rs
new file mode 100644
--- /dev/null
+++ b/atuin/src/command/client/search/inspector.rs
@@ -0,0 +1,259 @@
+use std::time::Duration;
+use time::macros::format_description;
+
+use atuin_client::{
+ history::{History, HistoryStats},
+ settings::Settings,
+};
+use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
+use ratatui::{
+ layout::Rect,
+ prelude::{Constraint, Direction, Layout},
+ style::Style,
+ widgets::{Bar, BarChart, BarGroup, Block, Borders, Padding, Paragraph, Row, Table},
+ Frame,
+};
+
+use super::duration::format_duration;
+
+use super::interactive::{InputAction, State};
+
+#[allow(clippy::cast_sign_loss)]
+fn u64_or_zero(num: i64) -> u64 {
+ if num < 0 {
+ 0
+ } else {
+ num as u64
+ }
+}
+
+pub fn draw_commands(f: &mut Frame<'_>, parent: Rect, history: &History, stats: &HistoryStats) {
+ let commands = Layout::default()
+ .direction(Direction::Horizontal)
+ .constraints([
+ Constraint::Ratio(1, 4),
+ Constraint::Ratio(1, 2),
+ Constraint::Ratio(1, 4),
+ ])
+ .split(parent);
+
+ let command = Paragraph::new(history.command.clone()).block(
+ Block::new()
+ .borders(Borders::ALL)
+ .title("Command")
+ .padding(Padding::horizontal(1)),
+ );
+
+ let previous = Paragraph::new(
+ stats
+ .previous
+ .clone()
+ .map_or("No previous command".to_string(), |prev| prev.command),
+ )
+ .block(
+ Block::new()
+ .borders(Borders::ALL)
+ .title("Previous command")
+ .padding(Padding::horizontal(1)),
+ );
+
+ let next = Paragraph::new(
+ stats
+ .next
+ .clone()
+ .map_or("No next command".to_string(), |next| next.command),
+ )
+ .block(
+ Block::new()
+ .borders(Borders::ALL)
+ .title("Next command")
+ .padding(Padding::horizontal(1)),
+ );
+
+ f.render_widget(previous, commands[0]);
+ f.render_widget(command, commands[1]);
+ f.render_widget(next, commands[2]);
+}
+
+pub fn draw_stats_table(f: &mut Frame<'_>, parent: Rect, history: &History, stats: &HistoryStats) {
+ let duration = Duration::from_nanos(u64_or_zero(history.duration));
+ let avg_duration = Duration::from_nanos(stats.average_duration);
+
+ let rows = [
+ Row::new(vec!["Time".to_string(), history.timestamp.to_string()]),
+ Row::new(vec!["Duration".to_string(), format_duration(duration)]),
+ Row::new(vec![
+ "Avg duration".to_string(),
+ format_duration(avg_duration),
+ ]),
+ Row::new(vec!["Exit".to_string(), history.exit.to_string()]),
+ Row::new(vec!["Directory".to_string(), history.cwd.to_string()]),
+ Row::new(vec!["Session".to_string(), history.session.to_string()]),
+ Row::new(vec!["Total runs".to_string(), stats.total.to_string()]),
+ ];
+
+ let widths = [Constraint::Ratio(1, 5), Constraint::Ratio(4, 5)];
+
+ let table = Table::new(rows, widths).column_spacing(1).block(
+ Block::default()
+ .title("Command stats")
+ .borders(Borders::ALL)
+ .padding(Padding::vertical(1)),
+ );
+
+ f.render_widget(table, parent);
+}
+
+fn num_to_day(num: &str) -> String {
+ match num {
+ "0" => "Sunday".to_string(),
+ "1" => "Monday".to_string(),
+ "2" => "Tuesday".to_string(),
+ "3" => "Wednesday".to_string(),
+ "4" => "Thursday".to_string(),
+ "5" => "Friday".to_string(),
+ "6" => "Saturday".to_string(),
+ _ => "Invalid day".to_string(),
+ }
+}
+
+fn sort_duration_over_time(durations: &[(String, i64)]) -> Vec<(String, i64)> {
+ let format = format_description!("[day]-[month]-[year]");
+ let output = format_description!("[month]/[year repr:last_two]");
+
+ let mut durations: Vec<(time::Date, i64)> = durations
+ .iter()
+ .map(|d| {
+ (
+ time::Date::parse(d.0.as_str(), &format).expect("invalid date string from sqlite"),
+ d.1,
+ )
+ })
+ .collect();
+
+ durations.sort_by(|a, b| a.0.cmp(&b.0));
+
+ durations
+ .iter()
+ .map(|(date, duration)| {
+ (
+ date.format(output).expect("failed to format sqlite date"),
+ *duration,
+ )
+ })
+ .collect()
+}
+
+fn draw_stats_charts(f: &mut Frame<'_>, parent: Rect, stats: &HistoryStats) {
+ let exits: Vec<Bar> = stats
+ .exits
+ .iter()
+ .map(|(exit, count)| {
+ Bar::default()
+ .label(exit.to_string().into())
+ .value(u64_or_zero(*count))
+ })
+ .collect();
+
+ let exits = BarChart::default()
+ .block(
+ Block::default()
+ .title("Exit code distribution")
+ .borders(Borders::ALL),
+ )
+ .bar_width(3)
+ .bar_gap(1)
+ .bar_style(Style::default())
+ .value_style(Style::default())
+ .label_style(Style::default())
+ .data(BarGroup::default().bars(&exits));
+
+ let day_of_week: Vec<Bar> = stats
+ .day_of_week
+ .iter()
+ .map(|(day, count)| {
+ Bar::default()
+ .label(num_to_day(day.as_str()).into())
+ .value(u64_or_zero(*count))
+ })
+ .collect();
+
+ let day_of_week = BarChart::default()
+ .block(Block::default().title("Runs per day").borders(Borders::ALL))
+ .bar_width(3)
+ .bar_gap(1)
+ .bar_style(Style::default())
+ .value_style(Style::default())
+ .label_style(Style::default())
+ .data(BarGroup::default().bars(&day_of_week));
+
+ let duration_over_time = sort_duration_over_time(&stats.duration_over_time);
+ let duration_over_time: Vec<Bar> = duration_over_time
+ .iter()
+ .map(|(date, duration)| {
+ let d = Duration::from_nanos(u64_or_zero(*duration));
+ Bar::default()
+ .label(date.clone().into())
+ .value(u64_or_zero(*duration))
+ .text_value(format_duration(d))
+ })
+ .collect();
+
+ let duration_over_time = BarChart::default()
+ .block(
+ Block::default()
+ .title("Duration over time")
+ .borders(Borders::ALL),
+ )
+ .bar_width(5)
+ .bar_gap(1)
+ .bar_style(Style::default())
+ .value_style(Style::default())
+ .label_style(Style::default())
+ .data(BarGroup::default().bars(&duration_over_time));
+
+ let layout = Layout::default()
+ .direction(Direction::Vertical)
+ .constraints([
+ Constraint::Ratio(1, 3),
+ Constraint::Ratio(1, 3),
+ Constraint::Ratio(1, 3),
+ ])
+ .split(parent);
+
+ f.render_widget(exits, layout[0]);
+ f.render_widget(day_of_week, layout[1]);
+ f.render_widget(duration_over_time, layout[2]);
+}
+
+pub fn draw(f: &mut Frame<'_>, chunk: Rect, history: &History, stats: &HistoryStats) {
+ let vert_layout = Layout::default()
+ .direction(Direction::Vertical)
+ .constraints([Constraint::Ratio(1, 5), Constraint::Ratio(4, 5)])
+ .split(chunk);
+
+ let stats_layout = Layout::default()
+ .direction(Direction::Horizontal)
+ .constraints([Constraint::Ratio(1, 3), Constraint::Ratio(2, 3)])
+ .split(vert_layout[1]);
+
+ draw_commands(f, vert_layout[0], history, stats);
+ draw_stats_table(f, stats_layout[0], history, stats);
+ draw_stats_charts(f, stats_layout[1], stats);
+}
+
+// I'm going to break this out more, but just starting to move things around before changing
+// structure and making it nicer.
+pub fn input(
+ _state: &mut State,
+ _settings: &Settings,
+ selected: usize,
+ input: &KeyEvent,
+) -> InputAction {
+ let ctrl = input.modifiers.contains(KeyModifiers::CONTROL);
+
+ match input.code {
+ KeyCode::Char('d') if ctrl => InputAction::Delete(selected),
+ _ => InputAction::Continue,
+ }
+}
diff --git a/atuin/src/command/client/search/interactive.rs b/atuin/src/command/client/search/interactive.rs
--- a/atuin/src/command/client/search/interactive.rs
+++ b/atuin/src/command/client/search/interactive.rs
@@ -19,7 +19,7 @@ use unicode_width::UnicodeWidthStr;
use atuin_client::{
database::{current_context, Database},
- history::History,
+ history::{History, HistoryStats},
settings::{ExitMode, FilterMode, SearchMode, Settings},
};
diff --git a/atuin/src/command/client/search/interactive.rs b/atuin/src/command/client/search/interactive.rs
--- a/atuin/src/command/client/search/interactive.rs
+++ b/atuin/src/command/client/search/interactive.rs
@@ -28,19 +28,25 @@ use super::{
engines::{SearchEngine, SearchState},
history_list::{HistoryList, ListState, PREFIX_LENGTH},
};
+
use crate::{command::client::search::engines, VERSION};
+
use ratatui::{
backend::CrosstermBackend,
layout::{Alignment, Constraint, Direction, Layout},
+ prelude::*,
style::{Color, Modifier, Style},
text::{Line, Span, Text},
- widgets::{Block, BorderType, Borders, Paragraph},
+ widgets::{Block, BorderType, Borders, Paragraph, Tabs},
Frame, Terminal, TerminalOptions, Viewport,
};
-enum InputAction {
+const TAB_TITLES: [&str; 2] = ["Search", "Inspect"];
+
+pub enum InputAction {
Accept(usize),
Copy(usize),
+ Delete(usize),
ReturnOriginal,
ReturnQuery,
Continue,
diff --git a/atuin/src/command/client/search/interactive.rs b/atuin/src/command/client/search/interactive.rs
--- a/atuin/src/command/client/search/interactive.rs
+++ b/atuin/src/command/client/search/interactive.rs
@@ -48,7 +54,7 @@ enum InputAction {
}
#[allow(clippy::struct_field_names)]
-struct State {
+pub struct State {
history_count: i64,
update_needed: Option<Version>,
results_state: ListState,
diff --git a/atuin/src/command/client/search/interactive.rs b/atuin/src/command/client/search/interactive.rs
--- a/atuin/src/command/client/search/interactive.rs
+++ b/atuin/src/command/client/search/interactive.rs
@@ -56,6 +62,7 @@ struct State {
search_mode: SearchMode,
results_len: usize,
accept: bool,
+ tab_index: usize,
search: SearchState,
engine: Box<dyn SearchEngine>,
diff --git a/atuin/src/command/client/search/interactive.rs b/atuin/src/command/client/search/interactive.rs
--- a/atuin/src/command/client/search/interactive.rs
+++ b/atuin/src/command/client/search/interactive.rs
@@ -131,8 +138,7 @@ impl State {
// Use Ctrl-n instead of Alt-n?
let modfr = if settings.ctrl_n_shortcuts { ctrl } else { alt };
- // reset the state, will be set to true later if user really did change it
- self.switched_search_mode = false;
+ // core input handling, common for all tabs
match input.code {
KeyCode::Char('c' | 'g') if ctrl => return InputAction::ReturnOriginal,
KeyCode::Esc => {
diff --git a/atuin/src/command/client/search/interactive.rs b/atuin/src/command/client/search/interactive.rs
--- a/atuin/src/command/client/search/interactive.rs
+++ b/atuin/src/command/client/search/interactive.rs
@@ -144,6 +150,35 @@ impl State {
KeyCode::Tab => {
return InputAction::Accept(self.results_state.selected());
}
+ KeyCode::Char('i') if ctrl => {
+ self.tab_index = (self.tab_index + 1) % TAB_TITLES.len();
+
+ return InputAction::Continue;
+ }
+
+ _ => {}
+ }
+
+ // handle tab-specific input
+ // todo: split out search
+ match self.tab_index {
+ 0 => {}
+
+ 1 => {
+ return super::inspector::input(
+ self,
+ settings,
+ self.results_state.selected(),
+ input,
+ );
+ }
+
+ _ => panic!("invalid tab index on input"),
+ }
+ // reset the state, will be set to true later if user really did change it
+ self.switched_search_mode = false;
+
+ match input.code {
KeyCode::Enter => {
if settings.enter_accept {
self.accept = true;
diff --git a/atuin/src/command/client/search/interactive.rs b/atuin/src/command/client/search/interactive.rs
--- a/atuin/src/command/client/search/interactive.rs
+++ b/atuin/src/command/client/search/interactive.rs
@@ -321,7 +356,14 @@ impl State {
#[allow(clippy::cast_possible_truncation)]
#[allow(clippy::bool_to_int_with_if)]
- fn draw(&mut self, f: &mut Frame, results: &[History], settings: &Settings) {
+ #[allow(clippy::too_many_lines)]
+ fn draw(
+ &mut self,
+ f: &mut Frame,
+ results: &[History],
+ stats: Option<HistoryStats>,
+ settings: &Settings,
+ ) {
let compact = match settings.style {
atuin_client::settings::Style::Auto => f.size().height < 14,
atuin_client::settings::Style::Compact => true,
diff --git a/atuin/src/command/client/search/interactive.rs b/atuin/src/command/client/search/interactive.rs
--- a/atuin/src/command/client/search/interactive.rs
+++ b/atuin/src/command/client/search/interactive.rs
@@ -330,7 +372,7 @@ impl State {
let invert = settings.invert;
let border_size = if compact { 0 } else { 1 };
let preview_width = f.size().width - 2;
- let preview_height = if settings.show_preview {
+ let preview_height = if settings.show_preview && self.tab_index == 0 {
let longest_command = results
.iter()
.max_by(|h1, h2| h1.command.len().cmp(&h2.command.len()));
diff --git a/atuin/src/command/client/search/interactive.rs b/atuin/src/command/client/search/interactive.rs
--- a/atuin/src/command/client/search/interactive.rs
+++ b/atuin/src/command/client/search/interactive.rs
@@ -346,7 +388,7 @@ impl State {
.sum(),
)
}) + border_size * 2
- } else if compact {
+ } else if compact || self.tab_index == 1 {
0
} else {
1
diff --git a/atuin/src/command/client/search/interactive.rs b/atuin/src/command/client/search/interactive.rs
--- a/atuin/src/command/client/search/interactive.rs
+++ b/atuin/src/command/client/search/interactive.rs
@@ -362,11 +404,13 @@ impl State {
Constraint::Length(1 + border_size), // input
Constraint::Min(1), // results list
Constraint::Length(preview_height), // preview
+ Constraint::Length(1), // tabs
Constraint::Length(if show_help { 1 } else { 0 }), // header (sic)
]
} else {
[
Constraint::Length(if show_help { 1 } else { 0 }), // header
+ Constraint::Length(1), // tabs
Constraint::Min(1), // results list
Constraint::Length(1 + border_size), // input
Constraint::Length(preview_height), // preview
diff --git a/atuin/src/command/client/search/interactive.rs b/atuin/src/command/client/search/interactive.rs
--- a/atuin/src/command/client/search/interactive.rs
+++ b/atuin/src/command/client/search/interactive.rs
@@ -375,10 +419,25 @@ impl State {
.as_ref(),
)
.split(f.size());
- let input_chunk = if invert { chunks[0] } else { chunks[2] };
- let results_list_chunk = chunks[1];
- let preview_chunk = if invert { chunks[2] } else { chunks[3] };
- let header_chunk = if invert { chunks[3] } else { chunks[0] };
+
+ let input_chunk = if invert { chunks[0] } else { chunks[3] };
+ let results_list_chunk = if invert { chunks[1] } else { chunks[2] };
+ let preview_chunk = if invert { chunks[2] } else { chunks[4] };
+ let tabs_chunk = if invert { chunks[3] } else { chunks[1] };
+ let header_chunk = if invert { chunks[4] } else { chunks[0] };
+
+ // TODO: this should be split so that we have one interactive search container that is
+ // EITHER a search box or an inspector. But I'm not doing that now, way too much atm.
+ // also allocate less 🙈
+ let titles = TAB_TITLES.iter().copied().map(Line::from).collect();
+
+ let tabs = Tabs::new(titles)
+ .block(Block::default().borders(Borders::NONE))
+ .select(self.tab_index)
+ .style(Style::default())
+ .highlight_style(Style::default().bold().on_black());
+
+ f.render_widget(tabs, tabs_chunk);
let style = StyleState {
compact,
diff --git a/atuin/src/command/client/search/interactive.rs b/atuin/src/command/client/search/interactive.rs
--- a/atuin/src/command/client/search/interactive.rs
+++ b/atuin/src/command/client/search/interactive.rs
@@ -404,11 +463,35 @@ impl State {
let help = self.build_help();
f.render_widget(help, header_chunks[1]);
- let stats = self.build_stats();
- f.render_widget(stats, header_chunks[2]);
+ let stats_tab = self.build_stats();
+ f.render_widget(stats_tab, header_chunks[2]);
+
+ match self.tab_index {
+ 0 => {
+ let results_list = Self::build_results_list(style, results);
+ f.render_stateful_widget(results_list, results_list_chunk, &mut self.results_state);
+ }
+
+ 1 => {
+ super::inspector::draw(
+ f,
+ results_list_chunk,
+ &results[self.results_state.selected()],
+ &stats.expect("Drawing inspector, but no stats"),
+ );
+
+ // HACK: I'm following up with abstracting this into the UI container, with a
+ // sub-widget for search + for inspector
+ let feedback = Paragraph::new("The inspector is new - please give feedback (good, or bad) at https://forum.atuin.sh");
+ f.render_widget(feedback, input_chunk);
+
+ return;
+ }
- let results_list = Self::build_results_list(style, results);
- f.render_stateful_widget(results_list, results_list_chunk, &mut self.results_state);
+ _ => {
+ panic!("invalid tab index");
+ }
+ }
let input = self.build_input(style);
f.render_widget(input, input_chunk);
diff --git a/atuin/src/command/client/search/interactive.rs b/atuin/src/command/client/search/interactive.rs
--- a/atuin/src/command/client/search/interactive.rs
+++ b/atuin/src/command/client/search/interactive.rs
@@ -443,24 +526,41 @@ impl State {
}
#[allow(clippy::unused_self)]
- fn build_help(&mut self) -> Paragraph {
- let help = Paragraph::new(Text::from(Line::from(vec![
- Span::styled("<esc>", Style::default().add_modifier(Modifier::BOLD)),
- Span::raw(": exit"),
- Span::raw(", "),
- Span::styled("<tab>", Style::default().add_modifier(Modifier::BOLD)),
- Span::raw(": edit"),
- Span::raw(", "),
- Span::styled("<enter>", Style::default().add_modifier(Modifier::BOLD)),
- Span::raw(": execute"),
- Span::raw(", "),
- Span::styled("<ctrl-r>", Style::default().add_modifier(Modifier::BOLD)),
- Span::raw(": filter toggle"),
- ])))
+ fn build_help(&self) -> Paragraph {
+ match self.tab_index {
+ // search
+ 0 => Paragraph::new(Text::from(Line::from(vec![
+ Span::styled("<esc>", Style::default().add_modifier(Modifier::BOLD)),
+ Span::raw(": exit"),
+ Span::raw(", "),
+ Span::styled("<tab>", Style::default().add_modifier(Modifier::BOLD)),
+ Span::raw(": edit"),
+ Span::raw(", "),
+ Span::styled("<enter>", Style::default().add_modifier(Modifier::BOLD)),
+ Span::raw(": execute"),
+ Span::raw(", "),
+ Span::styled("<ctrl-r>", Style::default().add_modifier(Modifier::BOLD)),
+ Span::raw(": filter toggle"),
+ Span::raw(", "),
+ Span::styled("<ctrl-i>", Style::default().add_modifier(Modifier::BOLD)),
+ Span::raw(": open inspector"),
+ ]))),
+
+ 1 => Paragraph::new(Text::from(Line::from(vec![
+ Span::styled("<esc>", Style::default().add_modifier(Modifier::BOLD)),
+ Span::raw(": exit"),
+ Span::raw(", "),
+ Span::styled("<ctrl-i>", Style::default().add_modifier(Modifier::BOLD)),
+ Span::raw(": search"),
+ Span::raw(", "),
+ Span::styled("<ctrl-d>", Style::default().add_modifier(Modifier::BOLD)),
+ Span::raw(": delete"),
+ ]))),
+
+ _ => unreachable!("invalid tab index"),
+ }
.style(Style::default().fg(Color::DarkGray))
- .alignment(Alignment::Center);
-
- help
+ .alignment(Alignment::Center)
}
fn build_stats(&mut self) -> Paragraph {
diff --git a/atuin/src/command/client/search/interactive.rs b/atuin/src/command/client/search/interactive.rs
--- a/atuin/src/command/client/search/interactive.rs
+++ b/atuin/src/command/client/search/interactive.rs
@@ -475,6 +575,7 @@ impl State {
fn build_results_list(style: StyleState, results: &[History]) -> HistoryList {
let results_list = HistoryList::new(results, style.invert);
+
if style.compact {
results_list
} else if style.invert {
diff --git a/atuin/src/command/client/search/interactive.rs b/atuin/src/command/client/search/interactive.rs
--- a/atuin/src/command/client/search/interactive.rs
+++ b/atuin/src/command/client/search/interactive.rs
@@ -665,6 +766,7 @@ pub async fn history(
update_needed: None,
switched_search_mode: false,
search_mode,
+ tab_index: 0,
search: SearchState {
input,
filter_mode: if settings.workspaces && context.git_root.is_some() {
diff --git a/atuin/src/command/client/search/interactive.rs b/atuin/src/command/client/search/interactive.rs
--- a/atuin/src/command/client/search/interactive.rs
+++ b/atuin/src/command/client/search/interactive.rs
@@ -685,9 +787,10 @@ pub async fn history(
let mut results = app.query_results(&mut db).await?;
+ let mut stats: Option<HistoryStats> = None;
let accept;
let result = 'render: loop {
- terminal.draw(|f| app.draw(f, &results, settings))?;
+ terminal.draw(|f| app.draw(f, &results, stats.clone(), settings))?;
let initial_input = app.search.input.as_str().to_owned();
let initial_filter_mode = app.search.filter_mode;
diff --git a/atuin/src/command/client/search/interactive.rs b/atuin/src/command/client/search/interactive.rs
--- a/atuin/src/command/client/search/interactive.rs
+++ b/atuin/src/command/client/search/interactive.rs
@@ -701,9 +804,21 @@ pub async fn history(
loop {
match app.handle_input(settings, &event::read()?, &mut std::io::stdout())? {
InputAction::Continue => {},
+ InputAction::Delete(index) => {
+ app.results_len -= 1;
+ let selected = app.results_state.selected();
+ if selected == app.results_len {
+ app.results_state.select(selected - 1);
+ }
+
+ let entry = results.remove(index);
+ db.delete(entry).await?;
+
+ app.tab_index = 0;
+ },
InputAction::Redraw => {
terminal.clear()?;
- terminal.draw(|f| app.draw(f, &results, settings))?;
+ terminal.draw(|f| app.draw(f, &results, stats.clone(), settings))?;
},
r => {
accept = app.accept;
diff --git a/atuin/src/command/client/search/interactive.rs b/atuin/src/command/client/search/interactive.rs
--- a/atuin/src/command/client/search/interactive.rs
+++ b/atuin/src/command/client/search/interactive.rs
@@ -727,6 +842,13 @@ pub async fn history(
{
results = app.query_results(&mut db).await?;
}
+
+ stats = if app.tab_index == 0 {
+ None
+ } else {
+ let selected = results[app.results_state.selected()].clone();
+ Some(db.stats(&selected).await?)
+ };
};
if settings.inline_height > 0 {
diff --git a/atuin/src/command/client/search/interactive.rs b/atuin/src/command/client/search/interactive.rs
--- a/atuin/src/command/client/search/interactive.rs
+++ b/atuin/src/command/client/search/interactive.rs
@@ -755,7 +877,7 @@ pub async fn history(
// * out of bounds -> usually implies no selected entry so we return the input
Ok(app.search.input.into_inner())
}
- InputAction::Continue | InputAction::Redraw => {
+ InputAction::Continue | InputAction::Redraw | InputAction::Delete(_) => {
unreachable!("should have been handled!")
}
}
diff --git a/atuin/src/main.rs b/atuin/src/main.rs
--- a/atuin/src/main.rs
+++ b/atuin/src/main.rs
@@ -5,6 +5,7 @@ use clap::Parser;
use eyre::Result;
use command::AtuinCmd;
+
mod command;
const VERSION: &str = env!("CARGO_PKG_VERSION");
|
diff --git a/atuin-client/src/database.rs b/atuin-client/src/database.rs
--- a/atuin-client/src/database.rs
+++ b/atuin-client/src/database.rs
@@ -562,6 +566,123 @@ impl Database for Sqlite {
Ok(())
}
+
+ async fn stats(&self, h: &History) -> Result<HistoryStats> {
+ // We select the previous in the session by time
+ let mut prev = SqlBuilder::select_from("history");
+ prev.field("*")
+ .and_where("timestamp < ?1")
+ .and_where("session = ?2")
+ .order_by("timestamp", true)
+ .limit(1);
+
+ let mut next = SqlBuilder::select_from("history");
+ next.field("*")
+ .and_where("timestamp > ?1")
+ .and_where("session = ?2")
+ .order_by("timestamp", false)
+ .limit(1);
+
+ let mut total = SqlBuilder::select_from("history");
+ total.field("count(1)").and_where("command = ?1");
+
+ let mut average = SqlBuilder::select_from("history");
+ average.field("avg(duration)").and_where("command = ?1");
+
+ let mut exits = SqlBuilder::select_from("history");
+ exits
+ .fields(&["exit", "count(1) as count"])
+ .and_where("command = ?1")
+ .group_by("exit");
+
+ // rewrite the following with sqlbuilder
+ let mut day_of_week = SqlBuilder::select_from("history");
+ day_of_week
+ .fields(&[
+ "strftime('%w', ROUND(timestamp / 1000000000), 'unixepoch') AS day_of_week",
+ "count(1) as count",
+ ])
+ .and_where("command = ?1")
+ .group_by("day_of_week");
+
+ // Intentionally format the string with 01 hardcoded. We want the average runtime for the
+ // _entire month_, but will later parse it as a datetime for sorting
+ // Sqlite has no datetime so we cannot do it there, and otherwise sorting will just be a
+ // string sort, which won't be correct.
+ let mut duration_over_time = SqlBuilder::select_from("history");
+ duration_over_time
+ .fields(&[
+ "strftime('01-%m-%Y', ROUND(timestamp / 1000000000), 'unixepoch') AS month_year",
+ "avg(duration) as duration",
+ ])
+ .and_where("command = ?1")
+ .group_by("month_year")
+ .having("duration > 0");
+
+ let prev = prev.sql().expect("issue in stats previous query");
+ let next = next.sql().expect("issue in stats next query");
+ let total = total.sql().expect("issue in stats average query");
+ let average = average.sql().expect("issue in stats previous query");
+ let exits = exits.sql().expect("issue in stats exits query");
+ let day_of_week = day_of_week.sql().expect("issue in stats day of week query");
+ let duration_over_time = duration_over_time
+ .sql()
+ .expect("issue in stats duration over time query");
+
+ let prev = sqlx::query(&prev)
+ .bind(h.timestamp.unix_timestamp_nanos() as i64)
+ .bind(&h.session)
+ .map(Self::query_history)
+ .fetch_optional(&self.pool)
+ .await?;
+
+ let next = sqlx::query(&next)
+ .bind(h.timestamp.unix_timestamp_nanos() as i64)
+ .bind(&h.session)
+ .map(Self::query_history)
+ .fetch_optional(&self.pool)
+ .await?;
+
+ let total: (i64,) = sqlx::query_as(&total)
+ .bind(&h.command)
+ .fetch_one(&self.pool)
+ .await?;
+
+ let average: (f64,) = sqlx::query_as(&average)
+ .bind(&h.command)
+ .fetch_one(&self.pool)
+ .await?;
+
+ let exits: Vec<(i64, i64)> = sqlx::query_as(&exits)
+ .bind(&h.command)
+ .fetch_all(&self.pool)
+ .await?;
+
+ let day_of_week: Vec<(String, i64)> = sqlx::query_as(&day_of_week)
+ .bind(&h.command)
+ .fetch_all(&self.pool)
+ .await?;
+
+ let duration_over_time: Vec<(String, f64)> = sqlx::query_as(&duration_over_time)
+ .bind(&h.command)
+ .fetch_all(&self.pool)
+ .await?;
+
+ let duration_over_time = duration_over_time
+ .iter()
+ .map(|f| (f.0.clone(), f.1.round() as i64))
+ .collect();
+
+ Ok(HistoryStats {
+ next,
+ previous: prev,
+ total: total.0 as u64,
+ average_duration: average.0 as u64,
+ exits,
+ day_of_week,
+ duration_over_time,
+ })
+ }
}
#[cfg(test)]
|
Interactive deletion
``atuin search --delete -i`` should work as an interactive deletion.
Right now the ``--delete`` argument is ingored.
|
From my user's point of view: As it was a bit complicated to implement the deletion feature (because atuin can sync the history over systems) it was very important to implement it at all and thus to be able to use it from the command line.
So, I guess that interactive deletion will be implemented finally but it may take some time.
Yeah, we will implement an interactive deletion, but there's also a lot more we want to add to the interactive UI and it's a challenge to not overwhelm the user and also not let them make permanent mistakes
|
2023-10-08T19:14:21Z
|
17.2
|
2024-01-12T16:02:09Z
|
4b20544474088259c580faa015876cb535dbff36
|
[
"encryption::test::key_encodings",
"encryption::test::test_decode_old",
"encryption::test::test_decode",
"history::store::tests::test_serialize_deserialize_create",
"encryption::test::test_decode_deleted",
"history::store::tests::test_serialize_deserialize_delete",
"history::tests::test_serialize_deserialize",
"history::tests::test_serialize_deserialize_deleted",
"history::tests::test_serialize_deserialize_version",
"encryption::test::test_encrypt_decrypt",
"import::bash::test::parse_no_timestamps",
"import::bash::test::parse_with_partial_timestamps",
"import::bash::test::parse_with_timestamps",
"kv::tests::encode_decode",
"import::zsh::test::test_parse_extended_simple",
"import::fish::test::parse_complex",
"import::zsh::test::test_parse_file",
"import::zsh::test::test_parse_metafied",
"record::encryption::tests::full_record_round_trip",
"record::encryption::tests::cannot_decrypt_different_key",
"record::encryption::tests::cannot_decrypt_different_id",
"record::encryption::tests::full_record_round_trip_fail",
"record::encryption::tests::same_entry_different_output",
"record::encryption::tests::round_trip",
"record::encryption::tests::re_encrypt_round_trip",
"secrets::tests::test_secrets",
"history::tests::disable_secrets",
"import::zsh_histdb::test::test_env_vars",
"record::sqlite_store::tests::create_db",
"record::sqlite_store::tests::get_record",
"record::sqlite_store::tests::last",
"record::sqlite_store::tests::first",
"kv::tests::build_kv",
"import::zsh_histdb::test::test_import",
"record::sqlite_store::tests::push_record",
"record::sqlite_store::tests::len",
"record::sqlite_store::tests::len_different_tags",
"history::tests::privacy_test",
"record::sync::tests::test_basic_diff",
"database::test::test_search_prefix",
"database::test::test_search_reordered_fuzzy",
"database::test::test_search_fulltext",
"record::sync::tests::build_two_way_diff",
"record::sync::tests::build_complex_diff",
"database::test::test_search_fuzzy",
"record::sqlite_store::tests::append_a_bunch",
"database::test::test_search_bench_dupes",
"record::sqlite_store::tests::append_a_big_bunch"
] |
[] |
[] |
[] |
auto_2025-06-06
|
atuinsh/atuin
| 2,058
|
atuinsh__atuin-2058
|
[
"1882"
] |
4d74e38a515bc14381e1342afdf5ee2ec345f589
|
diff --git a/crates/atuin-history/src/stats.rs b/crates/atuin-history/src/stats.rs
--- a/crates/atuin-history/src/stats.rs
+++ b/crates/atuin-history/src/stats.rs
@@ -92,7 +92,7 @@ fn split_at_pipe(command: &str) -> Vec<&str> {
"\\" => if graphemes.next().is_some() {},
"|" => {
if !quoted {
- if command[start..].starts_with('|') {
+ if current > start && command[start..].starts_with('|') {
start += 1;
}
result.push(&command[start..current]);
|
diff --git a/crates/atuin-history/src/stats.rs b/crates/atuin-history/src/stats.rs
--- a/crates/atuin-history/src/stats.rs
+++ b/crates/atuin-history/src/stats.rs
@@ -396,4 +396,20 @@ mod tests {
["git commit -m \"🚀\""]
);
}
+
+ #[test]
+ fn starts_with_pipe() {
+ assert_eq!(
+ split_at_pipe("| sed 's/[0-9a-f]//g'"),
+ ["", " sed 's/[0-9a-f]//g'"]
+ );
+ }
+
+ #[test]
+ fn starts_with_spaces_and_pipe() {
+ assert_eq!(
+ split_at_pipe(" | sed 's/[0-9a-f]//g'"),
+ [" ", " sed 's/[0-9a-f]//g'"]
+ );
+ }
}
|
[Bug]: atuin stats panics when faced with unusual string in history
### What did you expect to happen?
No panic! ;]
### What happened?
When running `atuin stats` it panics with:
```
❯ RUST_BACKTRACE=1 atuin stats
thread 'main' panicked at atuin/src/command/client/stats.rs:56:41:
begin <= end (1 <= 0) when slicing `| awk '{print $1}' | R --no-echo -e 'x <- scan(file="stdin", quiet=TRUE); summary(x)'`
stack backtrace:
0: _rust_begin_unwind
1: core::panicking::panic_fmt
2: core::str::slice_error_fail_rt
3: core::str::slice_error_fail
4: atuin::command::client::stats::compute_stats
5: atuin::command::client::Cmd::run_inner::{{closure}}
6: tokio::runtime::scheduler::current_thread::Context::enter
7: tokio::runtime::context::set_scheduler
8: tokio::runtime::scheduler::current_thread::CoreGuard::block_on
9: tokio::runtime::context::runtime::enter_runtime
10: tokio::runtime::runtime::Runtime::block_on
11: atuin::main
note: Some details are omitted, run with `RUST_BACKTRACE=full` for a verbose backtrace.
```
Now that string `| awk '{print $1}' | R --no-echo -e 'x <- scan(file="stdin", quiet=TRUE); summary(x)'` is actually in my history like that (it's the "entire" command), so obviously some copy-pasta failure on my part, but I don't think it should make `atuin` panic (maybe due to starting with a `|`?).
### Atuin doctor output
```yaml
Atuin Doctor
Checking for diagnostics
Please include the output below with any bug reports or issues
atuin:
version: 18.1.0
sync:
cloud: false
records: true
auto_sync: true
last_sync: 2024-03-14 18:05:58.081633 +00:00:00
shell:
name: zsh
plugins:
- atuin
system:
os: Darwin
arch: x86_64
version: 14.3.1
disks:
- name: Macintosh HD
filesystem: apfs
- name: Macintosh HD
filesystem: apfs
```
### Code of Conduct
- [X] I agree to follow this project's Code of Conduct
|
seconding this- here's another fun string this happens with.
```console
$ RUST_BACKTRACE=1 atuin stats
thread 'main' panicked at atuin/src/command/client/stats.rs:56:41:
begin <= end (1 <= 0) when slicing `|_| |____||___||_| |_| |___||_|_`
stack backtrace:
0: 0x1054a29d0 - <std::sys_common::backtrace::_print::DisplayBacktrace as core::fmt::Display>::fmt::h61949099c17bb561
1: 0x1054ca8e0 - core::fmt::write::he0c0819610fe7c82
2: 0x105487c8c - std::io::Write::write_fmt::h14dadda6958822c3
3: 0x1054a2824 - std::sys_common::backtrace::print::h10166cbeffac9d38
4: 0x1054a3360 - std::panicking::default_hook::{{closure}}::hfec7fca779e11f3b
5: 0x1054a30e0 - std::panicking::default_hook::h26402d2c6670ffd0
6: 0x1054a39d4 - std::panicking::rust_panic_with_hook::hb00dd38969b5a277
7: 0x1054a378c - std::panicking::begin_panic_handler::{{closure}}::hc86edf66ba485638
8: 0x1054a2c04 - std::sys_common::backtrace::__rust_end_short_backtrace::h24f57ebe971b5eac
9: 0x1054a3514 - _rust_begin_unwind
10: 0x1055123e8 - core::panicking::panic_fmt::h21b3a72f47844886
11: 0x1054c6c10 - core::str::slice_error_fail_rt::h0bcfaeca513f69c4
12: 0x105512790 - core::str::slice_error_fail::h2e034b398f7b75a7
13: 0x104c3f69c - atuin::command::client::stats::compute_stats::h309a358b9b61ecd5
14: 0x104a24714 - atuin::command::client::Cmd::run_inner::{{closure}}::h4a9567b4490695de
15: 0x104b13448 - tokio::runtime::scheduler::current_thread::CoreGuard::block_on::h351c1c892460edf6
16: 0x104c38318 - tokio::runtime::context::runtime::enter_runtime::hef50c501bad43a82
17: 0x104b6e14c - tokio::runtime::runtime::Runtime::block_on::h7d3459fe69753074
18: 0x104bd38a4 - atuin::command::client::Cmd::run::h588a5ab129b29fa6
19: 0x104c400a4 - atuin::command::AtuinCmd::run::hf663edac3a0da924
20: 0x104bd3d70 - atuin::main::h61cb3fcec8322f37
21: 0x104b96218 - std::sys_common::backtrace::__rust_begin_short_backtrace::he76aba5053fdcc16
22: 0x104c242b8 - std::rt::lang_start::{{closure}}::h024e6bed810fd961
23: 0x1054a3400 - std::panicking::try::ha883230fd73a158c
24: 0x105485fc0 - std::rt::lang_start_internal::ha86617696da0c619
25: 0x104bd8c0c - _main
```
installed via nixpkgs/nix-darwin. atuin doctor output:
```yaml
atuin:
version: 18.1.0
sync:
cloud: false
records: false
auto_sync: true
last_sync: 2024-03-24 19:14:04.454307 +00:00:00
shell:
name: zsh
plugins:
- atuin
system:
os: Darwin
arch: arm64
version: '14.4'
disks:
- name: Macintosh HD
filesystem: apfs
- name: Macintosh HD
filesystem: apfs
```
this helped me track down and a similar panic, with `| landscape` as a history entry. I deleted the entry in atuin to fix my stats output.
Got something very similar:
```
atuin stats
thread 'main' panicked at atuin/src/command/client/stats.rs:56:41:
begin <= end (1 <= 0) when slicing `| wc -l`
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
```
It would be helpful if it printed the entire command that caused the problem, so I could delete it.
something similar

` RUST_BACKTRACE=full atuin stats
thread 'main' panicked at atuin/src/command/client/stats.rs:56:41:
begin <= end (1 <= 0) when slicing `| HTTPCode=%{http_code}\n\n"`
stack backtrace:
0: 0x562b9d838c96 - <unknown>
1: 0x562b9d868f20 - <unknown>
2: 0x562b9d834f6f - <unknown>`
Appears to happen for all commands starting with a pipe/| character for me (I used prune with a history_filter on the offending string in my config.toml to work around the issue).
Here's my backtrace output:
```
❯ atuin stats
thread 'main' panicked at atuin/src/command/client/stats.rs:56:41:
begin <= end (1 <= 0) when slicing `| grep -v CHOST`
stack backtrace:
0: 0x105397884 - <std::sys_common::backtrace::_print::DisplayBacktrace as core::fmt::Display>::fmt::hfb3c5255bdb4eac9
1: 0x1053cc6a4 - core::fmt::write::h4f9b26a431923163
2: 0x10539d8a8 - std::io::Write::write_fmt::h65a3848fda965d9a
3: 0x1053976b4 - std::sys_common::backtrace::print::hfb8e68d5340a5773
4: 0x1053adb90 - std::panicking::default_hook::{{closure}}::h3c1629cb3dea24df
5: 0x1053ad918 - std::panicking::default_hook::h5b4a788645c74387
6: 0x1053adf9c - std::panicking::rust_panic_with_hook::h2f1b18b39b6242c7
7: 0x105397d74 - std::panicking::begin_panic_handler::{{closure}}::hd6c9d27d8f83f59d
8: 0x105397ab8 - std::sys_common::backtrace::__rust_end_short_backtrace::hb3b76dda55c5a574
9: 0x1053add24 - _rust_begin_unwind
10: 0x10541fd60 - core::panicking::panic_fmt::h737710d5a381d17b
11: 0x1053cf9a0 - core::str::slice_error_fail_rt::h4b74b83a2a7f6848
12: 0x1054200b4 - core::str::slice_error_fail::h63b632dfbbc1ab21
13: 0x104b2a234 - atuin::command::client::stats::compute_stats::hda9c3aa01b72b14e
14: 0x10495420c - atuin::command::client::Cmd::run_inner::{{closure}}::ha0d80b7b53df7bfe
15: 0x1049e9670 - tokio::runtime::scheduler::current_thread::Context::enter::he4718aa49284b4be
16: 0x104abeb60 - tokio::runtime::context::scoped::Scoped<T>::set::h3ad6c66c16925748
17: 0x1049e984c - tokio::runtime::scheduler::current_thread::CoreGuard::block_on::ha97983b83be644af
18: 0x104ac06e0 - tokio::runtime::context::runtime::enter_runtime::h891287b6d7d34412
19: 0x104a38ac4 - atuin::command::client::Cmd::run::h1c7da15a92888fd9
20: 0x104b2b3cc - atuin::main::h45ddc4795688d199
21: 0x104a58bb0 - std::sys_common::backtrace::__rust_begin_short_backtrace::haad479e4b60591cd
22: 0x104a01e3c - std::rt::lang_start::{{closure}}::h862dbd93209a848c
23: 0x1053adc1c - std::panicking::try::he7b2dbdb2ebe3a2a
24: 0x105399730 - std::rt::lang_start_internal::h3cdb23022df8f974
25: 0x104b453a8 - _main
```
|
2024-05-30T14:26:22Z
|
18.2
|
2024-05-30T14:58:06Z
|
4d74e38a515bc14381e1342afdf5ee2ec345f589
|
[
"stats::tests::starts_with_pipe"
] |
[
"stats::tests::escaped_pipes",
"stats::tests::interesting_commands_spaces",
"stats::tests::split_multi_quoted",
"stats::tests::starts_with_spaces_and_pipe",
"stats::tests::interesting_commands",
"stats::tests::split_simple_quoted",
"stats::tests::split_multi",
"stats::tests::split_simple",
"stats::tests::interesting_commands_spaces_both",
"stats::tests::emoji",
"stats::tests::ignored_commands",
"stats::tests::interesting_commands_spaces_subcommand"
] |
[] |
[] |
auto_2025-06-06
|
atuinsh/atuin
| 1,739
|
atuinsh__atuin-1739
|
[
"1054"
] |
2a65f89cd54b8b8187240a1fdc288867b35f6b01
|
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -217,6 +217,7 @@ dependencies = [
"tracing",
"tracing-subscriber",
"tracing-tree",
+ "unicode-segmentation",
"unicode-width",
"uuid",
"whoami",
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -3937,9 +3938,9 @@ dependencies = [
[[package]]
name = "unicode-segmentation"
-version = "1.10.1"
+version = "1.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "1dd624098567895118886609431a7c3b8f516e41d30e0643f03d94592a147e36"
+checksum = "d4c87d22b6e3f4a18d4d40ef354e97c90fcb14dd91d7dc0aa9d8a1172ebf7202"
[[package]]
name = "unicode-width"
diff --git a/atuin/Cargo.toml b/atuin/Cargo.toml
--- a/atuin/Cargo.toml
+++ b/atuin/Cargo.toml
@@ -78,6 +78,7 @@ ratatui = "0.25"
tracing = "0.1"
cli-clipboard = { version = "0.4.0", optional = true }
uuid = { workspace = true }
+unicode-segmentation = "1.11.0"
[dependencies.tracing-subscriber]
diff --git a/atuin/src/command/client/stats.rs b/atuin/src/command/client/stats.rs
--- a/atuin/src/command/client/stats.rs
+++ b/atuin/src/command/client/stats.rs
@@ -1,6 +1,5 @@
use std::collections::{HashMap, HashSet};
-use atuin_common::utils::Escapable as _;
use clap::Parser;
use crossterm::style::{Color, ResetColor, SetAttribute, SetForegroundColor};
use eyre::Result;
diff --git a/atuin/src/command/client/stats.rs b/atuin/src/command/client/stats.rs
--- a/atuin/src/command/client/stats.rs
+++ b/atuin/src/command/client/stats.rs
@@ -12,6 +11,7 @@ use atuin_client::{
settings::Settings,
};
use time::{Duration, OffsetDateTime, Time};
+use unicode_segmentation::UnicodeSegmentation;
#[derive(Parser, Debug)]
#[command(infer_subcommands = true)]
diff --git a/atuin/src/command/client/stats.rs b/atuin/src/command/client/stats.rs
--- a/atuin/src/command/client/stats.rs
+++ b/atuin/src/command/client/stats.rs
@@ -22,12 +22,60 @@ pub struct Cmd {
/// How many top commands to list
#[arg(long, short, default_value = "10")]
count: usize,
+
+ /// The number of consecutive commands to consider
+ #[arg(long, short, default_value = "1")]
+ ngram_size: usize,
}
-fn compute_stats(settings: &Settings, history: &[History], count: usize) -> (usize, usize) {
+fn split_at_pipe(command: &str) -> Vec<&str> {
+ let mut result = vec![];
+ let mut quoted = false;
+ let mut start = 0;
+ let mut graphemes = UnicodeSegmentation::grapheme_indices(command, true);
+
+ while let Some((i, c)) = graphemes.next() {
+ let current = i;
+ match c {
+ "\"" => {
+ if command[start..current] != *"\"" {
+ quoted = !quoted;
+ }
+ }
+ "'" => {
+ if command[start..current] != *"'" {
+ quoted = !quoted;
+ }
+ }
+ "\\" => if graphemes.next().is_some() {},
+ "|" => {
+ if !quoted {
+ if command[start..].starts_with('|') {
+ start += 1;
+ }
+ result.push(&command[start..current]);
+ start = current;
+ }
+ }
+ _ => {}
+ }
+ }
+ if command[start..].starts_with('|') {
+ start += 1;
+ }
+ result.push(&command[start..]);
+ result
+}
+
+fn compute_stats(
+ settings: &Settings,
+ history: &[History],
+ count: usize,
+ ngram_size: usize,
+) -> (usize, usize) {
let mut commands = HashSet::<&str>::with_capacity(history.len());
- let mut prefixes = HashMap::<&str, usize>::with_capacity(history.len());
let mut total_unignored = 0;
+ let mut prefixes = HashMap::<Vec<&str>, usize>::with_capacity(history.len());
for i in history {
// just in case it somehow has a leading tab or space or something (legacy atuin didn't ignore space prefixes)
let command = i.command.trim();
diff --git a/atuin/src/command/client/stats.rs b/atuin/src/command/client/stats.rs
--- a/atuin/src/command/client/stats.rs
+++ b/atuin/src/command/client/stats.rs
@@ -39,7 +87,21 @@ fn compute_stats(settings: &Settings, history: &[History], count: usize) -> (usi
total_unignored += 1;
commands.insert(command);
- *prefixes.entry(prefix).or_default() += 1;
+
+ split_at_pipe(i.command.trim())
+ .iter()
+ .map(|l| {
+ let command = l.trim();
+ commands.insert(command);
+ command
+ })
+ .collect::<Vec<_>>()
+ .windows(ngram_size)
+ .for_each(|w| {
+ *prefixes
+ .entry(w.iter().map(|c| interesting_command(settings, c)).collect())
+ .or_default() += 1;
+ });
}
let unique = commands.len();
diff --git a/atuin/src/command/client/stats.rs b/atuin/src/command/client/stats.rs
--- a/atuin/src/command/client/stats.rs
+++ b/atuin/src/command/client/stats.rs
@@ -54,6 +116,17 @@ fn compute_stats(settings: &Settings, history: &[History], count: usize) -> (usi
let max = top.iter().map(|x| x.1).max().unwrap();
let num_pad = max.ilog10() as usize + 1;
+ // Find the length of the longest command name for each column
+ let column_widths = top
+ .iter()
+ .map(|(commands, _)| commands.iter().map(|c| c.len()).collect::<Vec<usize>>())
+ .fold(vec![0; ngram_size], |acc, item| {
+ acc.iter()
+ .zip(item.iter())
+ .map(|(a, i)| *std::cmp::max(a, i))
+ .collect()
+ });
+
for (command, count) in top {
let gray = SetForegroundColor(Color::Grey);
let bold = SetAttribute(crossterm::style::Attribute::Bold);
diff --git a/atuin/src/command/client/stats.rs b/atuin/src/command/client/stats.rs
--- a/atuin/src/command/client/stats.rs
+++ b/atuin/src/command/client/stats.rs
@@ -74,10 +147,14 @@ fn compute_stats(settings: &Settings, history: &[History], count: usize) -> (usi
print!(" ");
}
- println!(
- "{ResetColor}] {gray}{count:num_pad$}{ResetColor} {bold}{}{ResetColor}",
- command.escape_control()
- );
+ let formatted_command = command
+ .iter()
+ .zip(column_widths.iter())
+ .map(|(cmd, width)| format!("{cmd:width$}"))
+ .collect::<Vec<_>>()
+ .join(" | ");
+
+ println!("{ResetColor}] {gray}{count:num_pad$}{ResetColor} {bold}{formatted_command}{ResetColor}");
}
println!("Total commands: {total_unignored}");
println!("Unique commands: {unique}");
diff --git a/atuin/src/command/client/stats.rs b/atuin/src/command/client/stats.rs
--- a/atuin/src/command/client/stats.rs
+++ b/atuin/src/command/client/stats.rs
@@ -120,7 +197,7 @@ impl Cmd {
let end = start + Duration::days(1);
db.range(start, end).await?
};
- compute_stats(settings, &history, self.count);
+ compute_stats(settings, &history, self.count, self.ngram_size);
Ok(())
}
}
|
diff --git a/atuin/src/command/client/stats.rs b/atuin/src/command/client/stats.rs
--- a/atuin/src/command/client/stats.rs
+++ b/atuin/src/command/client/stats.rs
@@ -189,7 +266,7 @@ mod tests {
use time::OffsetDateTime;
use super::compute_stats;
- use super::interesting_command;
+ use super::{interesting_command, split_at_pipe};
#[test]
fn ignored_commands() {
diff --git a/atuin/src/command/client/stats.rs b/atuin/src/command/client/stats.rs
--- a/atuin/src/command/client/stats.rs
+++ b/atuin/src/command/client/stats.rs
@@ -209,7 +286,7 @@ mod tests {
.into(),
];
- let (total, unique) = compute_stats(&settings, &history, 10);
+ let (total, unique) = compute_stats(&settings, &history, 10, 1);
assert_eq!(total, 1);
assert_eq!(unique, 1);
}
diff --git a/atuin/src/command/client/stats.rs b/atuin/src/command/client/stats.rs
--- a/atuin/src/command/client/stats.rs
+++ b/atuin/src/command/client/stats.rs
@@ -312,4 +389,49 @@ mod tests {
"cargo build foo"
);
}
+
+ #[test]
+ fn split_simple() {
+ assert_eq!(split_at_pipe("fd | rg"), ["fd ", " rg"]);
+ }
+
+ #[test]
+ fn split_multi() {
+ assert_eq!(
+ split_at_pipe("kubectl | jq | rg"),
+ ["kubectl ", " jq ", " rg"]
+ );
+ }
+
+ #[test]
+ fn split_simple_quoted() {
+ assert_eq!(
+ split_at_pipe("foo | bar 'baz {} | quux' | xyzzy"),
+ ["foo ", " bar 'baz {} | quux' ", " xyzzy"]
+ );
+ }
+
+ #[test]
+ fn split_multi_quoted() {
+ assert_eq!(
+ split_at_pipe("foo | bar 'baz \"{}\" | quux' | xyzzy"),
+ ["foo ", " bar 'baz \"{}\" | quux' ", " xyzzy"]
+ );
+ }
+
+ #[test]
+ fn escaped_pipes() {
+ assert_eq!(
+ split_at_pipe("foo | bar baz \\| quux"),
+ ["foo ", " bar baz \\| quux"]
+ );
+ }
+
+ #[test]
+ fn emoji() {
+ assert_eq!(
+ split_at_pipe("git commit -m \"🚀\""),
+ ["git commit -m \"🚀\""]
+ );
+ }
}
|
Enable multiple command stats to be shown
These changes extend the `stats` subcommand with an `--ngram-size` argument, which supports providing statistics for combinations of commands. I have found this useful for identifying the most common combinations of commands as candidates for further automation.
|
2024-02-20T05:51:10Z
|
18.0
|
2024-02-27T19:41:41Z
|
2a65f89cd54b8b8187240a1fdc288867b35f6b01
|
[
"command::client::search::cursor::cursor_tests::back",
"command::client::search::cursor::cursor_tests::left",
"command::client::search::cursor::cursor_tests::pop",
"command::client::stats::tests::interesting_commands",
"command::client::search::cursor::cursor_tests::test_emacs_get_prev_word_pos",
"command::client::search::cursor::cursor_tests::insert",
"command::client::search::cursor::cursor_tests::test_subl_get_next_word_pos",
"command::client::stats::tests::interesting_commands_spaces",
"command::client::search::cursor::cursor_tests::right",
"command::client::search::cursor::cursor_tests::test_emacs_get_next_word_pos",
"command::client::stats::tests::interesting_commands_spaces_both",
"command::client::account::login::tests::mnemonic_round_trip",
"command::client::search::cursor::cursor_tests::test_subl_get_prev_word_pos",
"command::client::stats::tests::interesting_commands_spaces_subcommand",
"command::client::stats::tests::ignored_commands"
] |
[] |
[] |
[] |
auto_2025-06-06
|
|
atuinsh/atuin
| 1,722
|
atuinsh__atuin-1722
|
[
"1714"
] |
063d9054d74c0c44781507eed27378415ab9fef5
|
diff --git a/atuin-client/config.toml b/atuin-client/config.toml
--- a/atuin-client/config.toml
+++ b/atuin-client/config.toml
@@ -171,3 +171,6 @@ enter_accept = true
## Set commands that should be totally stripped and ignored from stats
#common_prefix = ["sudo"]
+
+## Set commands that will be completely ignored from stats
+#ignored_commands = ["cd", "ls", "vi"]
diff --git a/atuin-client/src/settings.rs b/atuin-client/src/settings.rs
--- a/atuin-client/src/settings.rs
+++ b/atuin-client/src/settings.rs
@@ -270,6 +270,8 @@ pub struct Stats {
pub common_prefix: Vec<String>, // sudo, etc. commands we want to strip off
#[serde(default = "Stats::common_subcommands_default")]
pub common_subcommands: Vec<String>, // kubectl, commands we should consider subcommands for
+ #[serde(default = "Stats::ignored_commands_default")]
+ pub ignored_commands: Vec<String>, // cd, ls, etc. commands we want to completely hide from stats
}
impl Stats {
diff --git a/atuin-client/src/settings.rs b/atuin-client/src/settings.rs
--- a/atuin-client/src/settings.rs
+++ b/atuin-client/src/settings.rs
@@ -283,6 +285,10 @@ impl Stats {
.map(String::from)
.collect()
}
+
+ fn ignored_commands_default() -> Vec<String> {
+ vec![]
+ }
}
impl Default for Stats {
diff --git a/atuin-client/src/settings.rs b/atuin-client/src/settings.rs
--- a/atuin-client/src/settings.rs
+++ b/atuin-client/src/settings.rs
@@ -290,6 +296,7 @@ impl Default for Stats {
Self {
common_prefix: Self::common_prefix_default(),
common_subcommands: Self::common_subcommands_default(),
+ ignored_commands: Self::ignored_commands_default(),
}
}
}
diff --git a/atuin/src/command/client/stats.rs b/atuin/src/command/client/stats.rs
--- a/atuin/src/command/client/stats.rs
+++ b/atuin/src/command/client/stats.rs
@@ -24,16 +24,22 @@ pub struct Cmd {
count: usize,
}
-fn compute_stats(settings: &Settings, history: &[History], count: usize) {
+fn compute_stats(settings: &Settings, history: &[History], count: usize) -> (usize, usize) {
let mut commands = HashSet::<&str>::with_capacity(history.len());
let mut prefixes = HashMap::<&str, usize>::with_capacity(history.len());
+ let mut total_unignored = 0;
for i in history {
// just in case it somehow has a leading tab or space or something (legacy atuin didn't ignore space prefixes)
let command = i.command.trim();
+ let prefix = interesting_command(settings, command);
+
+ if settings.stats.ignored_commands.iter().any(|c| c == prefix) {
+ continue;
+ }
+
+ total_unignored += 1;
commands.insert(command);
- *prefixes
- .entry(interesting_command(settings, command))
- .or_default() += 1;
+ *prefixes.entry(prefix).or_default() += 1;
}
let unique = commands.len();
diff --git a/atuin/src/command/client/stats.rs b/atuin/src/command/client/stats.rs
--- a/atuin/src/command/client/stats.rs
+++ b/atuin/src/command/client/stats.rs
@@ -42,7 +48,7 @@ fn compute_stats(settings: &Settings, history: &[History], count: usize) {
top.truncate(count);
if top.is_empty() {
println!("No commands found");
- return;
+ return (0, 0);
}
let max = top.iter().map(|x| x.1).max().unwrap();
diff --git a/atuin/src/command/client/stats.rs b/atuin/src/command/client/stats.rs
--- a/atuin/src/command/client/stats.rs
+++ b/atuin/src/command/client/stats.rs
@@ -73,8 +79,10 @@ fn compute_stats(settings: &Settings, history: &[History], count: usize) {
command.escape_control()
);
}
- println!("Total commands: {}", history.len());
+ println!("Total commands: {total_unignored}");
println!("Unique commands: {unique}");
+
+ (total_unignored, unique)
}
impl Cmd {
|
diff --git a/atuin/src/command/client/stats.rs b/atuin/src/command/client/stats.rs
--- a/atuin/src/command/client/stats.rs
+++ b/atuin/src/command/client/stats.rs
@@ -176,10 +184,36 @@ fn interesting_command<'a>(settings: &Settings, mut command: &'a str) -> &'a str
#[cfg(test)]
mod tests {
+ use atuin_client::history::History;
use atuin_client::settings::Settings;
+ use time::OffsetDateTime;
+ use super::compute_stats;
use super::interesting_command;
+ #[test]
+ fn ignored_commands() {
+ let mut settings = Settings::utc();
+ settings.stats.ignored_commands.push("cd".to_string());
+
+ let history = [
+ History::import()
+ .timestamp(OffsetDateTime::now_utc())
+ .command("cd foo")
+ .build()
+ .into(),
+ History::import()
+ .timestamp(OffsetDateTime::now_utc())
+ .command("cargo build stuff")
+ .build()
+ .into(),
+ ];
+
+ let (total, unique) = compute_stats(&settings, &history, 10);
+ assert_eq!(total, 1);
+ assert_eq!(unique, 1);
+ }
+
#[test]
fn interesting_commands() {
let settings = Settings::utc();
|
`ignore_commands` option for stats
Would you be open to having an `ignore_commands` option for `atuin stats`? `cd`, `ls`, and `vi` are my three top commands by nearly an order of and I don't find this particularly informative; I'd be interested in filtering these out entirely from my stats.
If you're interested in this, I'd be willing to take a stab at a PR for it.
|
I'd be interested!
Otherwise, you can see more commands with the -c arg, if you find them a waste of space
eg
`atuin stats -c 100` will show the top 100, rather than top 10
OK I will see how hard this is and take a stab at a PR.
The issue is not so much a waste of space, but that it makes the histogram kindof useless:
```
> atuin stats
[▮▮▮▮▮▮▮▮▮▮] 890 cd
[▮▮▮▮▮▮▮▮▮ ] 868 vi
[▮▮▮▮▮▮ ] 608 ls
[▮▮ ] 199 kcgp
[▮ ] 165 git stat
[▮ ] 159 kcl
[▮ ] 141 kcapp
[▮ ] 131 kcrm
[▮ ] 130 git co
[▮ ] 119 kcg
```
When all the other commands only have one bar because the top three are so large, it's hard to actually tell "at a glance" the magnitude difference between them all.
|
2024-02-14T17:42:21Z
|
18.0
|
2024-02-15T18:52:19Z
|
2a65f89cd54b8b8187240a1fdc288867b35f6b01
|
[
"command::client::search::cursor::cursor_tests::test_emacs_get_next_word_pos",
"command::client::search::cursor::cursor_tests::test_subl_get_prev_word_pos",
"command::client::search::cursor::cursor_tests::right",
"command::client::search::cursor::cursor_tests::pop",
"command::client::search::cursor::cursor_tests::left",
"command::client::search::cursor::cursor_tests::back",
"command::client::account::login::tests::mnemonic_round_trip",
"command::client::search::cursor::cursor_tests::test_emacs_get_prev_word_pos",
"command::client::stats::tests::interesting_commands",
"command::client::search::cursor::cursor_tests::test_subl_get_next_word_pos",
"command::client::stats::tests::interesting_commands_spaces_subcommand",
"command::client::search::cursor::cursor_tests::insert",
"command::client::stats::tests::interesting_commands_spaces_both",
"command::client::stats::tests::interesting_commands_spaces"
] |
[] |
[] |
[] |
auto_2025-06-06
|
atuinsh/atuin
| 791
|
atuinsh__atuin-791
|
[
"592"
] |
edcd477153d00944c5dae16ec3ba69e339e1450c
|
diff --git a/.mailmap b/.mailmap
--- a/.mailmap
+++ b/.mailmap
@@ -1,1 +1,2 @@
networkException <git@nwex.de> <github@nwex.de>
+Violet Shreve <github@shreve.io> <jacob@shreve.io>
diff --git /dev/null b/atuin-client/migrations/20230315220114_drop-events.sql
new file mode 100644
--- /dev/null
+++ b/atuin-client/migrations/20230315220114_drop-events.sql
@@ -0,0 +1,2 @@
+-- Add migration script here
+drop table events;
diff --git /dev/null b/atuin-client/migrations/20230319185725_deleted_at.sql
new file mode 100644
--- /dev/null
+++ b/atuin-client/migrations/20230319185725_deleted_at.sql
@@ -0,0 +1,2 @@
+-- Add migration script here
+alter table history add column deleted_at integer;
diff --git a/atuin-client/src/api_client.rs b/atuin-client/src/api_client.rs
--- a/atuin-client/src/api_client.rs
+++ b/atuin-client/src/api_client.rs
@@ -1,4 +1,5 @@
use std::collections::HashMap;
+use std::collections::HashSet;
use chrono::Utc;
use eyre::{bail, Result};
diff --git a/atuin-client/src/api_client.rs b/atuin-client/src/api_client.rs
--- a/atuin-client/src/api_client.rs
+++ b/atuin-client/src/api_client.rs
@@ -9,8 +10,8 @@ use reqwest::{
use sodiumoxide::crypto::secretbox;
use atuin_common::api::{
- AddHistoryRequest, CountResponse, ErrorResponse, IndexResponse, LoginRequest, LoginResponse,
- RegisterResponse, SyncHistoryResponse,
+ AddHistoryRequest, CountResponse, DeleteHistoryRequest, ErrorResponse, IndexResponse,
+ LoginRequest, LoginResponse, RegisterResponse, StatusResponse, SyncHistoryResponse,
};
use semver::Version;
diff --git a/atuin-client/src/api_client.rs b/atuin-client/src/api_client.rs
--- a/atuin-client/src/api_client.rs
+++ b/atuin-client/src/api_client.rs
@@ -138,11 +139,27 @@ impl<'a> Client<'a> {
Ok(count.count)
}
+ pub async fn status(&self) -> Result<StatusResponse> {
+ let url = format!("{}/sync/status", self.sync_addr);
+ let url = Url::parse(url.as_str())?;
+
+ let resp = self.client.get(url).send().await?;
+
+ if resp.status() != StatusCode::OK {
+ bail!("failed to get status (are you logged in?)");
+ }
+
+ let status = resp.json::<StatusResponse>().await?;
+
+ Ok(status)
+ }
+
pub async fn get_history(
&self,
sync_ts: chrono::DateTime<Utc>,
history_ts: chrono::DateTime<Utc>,
host: Option<String>,
+ deleted: HashSet<String>,
) -> Result<Vec<History>> {
let host = match host {
None => hash_str(&format!("{}:{}", whoami::hostname(), whoami::username())),
diff --git a/atuin-client/src/api_client.rs b/atuin-client/src/api_client.rs
--- a/atuin-client/src/api_client.rs
+++ b/atuin-client/src/api_client.rs
@@ -163,8 +180,17 @@ impl<'a> Client<'a> {
let history = history
.history
.iter()
+ // TODO: handle deletion earlier in this chain
.map(|h| serde_json::from_str(h).expect("invalid base64"))
.map(|h| decrypt(&h, &self.key).expect("failed to decrypt history! check your key"))
+ .map(|mut h| {
+ if deleted.contains(&h.id) {
+ h.deleted_at = Some(chrono::Utc::now());
+ h.command = String::from("");
+ }
+
+ h
+ })
.collect();
Ok(history)
diff --git a/atuin-client/src/api_client.rs b/atuin-client/src/api_client.rs
--- a/atuin-client/src/api_client.rs
+++ b/atuin-client/src/api_client.rs
@@ -178,4 +204,17 @@ impl<'a> Client<'a> {
Ok(())
}
+
+ pub async fn delete_history(&self, h: History) -> Result<()> {
+ let url = format!("{}/history", self.sync_addr);
+ let url = Url::parse(url.as_str())?;
+
+ self.client
+ .delete(url)
+ .json(&DeleteHistoryRequest { client_id: h.id })
+ .send()
+ .await?;
+
+ Ok(())
+ }
}
diff --git a/atuin-client/src/database.rs b/atuin-client/src/database.rs
--- a/atuin-client/src/database.rs
+++ b/atuin-client/src/database.rs
@@ -14,7 +14,6 @@ use sqlx::{
};
use super::{
- event::{Event, EventType},
history::History,
ordering,
settings::{FilterMode, SearchMode},
diff --git a/atuin-client/src/database.rs b/atuin-client/src/database.rs
--- a/atuin-client/src/database.rs
+++ b/atuin-client/src/database.rs
@@ -62,13 +61,14 @@ pub trait Database: Send + Sync {
async fn update(&self, h: &History) -> Result<()>;
async fn history_count(&self) -> Result<i64>;
- async fn event_count(&self) -> Result<i64>;
- async fn merge_events(&self) -> Result<i64>;
async fn first(&self) -> Result<History>;
async fn last(&self) -> Result<History>;
async fn before(&self, timestamp: chrono::DateTime<Utc>, count: i64) -> Result<Vec<History>>;
+ async fn delete(&self, mut h: History) -> Result<()>;
+ async fn deleted(&self) -> Result<Vec<History>>;
+
// Yes I know, it's a lot.
// Could maybe break it down to a searchparams struct or smth but that feels a little... pointless.
// Been debating maybe a DSL for search? eg "before:time limit:1 the query"
diff --git a/atuin-client/src/database.rs b/atuin-client/src/database.rs
--- a/atuin-client/src/database.rs
+++ b/atuin-client/src/database.rs
@@ -126,31 +126,10 @@ impl Sqlite {
Ok(())
}
- async fn save_event(tx: &mut sqlx::Transaction<'_, sqlx::Sqlite>, e: &Event) -> Result<()> {
- let event_type = match e.event_type {
- EventType::Create => "create",
- EventType::Delete => "delete",
- };
-
- sqlx::query(
- "insert or ignore into events(id, timestamp, hostname, event_type, history_id)
- values(?1, ?2, ?3, ?4, ?5)",
- )
- .bind(e.id.as_str())
- .bind(e.timestamp.timestamp_nanos())
- .bind(e.hostname.as_str())
- .bind(event_type)
- .bind(e.history_id.as_str())
- .execute(tx)
- .await?;
-
- Ok(())
- }
-
async fn save_raw(tx: &mut sqlx::Transaction<'_, sqlx::Sqlite>, h: &History) -> Result<()> {
sqlx::query(
- "insert or ignore into history(id, timestamp, duration, exit, command, cwd, session, hostname)
- values(?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)",
+ "insert or ignore into history(id, timestamp, duration, exit, command, cwd, session, hostname, deleted_at)
+ values(?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)",
)
.bind(h.id.as_str())
.bind(h.timestamp.timestamp_nanos())
diff --git a/atuin-client/src/database.rs b/atuin-client/src/database.rs
--- a/atuin-client/src/database.rs
+++ b/atuin-client/src/database.rs
@@ -160,6 +139,7 @@ impl Sqlite {
.bind(h.cwd.as_str())
.bind(h.session.as_str())
.bind(h.hostname.as_str())
+ .bind(h.deleted_at.map(|t|t.timestamp_nanos()))
.execute(tx)
.await?;
diff --git a/atuin-client/src/database.rs b/atuin-client/src/database.rs
--- a/atuin-client/src/database.rs
+++ b/atuin-client/src/database.rs
@@ -167,6 +147,8 @@ impl Sqlite {
}
fn query_history(row: SqliteRow) -> History {
+ let deleted_at: Option<i64> = row.get("deleted_at");
+
History {
id: row.get("id"),
timestamp: Utc.timestamp_nanos(row.get("timestamp")),
diff --git a/atuin-client/src/database.rs b/atuin-client/src/database.rs
--- a/atuin-client/src/database.rs
+++ b/atuin-client/src/database.rs
@@ -176,6 +158,7 @@ impl Sqlite {
cwd: row.get("cwd"),
session: row.get("session"),
hostname: row.get("hostname"),
+ deleted_at: deleted_at.map(|t| Utc.timestamp_nanos(t)),
}
}
}
diff --git a/atuin-client/src/database.rs b/atuin-client/src/database.rs
--- a/atuin-client/src/database.rs
+++ b/atuin-client/src/database.rs
@@ -184,11 +167,8 @@ impl Sqlite {
impl Database for Sqlite {
async fn save(&mut self, h: &History) -> Result<()> {
debug!("saving history to sqlite");
- let event = Event::new_create(h);
-
let mut tx = self.pool.begin().await?;
Self::save_raw(&mut tx, h).await?;
- Self::save_event(&mut tx, &event).await?;
tx.commit().await?;
Ok(())
diff --git a/atuin-client/src/database.rs b/atuin-client/src/database.rs
--- a/atuin-client/src/database.rs
+++ b/atuin-client/src/database.rs
@@ -200,9 +180,7 @@ impl Database for Sqlite {
let mut tx = self.pool.begin().await?;
for i in h {
- let event = Event::new_create(i);
Self::save_raw(&mut tx, i).await?;
- Self::save_event(&mut tx, &event).await?;
}
tx.commit().await?;
diff --git a/atuin-client/src/database.rs b/atuin-client/src/database.rs
--- a/atuin-client/src/database.rs
+++ b/atuin-client/src/database.rs
@@ -227,7 +205,7 @@ impl Database for Sqlite {
sqlx::query(
"update history
- set timestamp = ?2, duration = ?3, exit = ?4, command = ?5, cwd = ?6, session = ?7, hostname = ?8
+ set timestamp = ?2, duration = ?3, exit = ?4, command = ?5, cwd = ?6, session = ?7, hostname = ?8, deleted_at = ?9
where id = ?1",
)
.bind(h.id.as_str())
diff --git a/atuin-client/src/database.rs b/atuin-client/src/database.rs
--- a/atuin-client/src/database.rs
+++ b/atuin-client/src/database.rs
@@ -238,6 +216,7 @@ impl Database for Sqlite {
.bind(h.cwd.as_str())
.bind(h.session.as_str())
.bind(h.hostname.as_str())
+ .bind(h.deleted_at.map(|t|t.timestamp_nanos()))
.execute(&self.pool)
.await?;
diff --git a/atuin-client/src/database.rs b/atuin-client/src/database.rs
--- a/atuin-client/src/database.rs
+++ b/atuin-client/src/database.rs
@@ -338,49 +317,15 @@ impl Database for Sqlite {
Ok(res)
}
- async fn event_count(&self) -> Result<i64> {
- let res: i64 = sqlx::query_scalar("select count(1) from events")
- .fetch_one(&self.pool)
+ async fn deleted(&self) -> Result<Vec<History>> {
+ let res = sqlx::query("select * from history where deleted_at is not null")
+ .map(Self::query_history)
+ .fetch_all(&self.pool)
.await?;
Ok(res)
}
- // Ensure that we have correctly merged the event log
- async fn merge_events(&self) -> Result<i64> {
- // Ensure that we do not have more history locally than we do events.
- // We can think of history as the merged log of events. There should never be more history than
- // events, and the only time this could happen is if someone is upgrading from an old Atuin version
- // from before we stored events.
- let history_count = self.history_count().await?;
- let event_count = self.event_count().await?;
-
- if history_count > event_count {
- // pass an empty context, because with global listing we don't care
- let no_context = Context {
- cwd: String::from(""),
- session: String::from(""),
- hostname: String::from(""),
- };
-
- // We're just gonna load everything into memory here. That sucks, I know, sorry.
- // But also even if you have a LOT of history that should be fine, and we're only going to be doing this once EVER.
- let all_the_history = self
- .list(FilterMode::Global, &no_context, None, false)
- .await?;
-
- let mut tx = self.pool.begin().await?;
- for i in all_the_history.iter() {
- // A CREATE for every single history item is to be expected.
- let event = Event::new_create(i);
- Self::save_event(&mut tx, &event).await?;
- }
- tx.commit().await?;
- }
-
- Ok(0)
- }
-
async fn history_count(&self) -> Result<i64> {
let res: (i64,) = sqlx::query_as("select count(1) from history")
.fetch_one(&self.pool)
diff --git a/atuin-client/src/event.rs /dev/null
--- a/atuin-client/src/event.rs
+++ /dev/null
@@ -1,47 +0,0 @@
-use chrono::Utc;
-use serde::{Deserialize, Serialize};
-
-use crate::history::History;
-use atuin_common::utils::uuid_v4;
-
-#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
-pub enum EventType {
- Create,
- Delete,
-}
-
-#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, sqlx::FromRow)]
-pub struct Event {
- pub id: String,
- pub timestamp: chrono::DateTime<Utc>,
- pub hostname: String,
- pub event_type: EventType,
-
- pub history_id: String,
-}
-
-impl Event {
- pub fn new_create(history: &History) -> Event {
- Event {
- id: uuid_v4(),
- timestamp: history.timestamp,
- hostname: history.hostname.clone(),
- event_type: EventType::Create,
-
- history_id: history.id.clone(),
- }
- }
-
- pub fn new_delete(history_id: &str) -> Event {
- let hostname = format!("{}:{}", whoami::hostname(), whoami::username());
-
- Event {
- id: uuid_v4(),
- timestamp: chrono::Utc::now(),
- hostname,
- event_type: EventType::Create,
-
- history_id: history_id.to_string(),
- }
- }
-}
diff --git a/atuin-client/src/history.rs b/atuin-client/src/history.rs
--- a/atuin-client/src/history.rs
+++ b/atuin-client/src/history.rs
@@ -16,9 +16,11 @@ pub struct History {
pub cwd: String,
pub session: String,
pub hostname: String,
+ pub deleted_at: Option<chrono::DateTime<Utc>>,
}
impl History {
+ #[allow(clippy::too_many_arguments)]
pub fn new(
timestamp: chrono::DateTime<Utc>,
command: String,
diff --git a/atuin-client/src/history.rs b/atuin-client/src/history.rs
--- a/atuin-client/src/history.rs
+++ b/atuin-client/src/history.rs
@@ -27,6 +29,7 @@ impl History {
duration: i64,
session: Option<String>,
hostname: Option<String>,
+ deleted_at: Option<chrono::DateTime<Utc>>,
) -> Self {
let session = session
.or_else(|| env::var("ATUIN_SESSION").ok())
diff --git a/atuin-client/src/history.rs b/atuin-client/src/history.rs
--- a/atuin-client/src/history.rs
+++ b/atuin-client/src/history.rs
@@ -43,6 +46,7 @@ impl History {
duration,
session,
hostname,
+ deleted_at,
}
}
diff --git a/atuin-client/src/import/bash.rs b/atuin-client/src/import/bash.rs
--- a/atuin-client/src/import/bash.rs
+++ b/atuin-client/src/import/bash.rs
@@ -78,6 +78,7 @@ impl Importer for Bash {
-1,
None,
None,
+ None,
);
h.push(entry).await?;
next_timestamp += timestamp_increment;
diff --git a/atuin-client/src/import/fish.rs b/atuin-client/src/import/fish.rs
--- a/atuin-client/src/import/fish.rs
+++ b/atuin-client/src/import/fish.rs
@@ -80,6 +80,7 @@ impl Importer for Fish {
-1,
None,
None,
+ None,
))
.await?;
}
diff --git a/atuin-client/src/import/fish.rs b/atuin-client/src/import/fish.rs
--- a/atuin-client/src/import/fish.rs
+++ b/atuin-client/src/import/fish.rs
@@ -115,6 +116,7 @@ impl Importer for Fish {
-1,
None,
None,
+ None,
))
.await?;
}
diff --git a/atuin-client/src/import/resh.rs b/atuin-client/src/import/resh.rs
--- a/atuin-client/src/import/resh.rs
+++ b/atuin-client/src/import/resh.rs
@@ -131,6 +131,7 @@ impl Importer for Resh {
cwd: entry.pwd,
session: uuid_v4(),
hostname: entry.host,
+ deleted_at: None,
})
.await?;
}
diff --git a/atuin-client/src/import/zsh.rs b/atuin-client/src/import/zsh.rs
--- a/atuin-client/src/import/zsh.rs
+++ b/atuin-client/src/import/zsh.rs
@@ -86,6 +86,7 @@ impl Importer for Zsh {
-1,
None,
None,
+ None,
))
.await?;
}
diff --git a/atuin-client/src/import/zsh.rs b/atuin-client/src/import/zsh.rs
--- a/atuin-client/src/import/zsh.rs
+++ b/atuin-client/src/import/zsh.rs
@@ -119,6 +120,7 @@ fn parse_extended(line: &str, counter: i64) -> History {
duration,
None,
None,
+ None,
)
}
diff --git a/atuin-client/src/import/zsh_histdb.rs b/atuin-client/src/import/zsh_histdb.rs
--- a/atuin-client/src/import/zsh_histdb.rs
+++ b/atuin-client/src/import/zsh_histdb.rs
@@ -80,6 +80,7 @@ impl From<HistDbEntry> for History {
.trim_end()
.to_string(),
),
+ None,
)
}
}
diff --git a/atuin-client/src/lib.rs b/atuin-client/src/lib.rs
--- a/atuin-client/src/lib.rs
+++ b/atuin-client/src/lib.rs
@@ -11,7 +11,6 @@ pub mod encryption;
pub mod sync;
pub mod database;
-pub mod event;
pub mod history;
pub mod import;
pub mod ordering;
diff --git a/atuin-client/src/sync.rs b/atuin-client/src/sync.rs
--- a/atuin-client/src/sync.rs
+++ b/atuin-client/src/sync.rs
@@ -1,4 +1,6 @@
+use std::collections::HashSet;
use std::convert::TryInto;
+use std::iter::FromIterator;
use chrono::prelude::*;
use eyre::Result;
diff --git a/atuin-client/src/sync.rs b/atuin-client/src/sync.rs
--- a/atuin-client/src/sync.rs
+++ b/atuin-client/src/sync.rs
@@ -37,7 +39,11 @@ async fn sync_download(
) -> Result<(i64, i64)> {
debug!("starting sync download");
- let remote_count = client.count().await?;
+ let remote_status = client.status().await?;
+ let remote_count = remote_status.count;
+
+ // useful to ensure we don't even save something that hasn't yet been synced + deleted
+ let remote_deleted = HashSet::from_iter(remote_status.deleted.clone());
let initial_local = db.history_count().await?;
let mut local_count = initial_local;
diff --git a/atuin-client/src/sync.rs b/atuin-client/src/sync.rs
--- a/atuin-client/src/sync.rs
+++ b/atuin-client/src/sync.rs
@@ -54,7 +60,12 @@ async fn sync_download(
while remote_count > local_count {
let page = client
- .get_history(last_sync, last_timestamp, host.clone())
+ .get_history(
+ last_sync,
+ last_timestamp,
+ host.clone(),
+ remote_deleted.clone(),
+ )
.await?;
db.save_bulk(&page).await?;
diff --git a/atuin-client/src/sync.rs b/atuin-client/src/sync.rs
--- a/atuin-client/src/sync.rs
+++ b/atuin-client/src/sync.rs
@@ -81,6 +92,13 @@ async fn sync_download(
}
}
+ for i in remote_status.deleted {
+ // we will update the stored history to have this data
+ // pretty much everything can be nullified
+ let h = db.load(i.as_str()).await?;
+ db.delete(h).await?;
+ }
+
Ok((local_count - initial_local, local_count))
}
diff --git a/atuin-client/src/sync.rs b/atuin-client/src/sync.rs
--- a/atuin-client/src/sync.rs
+++ b/atuin-client/src/sync.rs
@@ -136,12 +154,17 @@ async fn sync_upload(
debug!("upload cursor: {:?}", cursor);
}
+ let deleted = db.deleted().await?;
+
+ for i in deleted {
+ info!("deleting {} on remote", i.id);
+ client.delete_history(i).await?;
+ }
+
Ok(())
}
pub async fn sync(settings: &Settings, force: bool, db: &mut (impl Database + Send)) -> Result<()> {
- db.merge_events().await?;
-
let client = api_client::Client::new(
&settings.sync_address,
&settings.session_token,
diff --git a/atuin-common/src/api.rs b/atuin-common/src/api.rs
--- a/atuin-common/src/api.rs
+++ b/atuin-common/src/api.rs
@@ -66,31 +66,18 @@ pub struct IndexResponse {
pub version: String,
}
-// Doubled up with the history sync stuff, because atm we need to support BOTH.
-// People are still running old clients, and in some cases _very_ old clients.
#[derive(Debug, Serialize, Deserialize)]
-pub enum AddEventRequest {
- Create(AddHistoryRequest),
-
- Delete {
- id: String,
- timestamp: chrono::DateTime<Utc>,
- hostname: chrono::DateTime<Utc>,
-
- // When we delete a history item, we push up an event marking its client
- // id as being deleted.
- history_id: String,
- },
+pub struct StatusResponse {
+ pub count: i64,
+ pub deleted: Vec<String>,
}
#[derive(Debug, Serialize, Deserialize)]
-pub struct SyncEventRequest {
- pub sync_ts: chrono::DateTime<chrono::FixedOffset>,
- pub event_ts: chrono::DateTime<chrono::FixedOffset>,
- pub host: String,
+pub struct DeleteHistoryRequest {
+ pub client_id: String,
}
#[derive(Debug, Serialize, Deserialize)]
-pub struct SyncEventResponse {
- pub events: Vec<String>,
+pub struct MessageResponse {
+ pub message: String,
}
diff --git /dev/null b/atuin-server/migrations/20230315220537_drop-events.sql
new file mode 100644
--- /dev/null
+++ b/atuin-server/migrations/20230315220537_drop-events.sql
@@ -0,0 +1,2 @@
+-- Add migration script here
+drop table events;
diff --git /dev/null b/atuin-server/migrations/20230315224203_create-deleted.sql
new file mode 100644
--- /dev/null
+++ b/atuin-server/migrations/20230315224203_create-deleted.sql
@@ -0,0 +1,5 @@
+-- Add migration script here
+alter table history add column if not exists deleted_at timestamp;
+
+-- queries will all be selecting the ids of history for a user, that has been deleted
+create index if not exists history_deleted_index on history(client_id, user_id, deleted_at);
diff --git a/atuin-server/src/database.rs b/atuin-server/src/database.rs
--- a/atuin-server/src/database.rs
+++ b/atuin-server/src/database.rs
@@ -4,6 +4,9 @@ use async_trait::async_trait;
use chrono::{Datelike, TimeZone};
use chronoutil::RelativeDuration;
use sqlx::{postgres::PgPoolOptions, Result};
+
+use sqlx::Row;
+
use tracing::{debug, instrument, warn};
use super::{
diff --git a/atuin-server/src/database.rs b/atuin-server/src/database.rs
--- a/atuin-server/src/database.rs
+++ b/atuin-server/src/database.rs
@@ -28,6 +31,9 @@ pub trait Database {
async fn count_history(&self, user: &User) -> Result<i64>;
async fn count_history_cached(&self, user: &User) -> Result<i64>;
+ async fn delete_history(&self, user: &User, id: String) -> Result<()>;
+ async fn deleted_history(&self, user: &User) -> Result<Vec<String>>;
+
async fn count_history_range(
&self,
user: &User,
diff --git a/atuin-server/src/database.rs b/atuin-server/src/database.rs
--- a/atuin-server/src/database.rs
+++ b/atuin-server/src/database.rs
@@ -141,6 +147,46 @@ impl Database for Postgres {
Ok(res.0 as i64)
}
+ async fn delete_history(&self, user: &User, id: String) -> Result<()> {
+ sqlx::query(
+ "update history
+ set deleted_at = $3
+ where user_id = $1
+ and client_id = $2
+ and deleted_at is null", // don't just keep setting it
+ )
+ .bind(user.id)
+ .bind(id)
+ .bind(chrono::Utc::now().naive_utc())
+ .fetch_all(&self.pool)
+ .await?;
+
+ Ok(())
+ }
+
+ #[instrument(skip_all)]
+ async fn deleted_history(&self, user: &User) -> Result<Vec<String>> {
+ // The cache is new, and the user might not yet have a cache value.
+ // They will have one as soon as they post up some new history, but handle that
+ // edge case.
+
+ let res = sqlx::query(
+ "select client_id from history
+ where user_id = $1
+ and deleted_at is not null",
+ )
+ .bind(user.id)
+ .fetch_all(&self.pool)
+ .await?;
+
+ let res = res
+ .iter()
+ .map(|row| row.get::<String, _>("client_id"))
+ .collect();
+
+ Ok(res)
+ }
+
#[instrument(skip_all)]
async fn count_history_range(
&self,
diff --git a/atuin-server/src/handlers/history.rs b/atuin-server/src/handlers/history.rs
--- a/atuin-server/src/handlers/history.rs
+++ b/atuin-server/src/handlers/history.rs
@@ -74,6 +74,28 @@ pub async fn list<DB: Database>(
Ok(Json(SyncHistoryResponse { history }))
}
+#[instrument(skip_all, fields(user.id = user.id))]
+pub async fn delete<DB: Database>(
+ user: User,
+ state: State<AppState<DB>>,
+ Json(req): Json<DeleteHistoryRequest>,
+) -> Result<Json<MessageResponse>, ErrorResponseStatus<'static>> {
+ let db = &state.0.database;
+
+ // user_id is the ID of the history, as set by the user (the server has its own ID)
+ let deleted = db.delete_history(&user, req.client_id).await;
+
+ if let Err(e) = deleted {
+ error!("failed to delete history: {}", e);
+ return Err(ErrorResponse::reply("failed to delete history")
+ .with_status(StatusCode::INTERNAL_SERVER_ERROR));
+ }
+
+ Ok(Json(MessageResponse {
+ message: String::from("deleted OK"),
+ }))
+}
+
#[instrument(skip_all, fields(user.id = user.id))]
pub async fn add<DB: Database>(
user: User,
diff --git a/atuin-server/src/handlers/mod.rs b/atuin-server/src/handlers/mod.rs
--- a/atuin-server/src/handlers/mod.rs
+++ b/atuin-server/src/handlers/mod.rs
@@ -2,6 +2,7 @@ use atuin_common::api::{ErrorResponse, IndexResponse};
use axum::{response::IntoResponse, Json};
pub mod history;
+pub mod status;
pub mod user;
const VERSION: &str = env!("CARGO_PKG_VERSION");
diff --git /dev/null b/atuin-server/src/handlers/status.rs
new file mode 100644
--- /dev/null
+++ b/atuin-server/src/handlers/status.rs
@@ -0,0 +1,29 @@
+use axum::{extract::State, Json};
+use http::StatusCode;
+use tracing::instrument;
+
+use super::{ErrorResponse, ErrorResponseStatus, RespExt};
+use crate::{database::Database, models::User, router::AppState};
+
+use atuin_common::api::*;
+
+#[instrument(skip_all, fields(user.id = user.id))]
+pub async fn status<DB: Database>(
+ user: User,
+ state: State<AppState<DB>>,
+) -> Result<Json<StatusResponse>, ErrorResponseStatus<'static>> {
+ let db = &state.0.database;
+
+ let history_count = db.count_history_cached(&user).await;
+ let deleted = db.deleted_history(&user).await;
+
+ if history_count.is_err() || deleted.is_err() {
+ return Err(ErrorResponse::reply("failed to query history count")
+ .with_status(StatusCode::INTERNAL_SERVER_ERROR));
+ }
+
+ Ok(Json(StatusResponse {
+ count: history_count.unwrap(),
+ deleted: deleted.unwrap(),
+ }))
+}
diff --git a/atuin-server/src/router.rs b/atuin-server/src/router.rs
--- a/atuin-server/src/router.rs
+++ b/atuin-server/src/router.rs
@@ -2,7 +2,7 @@ use async_trait::async_trait;
use axum::{
extract::FromRequestParts,
response::IntoResponse,
- routing::{get, post},
+ routing::{delete, get, post},
Router,
};
use eyre::Result;
diff --git a/atuin-server/src/router.rs b/atuin-server/src/router.rs
--- a/atuin-server/src/router.rs
+++ b/atuin-server/src/router.rs
@@ -68,7 +68,9 @@ pub fn router<DB: Database + Clone + Send + Sync + 'static>(
.route("/sync/count", get(handlers::history::count))
.route("/sync/history", get(handlers::history::list))
.route("/sync/calendar/:focus", get(handlers::history::calendar))
+ .route("/sync/status", get(handlers::status::status))
.route("/history", post(handlers::history::add))
+ .route("/history", delete(handlers::history::delete))
.route("/user/:username", get(handlers::user::get))
.route("/register", post(handlers::user::register))
.route("/login", post(handlers::user::login));
diff --git a/src/command/client/history.rs b/src/command/client/history.rs
--- a/src/command/client/history.rs
+++ b/src/command/client/history.rs
@@ -184,7 +184,7 @@ impl Cmd {
// 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);
+ 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
diff --git a/src/command/client/search.rs b/src/command/client/search.rs
--- a/src/command/client/search.rs
+++ b/src/command/client/search.rs
@@ -76,6 +76,10 @@ pub struct Cmd {
#[arg(long)]
cmd_only: bool,
+ // Delete anything matching this query. Will not print out the match
+ #[arg(long)]
+ delete: bool,
+
/// Available variables: {command}, {directory}, {duration}, {user}, {host} and {time}.
/// Example: --format "{time} - [{duration}] - {directory}$\t{command}"
#[arg(long, short)]
diff --git a/src/command/client/search.rs b/src/command/client/search.rs
--- a/src/command/client/search.rs
+++ b/src/command/client/search.rs
@@ -100,12 +104,10 @@ impl Cmd {
let list_mode = ListMode::from_flags(self.human, self.cmd_only);
let entries = run_non_interactive(
settings,
- list_mode,
self.cwd,
self.exit,
self.exclude_exit,
self.exclude_cwd,
- self.format,
self.before,
self.after,
self.limit,
diff --git a/src/command/client/search.rs b/src/command/client/search.rs
--- a/src/command/client/search.rs
+++ b/src/command/client/search.rs
@@ -113,9 +115,22 @@ impl Cmd {
db,
)
.await?;
- if entries == 0 {
+
+ if entries.is_empty() {
std::process::exit(1)
}
+
+ // if we aren't deleting, print it all
+ if self.delete {
+ // delete it
+ // it only took me _years_ to add this
+ // sorry
+ for entry in entries {
+ db.delete(entry).await?;
+ }
+ } else {
+ super::history::print_list(&entries, list_mode, self.format.as_deref());
+ }
};
Ok(())
}
diff --git a/src/command/client/search.rs b/src/command/client/search.rs
--- a/src/command/client/search.rs
+++ b/src/command/client/search.rs
@@ -126,18 +141,16 @@ impl Cmd {
#[allow(clippy::too_many_arguments)]
async fn run_non_interactive(
settings: &Settings,
- list_mode: ListMode,
cwd: Option<String>,
exit: Option<i64>,
exclude_exit: Option<i64>,
exclude_cwd: Option<String>,
- format: Option<String>,
before: Option<String>,
after: Option<String>,
limit: Option<i64>,
query: &[String],
db: &mut impl Database,
-) -> Result<usize> {
+) -> Result<Vec<History>> {
let dir = if cwd.as_deref() == Some(".") {
Some(utils::get_current_dir())
} else {
diff --git a/src/command/client/search.rs b/src/command/client/search.rs
--- a/src/command/client/search.rs
+++ b/src/command/client/search.rs
@@ -202,6 +215,5 @@ async fn run_non_interactive(
.map(std::borrow::ToOwned::to_owned)
.collect();
- super::history::print_list(&results, list_mode, format.as_deref());
- Ok(results.len())
+ Ok(results)
}
|
diff --git a/atuin-client/src/database.rs b/atuin-client/src/database.rs
--- a/atuin-client/src/database.rs
+++ b/atuin-client/src/database.rs
@@ -528,6 +473,18 @@ impl Database for Sqlite {
Ok(res)
}
+
+ // deleted_at doesn't mean the actual time that the user deleted it,
+ // but the time that the system marks it as deleted
+ async fn delete(&self, mut h: History) -> Result<()> {
+ let now = chrono::Utc::now();
+ h.command = String::from(""); // blank it
+ h.deleted_at = Some(now); // delete it
+
+ self.update(&h).await?; // save it
+
+ Ok(())
+ }
}
#[cfg(test)]
diff --git a/atuin-client/src/database.rs b/atuin-client/src/database.rs
--- a/atuin-client/src/database.rs
+++ b/atuin-client/src/database.rs
@@ -585,6 +542,7 @@ mod test {
1,
Some("beep boop".to_string()),
Some("booop".to_string()),
+ None,
);
db.save(&history).await
}
diff --git a/atuin-client/src/encryption.rs b/atuin-client/src/encryption.rs
--- a/atuin-client/src/encryption.rs
+++ b/atuin-client/src/encryption.rs
@@ -124,6 +124,7 @@ mod test {
1,
Some("beep boop".to_string()),
Some("booop".to_string()),
+ None,
);
let e1 = encrypt(&history, &key1).unwrap();
|
Deleting history
So this has been proposed for a [super long time](https://github.com/ellie/atuin/issues/70).
It's taken a while, partly because deletion with sync is difficult. Deleting on one machine would result in it coming back the next time a sync happens, so we need to ensure deletion across all machines
I'm starting a new issue to track this, as it's actively being worked on
I wrote up my plan in a comment on #70, but copying it here for clarity
------------
tl;dr for the plan, which I'd like to break down a bit more and HOPEFULLY get in for a v12 release. Or at least partly!
## Deleting things, finally, as everyone has been asking me for it
(cue brain dump)
### 1. Switch to event log sync
I started on this here: https://github.com/ellie/atuin/pull/390
The difficulty here is that _actually_ deleting the entire row will change the count of rows. Syncing two append-only logs is much much easier and simpler than syncing two arbitrary length sets of data, especially when each installation of atuin is both read and write (so technically multi-master).
The premise with this solution is that instead of syncing up history items, as we do at the moment, we sync up events. I'm proposing two kinds of event. A CREATE event, and a DELETE event. For backwards compatibility, we'd want to add a CREATE event for every currently-existing item of history.
To delete an item of history, we push up a DELETE event to the log. This is still only an append, so we can retain our simple sync logic + keep things nice and easy.
If we replay the log on a fresh client, the history item will end up being created + then deleted. Mostly there, and mostly achieves the use case of "I don't want this thing showing up in my history".
Once that works, we could expand it to also blank out the data section of a CREATE event when a DELETE event has been created, though that would cause limitations in future sync methods (I was conisdering something based on merkle trees).
### 2. Implement UI for deletion
I'd like this to be smooth, obvious, and not some arbitrary key combination. But also not easy to do by accident! We may also want the option to delete a single occurence of a command, but not delete all historical occurances of it (and vice-versa).
To allow for this, it would be good to be able to open a "context menu" on a single item of history. I'd suggest using the tab character for this.
Scroll back to the item you wish to delete. Hit tab, and we switch to the menu item for that history. As well as showing extra information about it (directory executed in, some other context, etc), we can have an option for deleting it!
Might want some kind of UI hint to make it obvious that tab does stuff
### 3. done...?
Probably not, I imagine some things will break. I'd like to roll this out gradually, as we need to maintain backwards compatibility. Will probably save old style history rows and event rows side-by-side, and start by just syncing CREATE events up and not even implementing DELETE until the next version.
|
Just merged the first part of this!
https://github.com/ellie/atuin/pull/390
You _should_ see a new table created locally + tracking events
> I'd like this to be smooth, obvious, and not some arbitrary key combination. But also not easy to do by accident!
I'd personally love it if I could just highlight the entry and simply press <kbd>Del</kbd> to delete it, or perhaps <kbd>Shift</kbd>+<kbd>Del</kbd> like Chrome does it in the URL bar. This seems smooth and obvious and non-arbitrary to me, and especially the latter one is hard to do by accident.
In addition to selectively deleting records it would be good to have a way to configure sort of retention or max age/limit. I.e. "remove any history items older than 5y or 500k lines" or similar.
> In addition to selectively deleting records it would be good to have a way to configure sort of retention or max age/limit. I.e. "remove any history items older than 5y or 500k lines" or similar.
For sure! I've been thinking about that too. It has the same problem of breaking sync though 🙃
From a usage point of view I think the UI part for deleting is not so important.
When wanting to delete something in history I
* would like to check what to delete by running `atuin search <srchpat1> ...`
* and then deleting those entries by running `atuin delete <srchpat1> ...`
PS: For me the ability to delete items in the history is also very important.
You might find it helpful to
1. look at what people have figured out in shared text editing (whether multi-user or single user racing with async editor plugins), because they have to deal with what is fundamentally the same problem; and
2. also look at how *undo* is implemented, because a deletion is in many ways like an undo.
I remember reading some blog posts about implementing the Xi editor a few years ago were fairly enlightening for me, which might be relevant here. In particular [this one about CRDT and async undo](https://xi-editor.io/docs/crdt.html).
> From a usage point of view I think the UI part for deleting is not so important.
>
> When wanting to delete something in history I
>
> * would like to check what to delete by running `atuin search <srchpat1> ...`
>
> * and then deleting those entries by running `atuin delete <srchpat1> ...`
>
>
> PS: For me the ability to delete items in the history is also very important.
Super true. I'll probably release this first and think about the UI later
> You might find it helpful to
>
> 1. look at what people have figured out in shared text editing (whether multi-user or single user racing with async editor plugins), because they have to deal with what is fundamentally the same problem; and
>
> 2. also look at how _undo_ is implemented, because a deletion is in many ways like an undo.
>
>
> I remember reading some blog posts about implementing the Xi editor a few years ago were fairly enlightening for me, which might be relevant here. In particular [this one about CRDT and async undo](https://xi-editor.io/docs/crdt.html).
I did spend a while reading this literature + thinking about it, but they have a much harder problem to solve - that of multiple users + edit conflicts.
Neither of those problems really apply here, we just want to append stuff - and that can either be a CREATE or a DELETE
|
2023-03-19T20:49:53Z
|
13.0
|
2023-03-20T09:26:56Z
|
edcd477153d00944c5dae16ec3ba69e339e1450c
|
[
"import::bash::test::parse_no_timestamps",
"import::bash::test::parse_with_timestamps",
"import::zsh::test::test_parse_extended_simple",
"import::fish::test::parse_complex",
"encryption::test::test_encrypt_decrypt",
"import::zsh::test::test_parse_file",
"import::bash::test::parse_with_partial_timestamps",
"import::zsh_histdb::test::test_env_vars",
"import::zsh_histdb::test::test_import",
"database::test::test_search_reordered_fuzzy",
"database::test::test_search_prefix",
"database::test::test_search_fulltext",
"database::test::test_search_fuzzy",
"database::test::test_search_bench_dupes"
] |
[] |
[] |
[] |
auto_2025-06-06
|
atuinsh/atuin
| 770
|
atuinsh__atuin-770
|
[
"768"
] |
afd1113b3b0301795f3557feb94f7d7f953c5f9c
|
diff --git a/atuin-client/src/database.rs b/atuin-client/src/database.rs
--- a/atuin-client/src/database.rs
+++ b/atuin-client/src/database.rs
@@ -71,13 +71,19 @@ pub trait Database: Send + Sync {
async fn last(&self) -> Result<History>;
async fn before(&self, timestamp: chrono::DateTime<Utc>, count: i64) -> Result<Vec<History>>;
+ // Yes I know, it's a lot.
+ // Could maybe break it down to a searchparams struct or smth but that feels a little... pointless.
+ // Been debating maybe a DSL for search? eg "before:time limit:1 the query"
+ #[allow(clippy::too_many_arguments)]
async fn search(
&self,
- limit: Option<i64>,
search_mode: SearchMode,
filter: FilterMode,
context: &Context,
query: &str,
+ limit: Option<i64>,
+ before: Option<i64>,
+ after: Option<i64>,
) -> Result<Vec<History>>;
async fn query_history(&self, query: &str) -> Result<Vec<History>>;
diff --git a/atuin-client/src/database.rs b/atuin-client/src/database.rs
--- a/atuin-client/src/database.rs
+++ b/atuin-client/src/database.rs
@@ -385,11 +391,13 @@ impl Database for Sqlite {
async fn search(
&self,
- limit: Option<i64>,
search_mode: SearchMode,
filter: FilterMode,
context: &Context,
query: &str,
+ limit: Option<i64>,
+ before: Option<i64>,
+ after: Option<i64>,
) -> Result<Vec<History>> {
let mut sql = SqlBuilder::select_from("history");
diff --git a/atuin-client/src/database.rs b/atuin-client/src/database.rs
--- a/atuin-client/src/database.rs
+++ b/atuin-client/src/database.rs
@@ -401,6 +409,14 @@ impl Database for Sqlite {
sql.limit(limit);
}
+ if let Some(after) = after {
+ sql.and_where_gt("timestamp", after);
+ }
+
+ if let Some(before) = before {
+ sql.and_where_lt("timestamp", before);
+ }
+
match filter {
FilterMode::Global => &mut sql,
FilterMode::Host => sql.and_where_eq("hostname", quote(&context.hostname)),
diff --git a/src/command/client/search.rs b/src/command/client/search.rs
--- a/src/command/client/search.rs
+++ b/src/command/client/search.rs
@@ -148,13 +148,25 @@ async fn run_non_interactive(
let context = current_context();
+ let before = before.and_then(|b| {
+ interim::parse_date_string(b.as_str(), Utc::now(), interim::Dialect::Uk)
+ .map_or(None, |d| Some(d.timestamp_nanos()))
+ });
+
+ let after = after.and_then(|a| {
+ interim::parse_date_string(a.as_str(), Utc::now(), interim::Dialect::Uk)
+ .map_or(None, |d| Some(d.timestamp_nanos()))
+ });
+
let results = db
.search(
- limit,
settings.search_mode,
settings.filter_mode,
&context,
query.join(" ").as_str(),
+ limit,
+ before,
+ after,
)
.await?;
diff --git a/src/command/client/search.rs b/src/command/client/search.rs
--- a/src/command/client/search.rs
+++ b/src/command/client/search.rs
@@ -187,24 +199,6 @@ async fn run_non_interactive(
}
}
- if let Some(before) = &before {
- let before =
- interim::parse_date_string(before.as_str(), Utc::now(), interim::Dialect::Uk);
-
- if before.is_err() || h.timestamp.gt(&before.unwrap()) {
- return false;
- }
- }
-
- if let Some(after) = &after {
- let after =
- interim::parse_date_string(after.as_str(), Utc::now(), interim::Dialect::Uk);
-
- if after.is_err() || h.timestamp.lt(&after.unwrap()) {
- return false;
- }
- }
-
true
})
.map(std::borrow::ToOwned::to_owned)
diff --git a/src/command/client/search/interactive.rs b/src/command/client/search/interactive.rs
--- a/src/command/client/search/interactive.rs
+++ b/src/command/client/search/interactive.rs
@@ -57,8 +57,16 @@ impl State {
db.list(self.filter_mode, &self.context, Some(200), true)
.await?
} else {
- db.search(Some(200), search_mode, self.filter_mode, &self.context, i)
- .await?
+ db.search(
+ search_mode,
+ self.filter_mode,
+ &self.context,
+ i,
+ Some(200),
+ None,
+ None,
+ )
+ .await?
};
self.results_state.select(0);
|
diff --git a/atuin-client/src/database.rs b/atuin-client/src/database.rs
--- a/atuin-client/src/database.rs
+++ b/atuin-client/src/database.rs
@@ -498,7 +514,9 @@ mod test {
cwd: "/home/ellie".to_string(),
};
- let results = db.search(None, mode, filter_mode, &context, query).await?;
+ let results = db
+ .search(mode, filter_mode, &context, query, None, None, None)
+ .await?;
assert_eq!(
results.len(),
diff --git a/atuin-client/src/database.rs b/atuin-client/src/database.rs
--- a/atuin-client/src/database.rs
+++ b/atuin-client/src/database.rs
@@ -701,7 +719,15 @@ mod test {
}
let start = Instant::now();
let _results = db
- .search(None, SearchMode::Fuzzy, FilterMode::Global, &context, "")
+ .search(
+ SearchMode::Fuzzy,
+ FilterMode::Global,
+ &context,
+ "",
+ None,
+ None,
+ None,
+ )
.await
.unwrap();
let duration = start.elapsed();
|
bug(search): `limit` cant be used with `before` to search for results before a timestamp
`limit` is passed directly to `db.search` and `before` is applied in a `filter` after the results are fetched from the `db`.
I was trying to get the latest command run before a certain time, but I ended up getting 0 results back since `--limit=1` got the latest result which was after my `--before=$TIME`.
|
2023-03-08T22:34:07Z
|
13.0
|
2023-03-08T23:45:16Z
|
edcd477153d00944c5dae16ec3ba69e339e1450c
|
[
"encryption::test::test_encrypt_decrypt",
"import::zsh::test::test_parse_extended_simple",
"import::bash::test::parse_with_partial_timestamps",
"import::bash::test::parse_no_timestamps",
"import::bash::test::parse_with_timestamps",
"import::zsh::test::test_parse_file",
"import::fish::test::parse_complex",
"import::zsh_histdb::test::test_env_vars",
"import::zsh_histdb::test::test_import",
"database::test::test_search_fulltext",
"database::test::test_search_prefix",
"database::test::test_search_reordered_fuzzy",
"database::test::test_search_fuzzy",
"database::test::test_search_bench_dupes"
] |
[] |
[] |
[] |
auto_2025-06-06
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.