Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add cwd aware hinter #647

Merged
merged 7 commits into from
Oct 19, 2023
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
88 changes: 88 additions & 0 deletions examples/cwd_aware_hinter.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
// Create a reedline object with in-line hint support.
// cargo run --example cwd_aware_hinter
//
// Fish-style cwd history based hinting
// assuming history ["abc", "ade"]
// pressing "a" hints to abc.
// Up/Down or Ctrl p/n, to select next/previous match
use std::io;

#[cfg(any(feature = "sqlite", feature = "sqlite-dynlib"))]
fn create_item(cwd: &str, cmd: &str, exit_status: i64) -> reedline::HistoryItem {
use std::time::Duration;

use reedline::HistoryItem;
HistoryItem {
id: None,
start_timestamp: None,
command_line: cmd.to_string(),
session_id: None,
hostname: Some("foohost".to_string()),
cwd: Some(cwd.to_string()),
duration: Some(Duration::from_millis(1000)),
exit_status: Some(exit_status),
more_info: None,
}
}

#[cfg(any(feature = "sqlite", feature = "sqlite-dynlib"))]
fn create_filled_example_history(home_dir: &str, orig_dir: &str) -> Box<dyn reedline::History> {
use reedline::{History, SqliteBackedHistory};
let mut history = SqliteBackedHistory::in_memory().unwrap();
history.save(create_item(orig_dir, "dummy", 0)).unwrap(); // add dummy item so ids start with 1
history.save(create_item(orig_dir, "ls /usr", 0)).unwrap();
history.save(create_item(orig_dir, "pwd", 0)).unwrap();

history.save(create_item(home_dir, "cat foo", 0)).unwrap();
history.save(create_item(home_dir, "ls bar", 0)).unwrap();
history.save(create_item(home_dir, "rm baz", 0)).unwrap();
Box::new(history)
}

fn main() -> io::Result<()> {
#[cfg(any(feature = "sqlite", feature = "sqlite-dynlib"))]
return {
use nu_ansi_term::{Color, Style};
use reedline::{CwdAwareHinter, DefaultPrompt, Reedline, Signal};

let orig_dir = std::env::current_dir().unwrap();
#[allow(deprecated)]
let home_dir = std::env::home_dir().unwrap();

let history = create_filled_example_history(
&home_dir.to_string_lossy().to_string(),
&orig_dir.to_string_lossy().to_string(),
);

let mut line_editor = Reedline::create()
.with_hinter(Box::new(
CwdAwareHinter::default().with_style(Style::new().italic().fg(Color::Yellow)),
))
.with_history(history);

let prompt = DefaultPrompt::default();

let mut iterations = 0;
loop {
if iterations % 2 == 0 {
std::env::set_current_dir(&orig_dir).unwrap();
} else {
std::env::set_current_dir(&home_dir).unwrap();
}
let sig = line_editor.read_line(&prompt)?;
match sig {
Signal::Success(buffer) => {
println!("We processed: {buffer}");
}
Signal::CtrlD | Signal::CtrlC => {
println!("\nAborted!");
break Ok(());
}
}
iterations += 1;
}
};

#[cfg(not(any(feature = "sqlite", feature = "sqlite-dynlib")))]
panic!("cwd-aware hinter needs sqlite backed history");
}
100 changes: 100 additions & 0 deletions src/hinter/cwd_aware.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
#[cfg(any(feature = "sqlite", feature = "sqlite-dynlib"))]
use crate::{history::SearchQuery, Hinter, History};
#[cfg(any(feature = "sqlite", feature = "sqlite-dynlib"))]
use nu_ansi_term::{Color, Style};

/// A hinter that uses the completions or the history to show a hint to the user
/// NOTE: Only use this with `SqliteBackedHistory`!
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@sholderbach How does this look?

/// Similar to `fish` autosuggestins
#[cfg(any(feature = "sqlite", feature = "sqlite-dynlib"))]
pub struct CwdAwareHinter {
style: Style,
current_hint: String,
min_chars: usize,
}

#[cfg(any(feature = "sqlite", feature = "sqlite-dynlib"))]
impl Hinter for CwdAwareHinter {
fn handle(
&mut self,
line: &str,
#[allow(unused_variables)] pos: usize,
history: &dyn History,
use_ansi_coloring: bool,
) -> String {
self.current_hint = if line.chars().count() >= self.min_chars {
history
.search(SearchQuery::last_with_prefix_and_cwd(
line.to_string(),
history.session(),
))
.expect("todo: error handling")
.get(0)
.map_or_else(String::new, |entry| {
entry
.command_line
.get(line.len()..)
.unwrap_or_default()
.to_string()
})

Check warning on line 39 in src/hinter/cwd_aware.rs

View check run for this annotation

Codecov / codecov/patch

src/hinter/cwd_aware.rs#L18-L39

Added lines #L18 - L39 were not covered by tests
} else {
String::new()

Check warning on line 41 in src/hinter/cwd_aware.rs

View check run for this annotation

Codecov / codecov/patch

src/hinter/cwd_aware.rs#L41

Added line #L41 was not covered by tests
};

if use_ansi_coloring && !self.current_hint.is_empty() {
self.style.paint(&self.current_hint).to_string()

Check warning on line 45 in src/hinter/cwd_aware.rs

View check run for this annotation

Codecov / codecov/patch

src/hinter/cwd_aware.rs#L44-L45

Added lines #L44 - L45 were not covered by tests
} else {
self.current_hint.clone()

Check warning on line 47 in src/hinter/cwd_aware.rs

View check run for this annotation

Codecov / codecov/patch

src/hinter/cwd_aware.rs#L47

Added line #L47 was not covered by tests
}
}

Check warning on line 49 in src/hinter/cwd_aware.rs

View check run for this annotation

Codecov / codecov/patch

src/hinter/cwd_aware.rs#L49

Added line #L49 was not covered by tests

fn complete_hint(&self) -> String {
self.current_hint.clone()
}

Check warning on line 53 in src/hinter/cwd_aware.rs

View check run for this annotation

Codecov / codecov/patch

src/hinter/cwd_aware.rs#L51-L53

Added lines #L51 - L53 were not covered by tests

fn next_hint_token(&self) -> String {
let mut reached_content = false;
let result: String = self
.current_hint
.chars()
.take_while(|c| match (c.is_whitespace(), reached_content) {
(true, true) => false,
(true, false) => true,
(false, true) => true,

Check warning on line 63 in src/hinter/cwd_aware.rs

View check run for this annotation

Codecov / codecov/patch

src/hinter/cwd_aware.rs#L55-L63

Added lines #L55 - L63 were not covered by tests
(false, false) => {
reached_content = true;
true

Check warning on line 66 in src/hinter/cwd_aware.rs

View check run for this annotation

Codecov / codecov/patch

src/hinter/cwd_aware.rs#L65-L66

Added lines #L65 - L66 were not covered by tests
}
})
.collect();
result
}

Check warning on line 71 in src/hinter/cwd_aware.rs

View check run for this annotation

Codecov / codecov/patch

src/hinter/cwd_aware.rs#L68-L71

Added lines #L68 - L71 were not covered by tests
}

#[cfg(any(feature = "sqlite", feature = "sqlite-dynlib"))]
impl Default for CwdAwareHinter {
fn default() -> Self {
CwdAwareHinter {
style: Style::new().fg(Color::LightGray),
current_hint: String::new(),
min_chars: 1,
}
}

Check warning on line 82 in src/hinter/cwd_aware.rs

View check run for this annotation

Codecov / codecov/patch

src/hinter/cwd_aware.rs#L76-L82

Added lines #L76 - L82 were not covered by tests
}

#[cfg(any(feature = "sqlite", feature = "sqlite-dynlib"))]
impl CwdAwareHinter {
/// A builder that sets the style applied to the hint as part of the buffer
#[must_use]
pub fn with_style(mut self, style: Style) -> Self {
self.style = style;
self
}

Check warning on line 92 in src/hinter/cwd_aware.rs

View check run for this annotation

Codecov / codecov/patch

src/hinter/cwd_aware.rs#L89-L92

Added lines #L89 - L92 were not covered by tests

/// A builder that sets the number of characters that have to be present to enable history hints
#[must_use]
pub fn with_min_chars(mut self, min_chars: usize) -> Self {
self.min_chars = min_chars;
self
}

Check warning on line 99 in src/hinter/cwd_aware.rs

View check run for this annotation

Codecov / codecov/patch

src/hinter/cwd_aware.rs#L96-L99

Added lines #L96 - L99 were not covered by tests
}
4 changes: 1 addition & 3 deletions src/hinter/default.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
use crate::{history::SearchQuery, Hinter, History};
use nu_ansi_term::{Color, Style};

/// A hinter that use the completions or the history to show a hint to the user
///
/// Similar to `fish` autosuggestins
/// A hinter that uses the completions or the history to show a hint to the user
pub struct DefaultHinter {
style: Style,
current_hint: String,
Expand Down
3 changes: 3 additions & 0 deletions src/hinter/mod.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
mod cwd_aware;
mod default;
#[cfg(any(feature = "sqlite", feature = "sqlite-dynlib"))]
pub use cwd_aware::CwdAwareHinter;
pub use default::DefaultHinter;

use crate::History;
Expand Down
32 changes: 32 additions & 0 deletions src/history/base.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,18 @@
s
}

/// Create a search filter with a [`CommandLineSearch`] and `cwd`
pub fn from_text_search_cwd(
cwd: String,
cmd: CommandLineSearch,
session: Option<HistorySessionId>,
) -> SearchFilter {
let mut s = SearchFilter::anything(session);
s.command_line = Some(cmd);
s.cwd_exact = Some(cwd);
s
}

Check warning on line 79 in src/history/base.rs

View check run for this annotation

Codecov / codecov/patch

src/history/base.rs#L70-L79

Added lines #L70 - L79 were not covered by tests

/// anything within this session
pub fn anything(session: Option<HistorySessionId>) -> SearchFilter {
SearchFilter {
Expand Down Expand Up @@ -134,6 +146,26 @@
))
}

/// Get the most recent entry starting with the `prefix` and `cwd` same as the current cwd
pub fn last_with_prefix_and_cwd(
prefix: String,
session: Option<HistorySessionId>,
) -> SearchQuery {
let cwd = std::env::current_dir();
if let Ok(cwd) = cwd {
SearchQuery::last_with_search(SearchFilter::from_text_search_cwd(
cwd.to_string_lossy().to_string(),
CommandLineSearch::Prefix(prefix),
session,
))

Check warning on line 160 in src/history/base.rs

View check run for this annotation

Codecov / codecov/patch

src/history/base.rs#L150-L160

Added lines #L150 - L160 were not covered by tests
} else {
SearchQuery::last_with_search(SearchFilter::from_text_search(
CommandLineSearch::Prefix(prefix),
session,
))

Check warning on line 165 in src/history/base.rs

View check run for this annotation

Codecov / codecov/patch

src/history/base.rs#L162-L165

Added lines #L162 - L165 were not covered by tests
}
}

Check warning on line 167 in src/history/base.rs

View check run for this annotation

Codecov / codecov/patch

src/history/base.rs#L167

Added line #L167 was not covered by tests

/// Query to get all entries in the given [`SearchDirection`]
pub fn everything(
direction: SearchDirection,
Expand Down
2 changes: 2 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -269,6 +269,8 @@ mod completion;
pub use completion::{Completer, DefaultCompleter, Span, Suggestion};

mod hinter;
#[cfg(any(feature = "sqlite", feature = "sqlite-dynlib"))]
pub use hinter::CwdAwareHinter;
pub use hinter::{DefaultHinter, Hinter};

mod validator;
Expand Down