minor improvements of iterators

This commit is contained in:
Conrad Ludgate 2021-12-11 12:37:03 +00:00
parent 87df7d80ec
commit e4c6826647
7 changed files with 62 additions and 72 deletions

View File

@ -134,8 +134,8 @@ impl<'a> Client<'a> {
let history = resp.json::<SyncHistoryResponse>().await?;
let history = history
.history
.iter()
.map(|h| serde_json::from_str(h).expect("invalid base64"))
.into_iter()
.map(|h| serde_json::from_str(&h).expect("invalid base64"))
.map(|h| decrypt(&h, &self.key).expect("failed to decrypt history! check your key"))
.collect();

View File

@ -418,7 +418,7 @@ mod test {
// if fuzzy reordering is on, it should come back in a more sensible order
let mut results = db.search(None, SearchMode::Fuzzy, "curl").await.unwrap();
assert_eq!(results.len(), 2);
let commands: Vec<&String> = results.iter().map(|a| &a.command).collect();
let commands: Vec<String> = results.into_iter().map(|a| a.command).collect();
assert_eq!(commands, vec!["curl", "corburl"]);
results = db.search(None, SearchMode::Fuzzy, "xxxx").await.unwrap();

View File

@ -11,7 +11,6 @@ use chrono::prelude::*;
use chrono::Utc;
use directories::UserDirs;
use eyre::{eyre, Result};
use itertools::Itertools;
use super::{count_lines, Importer};
use crate::history::History;
@ -132,8 +131,8 @@ impl<R: Read> Iterator for Zsh<R> {
fn parse_extended(line: &str, counter: i64) -> History {
let line = line.replacen(": ", "", 2);
let (time, duration) = line.splitn(2, ':').collect_tuple().unwrap();
let (duration, command) = duration.splitn(2, ';').collect_tuple().unwrap();
let (time, duration) = line.split_once(':').unwrap();
let (duration, command) = duration.split_once(';').unwrap();
let time = time
.parse::<i64>()

View File

@ -15,9 +15,9 @@ where
A: Clone,
{
let mut r = res.clone();
let qvec = &query.chars().collect();
let qvec: Vec<char> = query.chars().collect();
r.sort_by_cached_key(|h| {
let (from, to) = match minspan::span(qvec, &(f(h).chars().collect())) {
let (from, to) = match minspan::span(&qvec, &(f(h).chars().collect())) {
Some(x) => x,
// this is a little unfortunate: when we are asked to match a query that is found nowhere,
// we don't want to return a None, as the comparison behaviour would put the worst matches

View File

@ -30,19 +30,18 @@ pub async fn list(
)
.await;
if let Err(e) = history {
error!("failed to load history: {}", e);
return reply_error(
ErrorResponse::reply("failed to load history")
.with_status(StatusCode::INTERNAL_SERVER_ERROR),
);
}
let history = match history {
Err(e) => {
error!("failed to load history: {}", e);
return reply_error(
ErrorResponse::reply("failed to load history")
.with_status(StatusCode::INTERNAL_SERVER_ERROR),
);
}
Ok(h) => h,
};
let history: Vec<String> = history
.unwrap()
.iter()
.map(|i| i.data.to_string())
.collect();
let history: Vec<String> = history.into_iter().map(|i| i.data).collect();
debug!(
"loaded {} items of history for user {}",

View File

@ -70,8 +70,7 @@ pub fn print_list(h: &[History], human: bool, cmd_only: bool) {
h.duration, 0,
) as u64))
.to_string();
let duration: Vec<&str> = duration.split(' ').collect();
let duration = duration[0];
let duration = duration.split(' ').next().unwrap();
format!(
"{}\t{}\t{}\n",

View File

@ -39,15 +39,14 @@ impl State {
let duration =
Duration::from_millis(std::cmp::max(h.duration, 0) as u64 / 1_000_000);
let duration = humantime::format_duration(duration).to_string();
let duration: Vec<&str> = duration.split(' ').collect();
let duration = duration.split(' ').next().unwrap();
let ago = chrono::Utc::now().sub(h.timestamp);
let ago = humantime::format_duration(ago.to_std().unwrap()).to_string();
let ago: Vec<&str> = ago.split(' ').collect();
let ago = ago.split(' ').next().unwrap();
(
duration[0]
.to_string()
duration
.replace("days", "d")
.replace("day", "d")
.replace("weeks", "w")
@ -56,9 +55,7 @@ impl State {
.replace("month", "mo")
.replace("years", "y")
.replace("year", "y"),
ago[0]
.to_string()
.replace("days", "d")
ago.replace("days", "d")
.replace("day", "d")
.replace("weeks", "w")
.replace("week", "w")
@ -87,7 +84,7 @@ impl State {
.iter()
.enumerate()
.map(|(i, m)| {
let command = m.command.to_string().replace("\n", " ").replace("\t", " ");
let command = m.command.replace("\n", " ").replace("\t", " ");
let mut command = Span::raw(command);
@ -381,67 +378,63 @@ pub async fn run(
let item = select_history(query, settings.search_mode, db).await?;
eprintln!("{}", item);
} else {
let results = db
let mut results = db
.search(None, settings.search_mode, query.join(" ").as_str())
.await?;
// TODO: This filtering would be better done in the SQL query, I just
// need a nice way of building queries.
let results: Vec<History> = results
.iter()
.filter(|h| {
if let Some(exit) = exit {
if h.exit != exit {
return false;
}
results.retain(|h| {
if let Some(exit) = exit {
if h.exit != exit {
return false;
}
}
if let Some(exit) = exclude_exit {
if h.exit == exit {
return false;
}
if let Some(exit) = exclude_exit {
if h.exit == exit {
return false;
}
}
if let Some(cwd) = &exclude_cwd {
if h.cwd.as_str() == cwd.as_str() {
return false;
}
if let Some(cwd) = &exclude_cwd {
if h.cwd.as_str() == cwd.as_str() {
return false;
}
}
if let Some(cwd) = &dir {
if h.cwd.as_str() != cwd.as_str() {
return false;
}
if let Some(cwd) = &dir {
if h.cwd.as_str() != cwd.as_str() {
return false;
}
}
if let Some(before) = &before {
let before = chrono_english::parse_date_string(
before.as_str(),
Utc::now(),
chrono_english::Dialect::Uk,
);
if let Some(before) = &before {
let before = chrono_english::parse_date_string(
before.as_str(),
Utc::now(),
chrono_english::Dialect::Uk,
);
if before.is_err() || h.timestamp.gt(&before.unwrap()) {
return false;
}
if before.is_err() || h.timestamp.gt(&before.unwrap()) {
return false;
}
}
if let Some(after) = &after {
let after = chrono_english::parse_date_string(
after.as_str(),
Utc::now(),
chrono_english::Dialect::Uk,
);
if let Some(after) = &after {
let after = chrono_english::parse_date_string(
after.as_str(),
Utc::now(),
chrono_english::Dialect::Uk,
);
if after.is_err() || h.timestamp.lt(&after.unwrap()) {
return false;
}
if after.is_err() || h.timestamp.lt(&after.unwrap()) {
return false;
}
}
true
})
.map(std::borrow::ToOwned::to_owned)
.collect();
true
});
super::history::print_list(&results, human, cmd_only);
}