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

feat(pm): impl apt_qs, allow keeping header with grep #554

Merged
merged 3 commits into from
Mar 31, 2023
Merged
Show file tree
Hide file tree
Changes from all 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
220 changes: 136 additions & 84 deletions Cargo.lock

Large diffs are not rendered by default.

9 changes: 5 additions & 4 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -30,12 +30,12 @@ xshell = "0.2.3"
[dependencies]
async-trait = "0.1.68"
bytes = "1.4.0"
clap = { version = "4.1.13", features = ["cargo", "derive"] }
clap = { version = "4.2.1", features = ["cargo", "derive"] }
console = "0.15.5"
dialoguer = { version = "0.10.3", features = ["fuzzy-select"] }
dirs-next = "2.0.0"
figment = { version = "0.10.8", features = ["env", "toml"] }
futures = { version = "0.3.27", default-features = false, features = ["std"] }
futures = { version = "0.3.28", default-features = false, features = ["std"] }
indoc = "2.0.1"
is-root = "0.1.2"
itertools = "0.10.5"
Expand All @@ -46,12 +46,13 @@ paste = "1.0.12"
regex = { version = "1.7.3", default-features = false, features = [
"std",
"perf",
"unicode-case",
"unicode-perl",
] }
serde = { version = "1.0.158", features = ["derive"] }
serde = { version = "1.0.159", features = ["derive"] }
tap = "1.0.1"
thiserror = "1.0.40"
tokio = { version = "1.26.0", features = [
tokio = { version = "1.27.0", features = [
"io-std",
"io-util",
"macros",
Expand Down
4 changes: 2 additions & 2 deletions crates/pacaptr-macros/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,8 @@ anyhow = "1.0.70"
itertools = "0.10.5"
litrs = "0.4.0"
once_cell = "1.17.1"
proc-macro2 = "1.0.53"
proc-macro2 = "1.0.54"
quote = "1.0.26"
regex = "1.7.3"
syn = "2.0.10"
syn = "2.0.12"
tabled = "0.10.0"
31 changes: 21 additions & 10 deletions src/exec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ use futures::prelude::*;
use indoc::indoc;
use is_root::is_root;
use itertools::{chain, Itertools};
use regex::Regex;
use regex::{RegexSet, RegexSetBuilder};
use tap::prelude::*;
use tokio::{
io::{self, AsyncRead, AsyncWrite},
Expand Down Expand Up @@ -388,23 +388,34 @@ macro_rules! docs_errors_grep {
/// An error message will be returned if this is not the case.
#[doc = docs_errors_grep!()]
pub fn grep<'t>(text: &'t str, patterns: &[&str]) -> Result<Vec<&'t str>> {
let patterns: Vec<Regex> = patterns
.iter()
.map(|pat| {
Regex::new(pat)
.map_err(|_e| Error::OtherError(format!("Pattern `{pat}` is ill-formed")))
})
.try_collect()?;
let patterns: RegexSet = RegexSetBuilder::new(patterns)
.case_insensitive(true)
.build()
.map_err(|e| Error::OtherError(format!("ill-formed patterns found: {e:?}")))?;
Ok(text
.lines()
.filter(|line| patterns.iter().all(|pat| pat.is_match(line)))
.filter(|line| patterns.matches(line).into_iter().count() == patterns.len())
.collect())
}

/// Prints the result of [`grep`] line by line.
#[doc = docs_errors_grep!()]
pub fn grep_print(text: &str, patterns: &[&str]) -> Result<()> {
grep(text, patterns).map(|lns| lns.iter().for_each(|ln| println!("{ln}")))
grep_print_with_header(text, patterns, 0)
}

/// Prints the result of [`grep`] line by line, with `header_lines` of header
/// prepended.
/// If `header_lines >= text.lines().count()`, then `text` is printed without
/// changes.
#[doc = docs_errors_grep!()]
pub fn grep_print_with_header(text: &str, patterns: &[&str], header_lines: usize) -> Result<()> {
let lns = text.lines();
lns.take(header_lines).for_each(|ln| println!("{ln}"));
grep(text, patterns)?
.into_iter()
.for_each(|ln| println!("{ln}"));
Ok(())
}

/// Checks if an executable exists by name (consult `$PATH`) or by path.
Expand Down
20 changes: 17 additions & 3 deletions src/pm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -410,16 +410,30 @@ pub trait PmHelper: Pm {
.await
}

/// Executes a command in [`PmMode::Mute`] and prints out the lines that
/// match against the given regex `patterns`.
/// Executes a command in [`PmMode::Mute`] and prints the output lines
/// that match against the given regex `patterns`.
async fn search_regex(&self, cmd: Cmd, patterns: &[&str]) -> Result<()> {
self.search_regex_with_header(cmd, patterns, 0).await
}

/// Executes a command in [`PmMode::Mute`] and prints `header_lines` of
/// header followed by the output lines that match against the given regex
/// `patterns`.
/// If `header_lines >= text.lines().count()`, then the
/// output lines are printed without changes.
async fn search_regex_with_header(
&self,
cmd: Cmd,
patterns: &[&str],
header_lines: usize,
) -> Result<()> {
if !self.cfg().dry_run {
println_quoted(&*prompt::RUNNING, &cmd);
}
let out_bytes = self
.check_output(cmd, PmMode::Mute, &Strategy::default())
.await?;
exec::grep_print(&String::from_utf8(out_bytes)?, patterns)
exec::grep_print_with_header(&String::from_utf8(out_bytes)?, patterns, header_lines)
}
}

Expand Down
11 changes: 11 additions & 0 deletions src/pm/apt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,17 @@ impl Pm for Apt {
.await
}

/// Qs searches locally installed package for names or descriptions.
// According to https://www.archlinux.org/pacman/pacman.8.html#_query_options_apply_to_em_q_em_a_id_qo_a,
// when including multiple search terms, only packages with descriptions
// matching ALL of those terms are returned.
async fn qs(&self, kws: &[&str], flags: &[&str]) -> Result<()> {
Cmd::new(["dpkg-query", "-l"])
.flags(flags)
.pipe(|cmd| self.search_regex_with_header(cmd, kws, 4))
.await
}

/// Qu lists packages which have an update available.
async fn qu(&self, kws: &[&str], flags: &[&str]) -> Result<()> {
Cmd::with_sudo(["apt", "upgrade", "--trivial-only"])
Expand Down
3 changes: 2 additions & 1 deletion src/pm/dnf.rs
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,8 @@ impl Pm for Dnf {
/// Qs searches locally installed package for names or descriptions.
// According to https://www.archlinux.org/pacman/pacman.8.html#_query_options_apply_to_em_q_em_a_id_qo_a,
// when including multiple search terms, only packages with descriptions
// matching ALL of those terms are returned. TODO: Is this right?
// matching ALL of those terms are returned.
// TODO: Is this right?
async fn qs(&self, kws: &[&str], flags: &[&str]) -> Result<()> {
self.search_regex(Cmd::new(["rpm", "-qa"]).flags(flags), kws)
.await
Expand Down
2 changes: 1 addition & 1 deletion src/pm/scoop.rs
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ impl Pm for Scoop {
async fn qs(&self, kws: &[&str], flags: &[&str]) -> Result<()> {
Cmd::new([&self.shell, "-Command", "scoop", "list"])
.flags(flags)
.pipe(|cmd| self.search_regex(cmd, kws))
.pipe(|cmd| self.search_regex_with_header(cmd, kws, 4))
.await
}

Expand Down
9 changes: 9 additions & 0 deletions tests/apt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,15 @@ fn apt_qp_sw() {
"## }
}

#[cfg(target_os = "linux")]
#[test]
fn apt_qs() {
test_dsl! { r##"
in -Qs shell
ou Bourne Again SHell
"## }
}

#[test]
#[ignore]
fn apt_r_s() {
Expand Down