Skip to content

Commit

Permalink
Auto merge of #10425 - epage:search, r=alexcrichton
Browse files Browse the repository at this point in the history
feat(search): Highlight search term

This supersedes #10116.  For the requested colored-output tests, this followed the pattern of the `fix` tests which just detects whether colored output is used or not.  The `cache_messages` actually verify the output is colored but that is because it can just compare to a rustc call's output.  Getting the colored output correct by hand in a test (with all of the resets) is a bit messy and would be brittle.

This was done in an exercise in exploring ways to generalize colored output support in preparation for `cargo-add` doing some colored output as well.

I converted all output calls to use this approach, even if coloring wasn't used, for consistency.  I considered coloring the overflow message but decided to hold off on that for now (either a warning-yellow or a hint-gray).

Fixes #9918
  • Loading branch information
bors committed Feb 28, 2022
2 parents f75d4ea + 1eb8913 commit 9d754ed
Show file tree
Hide file tree
Showing 3 changed files with 72 additions and 10 deletions.
27 changes: 27 additions & 0 deletions src/cargo/core/shell.rs
Original file line number Diff line number Diff line change
Expand Up @@ -333,6 +333,17 @@ impl Shell {
}
}

/// Write a styled fragment
///
/// Caller is responsible for deciding whether [`Shell::verbosity`] is affects output.
pub fn write_stdout(
&mut self,
fragment: impl fmt::Display,
color: &ColorSpec,
) -> CargoResult<()> {
self.output.write_stdout(fragment, color)
}

/// Prints a message to stderr and translates ANSI escape code into console colors.
pub fn print_ansi_stderr(&mut self, message: &[u8]) -> CargoResult<()> {
if self.needs_clear {
Expand Down Expand Up @@ -423,6 +434,22 @@ impl ShellOut {
Ok(())
}

/// Write a styled fragment
fn write_stdout(&mut self, fragment: impl fmt::Display, color: &ColorSpec) -> CargoResult<()> {
match *self {
ShellOut::Stream { ref mut stdout, .. } => {
stdout.reset()?;
stdout.set_color(&color)?;
write!(stdout, "{}", fragment)?;
stdout.reset()?;
}
ShellOut::Write(ref mut w) => {
write!(w, "{}", fragment)?;
}
}
Ok(())
}

/// Gets stdout as a `io::Write`.
fn stdout(&mut self) -> &mut dyn Write {
match *self {
Expand Down
31 changes: 21 additions & 10 deletions src/cargo/ops/registry.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ use crates_io::{self, NewCrate, NewCrateDependency, Registry};
use curl::easy::{Easy, InfoType, SslOpt, SslVersion};
use log::{log, Level};
use percent_encoding::{percent_encode, NON_ALPHANUMERIC};
use termcolor::Color::Green;
use termcolor::ColorSpec;

use crate::core::dependency::DepKind;
use crate::core::manifest::ManifestMetadata;
Expand Down Expand Up @@ -955,15 +957,26 @@ pub fn search(
}
None => name,
};
drop_println!(config, "{}", line);
let mut fragments = line.split(query).peekable();
while let Some(fragment) = fragments.next() {
let _ = config.shell().write_stdout(fragment, &ColorSpec::new());
if fragments.peek().is_some() {
let _ = config
.shell()
.write_stdout(query, &ColorSpec::new().set_bold(true).set_fg(Some(Green)));
}
}
let _ = config.shell().write_stdout("\n", &ColorSpec::new());
}

let search_max_limit = 100;
if total_crates > limit && limit < search_max_limit {
drop_println!(
config,
"... and {} crates more (use --limit N to see more)",
total_crates - limit
let _ = config.shell().write_stdout(
format_args!(
"... and {} crates more (use --limit N to see more)\n",
total_crates - limit
),
&ColorSpec::new(),
);
} else if total_crates > limit && limit >= search_max_limit {
let extra = if source_id.is_default_registry() {
Expand All @@ -974,11 +987,9 @@ pub fn search(
} else {
String::new()
};
drop_println!(
config,
"... and {} crates more{}",
total_crates - limit,
extra
let _ = config.shell().write_stdout(
format_args!("... and {} crates more{}\n", total_crates - limit, extra),
&ColorSpec::new(),
);
}

Expand Down
24 changes: 24 additions & 0 deletions tests/testsuite/search.rs
Original file line number Diff line number Diff line change
Expand Up @@ -190,3 +190,27 @@ fn multiple_query_params() {
.with_stdout_contains(SEARCH_RESULTS)
.run();
}

#[cargo_test]
fn ignore_quiet() {
setup();
set_cargo_config();

cargo_process("search -q postgres")
.with_stdout_contains(SEARCH_RESULTS)
.run();
}

#[cargo_test]
fn colored_results() {
setup();
set_cargo_config();

cargo_process("search --color=never postgres")
.with_stdout_does_not_contain("[..]\x1b[[..]")
.run();

cargo_process("search --color=always postgres")
.with_stdout_contains("[..]\x1b[[..]")
.run();
}

0 comments on commit 9d754ed

Please sign in to comment.