style: rustfmt everything

This is why I was so intent on clearing the PR queue. This will
effectively invalidate all existing patches, so I wanted to start from a
clean slate.

We do make one little tweak: we put the default type definitions in
their own file and tell rustfmt to keep its grubby mits off of it. We
also sort it lexicographically and hopefully will enforce that from here
on.
This commit is contained in:
Andrew Gallant
2020-02-17 18:08:47 -05:00
parent c95f29e3ba
commit 0bc4f0447b
67 changed files with 2707 additions and 2675 deletions

View File

@@ -62,42 +62,32 @@ impl ColorError {
impl fmt::Display for ColorError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
ColorError::UnrecognizedOutType(ref name) => {
write!(
f,
"unrecognized output type '{}'. Choose from: \
ColorError::UnrecognizedOutType(ref name) => write!(
f,
"unrecognized output type '{}'. Choose from: \
path, line, column, match.",
name,
)
}
ColorError::UnrecognizedSpecType(ref name) => {
write!(
f,
"unrecognized spec type '{}'. Choose from: \
name,
),
ColorError::UnrecognizedSpecType(ref name) => write!(
f,
"unrecognized spec type '{}'. Choose from: \
fg, bg, style, none.",
name,
)
}
ColorError::UnrecognizedColor(_, ref msg) => {
write!(f, "{}", msg)
}
ColorError::UnrecognizedStyle(ref name) => {
write!(
f,
"unrecognized style attribute '{}'. Choose from: \
name,
),
ColorError::UnrecognizedColor(_, ref msg) => write!(f, "{}", msg),
ColorError::UnrecognizedStyle(ref name) => write!(
f,
"unrecognized style attribute '{}'. Choose from: \
nobold, bold, nointense, intense, nounderline, \
underline.",
name,
)
}
ColorError::InvalidFormat(ref original) => {
write!(
f,
"invalid color spec format: '{}'. Valid format \
name,
),
ColorError::InvalidFormat(ref original) => write!(
f,
"invalid color spec format: '{}'. Valid format \
is '(path|line|column|match):(fg|bg|style):(value)'.",
original,
)
}
original,
),
}
}
}
@@ -227,7 +217,7 @@ enum Style {
Intense,
NoIntense,
Underline,
NoUnderline
NoUnderline,
}
impl ColorSpecs {
@@ -288,18 +278,32 @@ impl SpecValue {
fn merge_into(&self, cspec: &mut ColorSpec) {
match *self {
SpecValue::None => cspec.clear(),
SpecValue::Fg(ref color) => { cspec.set_fg(Some(color.clone())); }
SpecValue::Bg(ref color) => { cspec.set_bg(Some(color.clone())); }
SpecValue::Style(ref style) => {
match *style {
Style::Bold => { cspec.set_bold(true); }
Style::NoBold => { cspec.set_bold(false); }
Style::Intense => { cspec.set_intense(true); }
Style::NoIntense => { cspec.set_intense(false); }
Style::Underline => { cspec.set_underline(true); }
Style::NoUnderline => { cspec.set_underline(false); }
}
SpecValue::Fg(ref color) => {
cspec.set_fg(Some(color.clone()));
}
SpecValue::Bg(ref color) => {
cspec.set_bg(Some(color.clone()));
}
SpecValue::Style(ref style) => match *style {
Style::Bold => {
cspec.set_bold(true);
}
Style::NoBold => {
cspec.set_bold(false);
}
Style::Intense => {
cspec.set_intense(true);
}
Style::NoIntense => {
cspec.set_intense(false);
}
Style::Underline => {
cspec.set_underline(true);
}
Style::NoUnderline => {
cspec.set_underline(false);
}
},
}
}
}
@@ -315,10 +319,7 @@ impl FromStr for UserColorSpec {
let otype: OutType = pieces[0].parse()?;
match pieces[1].parse()? {
SpecType::None => {
Ok(UserColorSpec {
ty: otype,
value: SpecValue::None,
})
Ok(UserColorSpec { ty: otype, value: SpecValue::None })
}
SpecType::Style => {
if pieces.len() < 3 {
@@ -331,18 +332,16 @@ impl FromStr for UserColorSpec {
if pieces.len() < 3 {
return Err(ColorError::InvalidFormat(s.to_string()));
}
let color: Color = pieces[2]
.parse()
.map_err(ColorError::from_parse_error)?;
let color: Color =
pieces[2].parse().map_err(ColorError::from_parse_error)?;
Ok(UserColorSpec { ty: otype, value: SpecValue::Fg(color) })
}
SpecType::Bg => {
if pieces.len() < 3 {
return Err(ColorError::InvalidFormat(s.to_string()));
}
let color: Color = pieces[2]
.parse()
.map_err(ColorError::from_parse_error)?;
let color: Color =
pieces[2].parse().map_err(ColorError::from_parse_error)?;
Ok(UserColorSpec { ty: otype, value: SpecValue::Bg(color) })
}
}

View File

@@ -4,8 +4,8 @@ use std::time::Instant;
use grep_matcher::{Match, Matcher};
use grep_searcher::{
Searcher,
Sink, SinkError, SinkContext, SinkContextKind, SinkFinish, SinkMatch,
Searcher, Sink, SinkContext, SinkContextKind, SinkError, SinkFinish,
SinkMatch,
};
use serde_json as json;
@@ -27,11 +27,7 @@ struct Config {
impl Default for Config {
fn default() -> Config {
Config {
pretty: false,
max_matches: None,
always_begin_end: false,
}
Config { pretty: false, max_matches: None, always_begin_end: false }
}
}
@@ -492,8 +488,9 @@ impl<W: io::Write> JSON<W> {
matcher: M,
path: &'p P,
) -> JSONSink<'p, 's, M, W>
where M: Matcher,
P: ?Sized + AsRef<Path>,
where
M: Matcher,
P: ?Sized + AsRef<Path>,
{
JSONSink {
matcher: matcher,
@@ -615,10 +612,12 @@ impl<'p, 's, M: Matcher, W: io::Write> JSONSink<'p, 's, M, W> {
// the extent that it's easy to ensure that we never do more than
// one search to find the matches.
let matches = &mut self.json.matches;
self.matcher.find_iter(bytes, |m| {
matches.push(m);
true
}).map_err(io::Error::error_message)?;
self.matcher
.find_iter(bytes, |m| {
matches.push(m);
true
})
.map_err(io::Error::error_message)?;
// Don't report empty matches appearing at the end of the bytes.
if !matches.is_empty()
&& matches.last().unwrap().is_empty()
@@ -650,9 +649,7 @@ impl<'p, 's, M: Matcher, W: io::Write> JSONSink<'p, 's, M, W> {
if self.begin_printed {
return Ok(());
}
let msg = jsont::Message::Begin(jsont::Begin {
path: self.path,
});
let msg = jsont::Message::Begin(jsont::Begin { path: self.path });
self.json.write_message(&msg)?;
self.begin_printed = true;
Ok(())
@@ -699,13 +696,12 @@ impl<'p, 's, M: Matcher, W: io::Write> Sink for JSONSink<'p, 's, M, W> {
self.after_context_remaining =
self.after_context_remaining.saturating_sub(1);
}
let submatches =
if searcher.invert_match() {
self.record_matches(ctx.bytes())?;
SubMatches::new(ctx.bytes(), &self.json.matches)
} else {
SubMatches::empty()
};
let submatches = if searcher.invert_match() {
self.record_matches(ctx.bytes())?;
SubMatches::new(ctx.bytes(), &self.json.matches)
} else {
SubMatches::empty()
};
let msg = jsont::Message::Context(jsont::Context {
path: self.path,
lines: ctx.bytes(),
@@ -717,10 +713,7 @@ impl<'p, 's, M: Matcher, W: io::Write> Sink for JSONSink<'p, 's, M, W> {
Ok(!self.should_quit())
}
fn begin(
&mut self,
_searcher: &Searcher,
) -> Result<bool, io::Error> {
fn begin(&mut self, _searcher: &Searcher) -> Result<bool, io::Error> {
self.json.wtr.reset_count();
self.start_time = Instant::now();
self.match_count = 0;
@@ -779,7 +772,7 @@ enum SubMatches<'a> {
impl<'a> SubMatches<'a> {
/// Create a new set of match ranges from a set of matches and the
/// corresponding bytes that those matches apply to.
fn new(bytes: &'a[u8], matches: &[Match]) -> SubMatches<'a> {
fn new(bytes: &'a [u8], matches: &[Match]) -> SubMatches<'a> {
if matches.len() == 1 {
let mat = matches[0];
SubMatches::Small([jsont::SubMatch {
@@ -817,11 +810,11 @@ impl<'a> SubMatches<'a> {
#[cfg(test)]
mod tests {
use grep_regex::{RegexMatcher, RegexMatcherBuilder};
use grep_matcher::LineTerminator;
use grep_regex::{RegexMatcher, RegexMatcherBuilder};
use grep_searcher::SearcherBuilder;
use super::{JSON, JSONBuilder};
use super::{JSONBuilder, JSON};
const SHERLOCK: &'static [u8] = b"\
For the Doctor Watsons of this world, as opposed to the Sherlock
@@ -832,9 +825,7 @@ but Doctor Watson has to have it taken out for him and dusted,
and exhibited clearly, with a label attached.
";
fn printer_contents(
printer: &mut JSON<Vec<u8>>,
) -> String {
fn printer_contents(printer: &mut JSON<Vec<u8>>) -> String {
String::from_utf8(printer.get_mut().to_owned()).unwrap()
}
@@ -851,11 +842,8 @@ but Doctor Watson has to have it taken out for him and dusted,
and exhibited clearly, with a label attached.\
";
let matcher = RegexMatcher::new(
r"Watson"
).unwrap();
let mut printer = JSONBuilder::new()
.build(vec![]);
let matcher = RegexMatcher::new(r"Watson").unwrap();
let mut printer = JSONBuilder::new().build(vec![]);
SearcherBuilder::new()
.binary_detection(BinaryDetection::quit(b'\x00'))
.heap_limit(Some(80))
@@ -871,12 +859,9 @@ and exhibited clearly, with a label attached.\
#[test]
fn max_matches() {
let matcher = RegexMatcher::new(
r"Watson"
).unwrap();
let mut printer = JSONBuilder::new()
.max_matches(Some(1))
.build(vec![]);
let matcher = RegexMatcher::new(r"Watson").unwrap();
let mut printer =
JSONBuilder::new().max_matches(Some(1)).build(vec![]);
SearcherBuilder::new()
.build()
.search_reader(&matcher, SHERLOCK, printer.sink(&matcher))
@@ -888,11 +873,8 @@ and exhibited clearly, with a label attached.\
#[test]
fn no_match() {
let matcher = RegexMatcher::new(
r"DOES NOT MATCH"
).unwrap();
let mut printer = JSONBuilder::new()
.build(vec![]);
let matcher = RegexMatcher::new(r"DOES NOT MATCH").unwrap();
let mut printer = JSONBuilder::new().build(vec![]);
SearcherBuilder::new()
.build()
.search_reader(&matcher, SHERLOCK, printer.sink(&matcher))
@@ -904,12 +886,9 @@ and exhibited clearly, with a label attached.\
#[test]
fn always_begin_end_no_match() {
let matcher = RegexMatcher::new(
r"DOES NOT MATCH"
).unwrap();
let mut printer = JSONBuilder::new()
.always_begin_end(true)
.build(vec![]);
let matcher = RegexMatcher::new(r"DOES NOT MATCH").unwrap();
let mut printer =
JSONBuilder::new().always_begin_end(true).build(vec![]);
SearcherBuilder::new()
.build()
.search_reader(&matcher, SHERLOCK, printer.sink(&matcher))
@@ -924,11 +903,8 @@ and exhibited clearly, with a label attached.\
fn missing_crlf() {
let haystack = "test\r\n".as_bytes();
let matcher = RegexMatcherBuilder::new()
.build("test")
.unwrap();
let mut printer = JSONBuilder::new()
.build(vec![]);
let matcher = RegexMatcherBuilder::new().build("test").unwrap();
let mut printer = JSONBuilder::new().build(vec![]);
SearcherBuilder::new()
.build()
.search_reader(&matcher, haystack, printer.sink(&matcher))
@@ -941,12 +917,9 @@ and exhibited clearly, with a label attached.\
got.lines().nth(1).unwrap(),
);
let matcher = RegexMatcherBuilder::new()
.crlf(true)
.build("test")
.unwrap();
let mut printer = JSONBuilder::new()
.build(vec![]);
let matcher =
RegexMatcherBuilder::new().crlf(true).build("test").unwrap();
let mut printer = JSONBuilder::new().build(vec![]);
SearcherBuilder::new()
.line_terminator(LineTerminator::crlf())
.build()

View File

@@ -80,7 +80,9 @@ pub struct SubMatch<'a> {
#[derive(Clone, Debug, Hash, PartialEq, Eq, Serialize)]
#[serde(untagged)]
enum Data<'a> {
Text { text: Cow<'a, str> },
Text {
text: Cow<'a, str>,
},
Bytes {
#[serde(serialize_with = "to_base64")]
bytes: &'a [u8],
@@ -116,32 +118,26 @@ impl<'a> Data<'a> {
}
}
fn to_base64<T, S>(
bytes: T,
ser: S,
) -> Result<S::Ok, S::Error>
where T: AsRef<[u8]>,
S: Serializer
fn to_base64<T, S>(bytes: T, ser: S) -> Result<S::Ok, S::Error>
where
T: AsRef<[u8]>,
S: Serializer,
{
ser.serialize_str(&base64::encode(&bytes))
}
fn ser_bytes<T, S>(
bytes: T,
ser: S,
) -> Result<S::Ok, S::Error>
where T: AsRef<[u8]>,
S: Serializer
fn ser_bytes<T, S>(bytes: T, ser: S) -> Result<S::Ok, S::Error>
where
T: AsRef<[u8]>,
S: Serializer,
{
Data::from_bytes(bytes.as_ref()).serialize(ser)
}
fn ser_path<P, S>(
path: &Option<P>,
ser: S,
) -> Result<S::Ok, S::Error>
where P: AsRef<Path>,
S: Serializer
fn ser_path<P, S>(path: &Option<P>, ser: S) -> Result<S::Ok, S::Error>
where
P: AsRef<Path>,
S: Serializer,
{
path.as_ref().map(|p| Data::from_path(p.as_ref())).serialize(ser)
}

View File

@@ -84,9 +84,9 @@ extern crate serde_derive;
extern crate serde_json;
extern crate termcolor;
pub use color::{ColorError, ColorSpecs, UserColorSpec, default_color_specs};
pub use color::{default_color_specs, ColorError, ColorSpecs, UserColorSpec};
#[cfg(feature = "serde1")]
pub use json::{JSON, JSONBuilder, JSONSink};
pub use json::{JSONBuilder, JSONSink, JSON};
pub use standard::{Standard, StandardBuilder, StandardSink};
pub use stats::Stats;
pub use summary::{Summary, SummaryBuilder, SummaryKind, SummarySink};

View File

@@ -8,16 +8,15 @@ use std::time::Instant;
use bstr::ByteSlice;
use grep_matcher::{Match, Matcher};
use grep_searcher::{
LineStep, Searcher,
Sink, SinkError,
SinkContext, SinkContextKind, SinkFinish, SinkMatch,
LineStep, Searcher, Sink, SinkContext, SinkContextKind, SinkError,
SinkFinish, SinkMatch,
};
use termcolor::{ColorSpec, NoColor, WriteColor};
use color::ColorSpecs;
use counter::CounterWriter;
use stats::Stats;
use util::{PrinterPath, Replacer, Sunk, trim_ascii_prefix};
use util::{trim_ascii_prefix, PrinterPath, Replacer, Sunk};
/// The configuration for the standard printer.
///
@@ -151,10 +150,7 @@ impl StandardBuilder {
/// This completely overrides any previous color specifications. This does
/// not add to any previously provided color specifications on this
/// builder.
pub fn color_specs(
&mut self,
specs: ColorSpecs,
) -> &mut StandardBuilder {
pub fn color_specs(&mut self, specs: ColorSpecs) -> &mut StandardBuilder {
self.config.colors = specs;
self
}
@@ -409,10 +405,7 @@ impl StandardBuilder {
/// A typical use for this option is to permit cygwin users on Windows to
/// set the path separator to `/` instead of using the system default of
/// `\`.
pub fn separator_path(
&mut self,
sep: Option<u8>,
) -> &mut StandardBuilder {
pub fn separator_path(&mut self, sep: Option<u8>) -> &mut StandardBuilder {
self.config.separator_path = sep;
self
}
@@ -487,12 +480,7 @@ impl<W: WriteColor> Standard<W> {
&'s mut self,
matcher: M,
) -> StandardSink<'static, 's, M, W> {
let stats =
if self.config.stats {
Some(Stats::new())
} else {
None
};
let stats = if self.config.stats { Some(Stats::new()) } else { None };
let needs_match_granularity = self.needs_match_granularity();
StandardSink {
matcher: matcher,
@@ -517,20 +505,18 @@ impl<W: WriteColor> Standard<W> {
matcher: M,
path: &'p P,
) -> StandardSink<'p, 's, M, W>
where M: Matcher,
P: ?Sized + AsRef<Path>,
where
M: Matcher,
P: ?Sized + AsRef<Path>,
{
if !self.config.path {
return self.sink(matcher);
}
let stats =
if self.config.stats {
Some(Stats::new())
} else {
None
};
let stats = if self.config.stats { Some(Stats::new()) } else { None };
let ppath = PrinterPath::with_separator(
path.as_ref(), self.config.separator_path);
path.as_ref(),
self.config.separator_path,
);
let needs_match_granularity = self.needs_match_granularity();
StandardSink {
matcher: matcher,
@@ -689,10 +675,12 @@ impl<'p, 's, M: Matcher, W: WriteColor> StandardSink<'p, 's, M, W> {
// one search to find the matches (well, for replacements, we do one
// additional search to perform the actual replacement).
let matches = &mut self.standard.matches;
self.matcher.find_iter(bytes, |m| {
matches.push(m);
true
}).map_err(io::Error::error_message)?;
self.matcher
.find_iter(bytes, |m| {
matches.push(m);
true
})
.map_err(io::Error::error_message)?;
// Don't report empty matches appearing at the end of the bytes.
if !matches.is_empty()
&& matches.last().unwrap().is_empty()
@@ -714,11 +702,7 @@ impl<'p, 's, M: Matcher, W: WriteColor> StandardSink<'p, 's, M, W> {
.as_ref()
.map(|r| &*r)
.unwrap();
self.replacer.replace_all(
&self.matcher,
bytes,
replacement,
)?;
self.replacer.replace_all(&self.matcher, bytes, replacement)?;
}
Ok(())
}
@@ -811,10 +795,7 @@ impl<'p, 's, M: Matcher, W: WriteColor> Sink for StandardSink<'p, 's, M, W> {
Ok(true)
}
fn begin(
&mut self,
_searcher: &Searcher,
) -> Result<bool, io::Error> {
fn begin(&mut self, _searcher: &Searcher) -> Result<bool, io::Error> {
self.standard.wtr.borrow_mut().reset_count();
self.start_time = Instant::now();
self.match_count = 0;
@@ -887,10 +868,7 @@ impl<'a, M: Matcher, W: WriteColor> StandardImpl<'a, M, W> {
&sink.standard.matches,
sink.replacer.replacement(),
);
StandardImpl {
sunk: sunk,
..StandardImpl::new(searcher, sink)
}
StandardImpl { sunk: sunk, ..StandardImpl::new(searcher, sink) }
}
/// Bundle self with a searcher and return the core implementation of Sink
@@ -905,10 +883,7 @@ impl<'a, M: Matcher, W: WriteColor> StandardImpl<'a, M, W> {
&sink.standard.matches,
sink.replacer.replacement(),
);
StandardImpl {
sunk: sunk,
..StandardImpl::new(searcher, sink)
}
StandardImpl { sunk: sunk, ..StandardImpl::new(searcher, sink) }
}
fn sink(&self) -> io::Result<()> {
@@ -1084,10 +1059,7 @@ impl<'a, M: Matcher, W: WriteColor> StandardImpl<'a, M, W> {
line = line.with_start(upto);
if self.exceeds_max_columns(&bytes[this_line]) {
self.write_exceeded_line(
bytes,
this_line,
matches,
&mut midx,
bytes, this_line, matches, &mut midx,
)?;
} else {
self.write_spec(spec, &bytes[this_line])?;
@@ -1178,14 +1150,14 @@ impl<'a, M: Matcher, W: WriteColor> StandardImpl<'a, M, W> {
}
#[inline(always)]
fn write_line(
&self,
line: &[u8],
) -> io::Result<()> {
fn write_line(&self, line: &[u8]) -> io::Result<()> {
if self.exceeds_max_columns(line) {
let range = Match::new(0, line.len());
self.write_exceeded_line(
line, range, self.sunk.matches(), &mut 0,
line,
range,
self.sunk.matches(),
&mut 0,
)?;
} else {
self.write_trim(line)?;
@@ -1279,7 +1251,8 @@ impl<'a, M: Matcher, W: WriteColor> StandardImpl<'a, M, W> {
.map(|(_, end, _)| end)
.take(self.config().max_columns.unwrap_or(0) as usize)
.last()
.unwrap_or(0) + line.start();
.unwrap_or(0)
+ line.start();
line = line.with_end(end);
self.write_colored_matches(bytes, line, matches, match_index)?;
@@ -1292,16 +1265,12 @@ impl<'a, M: Matcher, W: WriteColor> StandardImpl<'a, M, W> {
m.start() >= line.end() && m.start() < original.end()
})
.count();
let tense =
if remaining == 1 {
"match"
} else {
"matches"
};
let tense = if remaining == 1 { "match" } else { "matches" };
write!(
self.wtr().borrow_mut(),
" [... {} more {}]",
remaining, tense,
remaining,
tense,
)?;
}
self.write_line_term()?;
@@ -1396,7 +1365,8 @@ impl<'a, M: Matcher, W: WriteColor> StandardImpl<'a, M, W> {
}
let remainder = format!(
"after match (found {:?} byte around offset {})\n",
[byte].as_bstr(), offset,
[byte].as_bstr(),
offset,
);
self.write(remainder.as_bytes())?;
} else if let Some(byte) = bin.convert_byte() {
@@ -1407,7 +1377,8 @@ impl<'a, M: Matcher, W: WriteColor> StandardImpl<'a, M, W> {
}
let remainder = format!(
"matches (found {:?} byte around offset {})\n",
[byte].as_bstr(), offset,
[byte].as_bstr(),
offset,
);
self.write(remainder.as_bytes())?;
}
@@ -1600,17 +1571,14 @@ but Doctor Watson has to have it taken out for him and dusted,\r
and exhibited clearly, with a label attached.\
";
fn printer_contents(
printer: &mut Standard<NoColor<Vec<u8>>>,
) -> String {
fn printer_contents(printer: &mut Standard<NoColor<Vec<u8>>>) -> String {
String::from_utf8(printer.get_mut().get_ref().to_owned()).unwrap()
}
#[test]
fn reports_match() {
let matcher = RegexMatcher::new("Sherlock").unwrap();
let mut printer = StandardBuilder::new()
.build(NoColor::new(vec![]));
let mut printer = StandardBuilder::new().build(NoColor::new(vec![]));
let mut sink = printer.sink(&matcher);
SearcherBuilder::new()
.line_number(false)
@@ -1620,8 +1588,7 @@ and exhibited clearly, with a label attached.\
assert!(sink.has_match());
let matcher = RegexMatcher::new("zzzzz").unwrap();
let mut printer = StandardBuilder::new()
.build(NoColor::new(vec![]));
let mut printer = StandardBuilder::new().build(NoColor::new(vec![]));
let mut sink = printer.sink(&matcher);
SearcherBuilder::new()
.line_number(false)
@@ -1636,8 +1603,7 @@ and exhibited clearly, with a label attached.\
use grep_searcher::BinaryDetection;
let matcher = RegexMatcher::new("Sherlock").unwrap();
let mut printer = StandardBuilder::new()
.build(NoColor::new(vec![]));
let mut printer = StandardBuilder::new().build(NoColor::new(vec![]));
let mut sink = printer.sink(&matcher);
SearcherBuilder::new()
.line_number(false)
@@ -1647,8 +1613,7 @@ and exhibited clearly, with a label attached.\
assert!(sink.binary_byte_offset().is_none());
let matcher = RegexMatcher::new(".+").unwrap();
let mut printer = StandardBuilder::new()
.build(NoColor::new(vec![]));
let mut printer = StandardBuilder::new().build(NoColor::new(vec![]));
let mut sink = printer.sink(&matcher);
SearcherBuilder::new()
.line_number(false)
@@ -1664,9 +1629,8 @@ and exhibited clearly, with a label attached.\
use std::time::Duration;
let matcher = RegexMatcher::new("Sherlock|opposed").unwrap();
let mut printer = StandardBuilder::new()
.stats(true)
.build(NoColor::new(vec![]));
let mut printer =
StandardBuilder::new().stats(true).build(NoColor::new(vec![]));
let stats = {
let mut sink = printer.sink(&matcher);
SearcherBuilder::new()
@@ -1685,7 +1649,6 @@ and exhibited clearly, with a label attached.\
assert_eq!(stats.bytes_printed(), buf.len() as u64);
assert_eq!(stats.matched_lines(), 2);
assert_eq!(stats.matches(), 3);
}
#[test]
@@ -1693,9 +1656,8 @@ and exhibited clearly, with a label attached.\
use std::time::Duration;
let matcher = RegexMatcher::new("Sherlock|opposed").unwrap();
let mut printer = StandardBuilder::new()
.stats(true)
.build(NoColor::new(vec![]));
let mut printer =
StandardBuilder::new().stats(true).build(NoColor::new(vec![]));
let stats = {
let mut sink = printer.sink(&matcher);
SearcherBuilder::new()
@@ -1860,9 +1822,8 @@ and exhibited clearly, with a label attached.
#[test]
fn path() {
let matcher = RegexMatcher::new("Watson").unwrap();
let mut printer = StandardBuilder::new()
.path(false)
.build(NoColor::new(vec![]));
let mut printer =
StandardBuilder::new().path(false).build(NoColor::new(vec![]));
SearcherBuilder::new()
.line_number(true)
.build()
@@ -1963,9 +1924,8 @@ books/sherlockZbut Doctor Watson has to have it taken out for him and dusted,
#[test]
fn heading() {
let matcher = RegexMatcher::new("Watson").unwrap();
let mut printer = StandardBuilder::new()
.heading(true)
.build(NoColor::new(vec![]));
let mut printer =
StandardBuilder::new().heading(true).build(NoColor::new(vec![]));
SearcherBuilder::new()
.line_number(false)
.build()
@@ -1988,9 +1948,8 @@ but Doctor Watson has to have it taken out for him and dusted,
#[test]
fn no_heading() {
let matcher = RegexMatcher::new("Watson").unwrap();
let mut printer = StandardBuilder::new()
.heading(false)
.build(NoColor::new(vec![]));
let mut printer =
StandardBuilder::new().heading(false).build(NoColor::new(vec![]));
SearcherBuilder::new()
.line_number(false)
.build()
@@ -2012,9 +1971,8 @@ sherlock:but Doctor Watson has to have it taken out for him and dusted,
#[test]
fn no_heading_multiple() {
let matcher = RegexMatcher::new("Watson").unwrap();
let mut printer = StandardBuilder::new()
.heading(false)
.build(NoColor::new(vec![]));
let mut printer =
StandardBuilder::new().heading(false).build(NoColor::new(vec![]));
SearcherBuilder::new()
.line_number(false)
.build()
@@ -2049,9 +2007,8 @@ sherlock:be, to a very large extent, the result of luck. Sherlock Holmes
#[test]
fn heading_multiple() {
let matcher = RegexMatcher::new("Watson").unwrap();
let mut printer = StandardBuilder::new()
.heading(true)
.build(NoColor::new(vec![]));
let mut printer =
StandardBuilder::new().heading(true).build(NoColor::new(vec![]));
SearcherBuilder::new()
.line_number(false)
.build()
@@ -2161,8 +2118,7 @@ Watson
#[test]
fn line_number() {
let matcher = RegexMatcher::new("Watson").unwrap();
let mut printer = StandardBuilder::new()
.build(NoColor::new(vec![]));
let mut printer = StandardBuilder::new().build(NoColor::new(vec![]));
SearcherBuilder::new()
.line_number(true)
.build()
@@ -2184,8 +2140,7 @@ Watson
#[test]
fn line_number_multi_line() {
let matcher = RegexMatcher::new("(?s)Watson.+Watson").unwrap();
let mut printer = StandardBuilder::new()
.build(NoColor::new(vec![]));
let mut printer = StandardBuilder::new().build(NoColor::new(vec![]));
SearcherBuilder::new()
.line_number(true)
.multi_line(true)
@@ -2211,9 +2166,8 @@ Watson
#[test]
fn column_number() {
let matcher = RegexMatcher::new("Watson").unwrap();
let mut printer = StandardBuilder::new()
.column(true)
.build(NoColor::new(vec![]));
let mut printer =
StandardBuilder::new().column(true).build(NoColor::new(vec![]));
SearcherBuilder::new()
.line_number(false)
.build()
@@ -2235,9 +2189,8 @@ Watson
#[test]
fn column_number_multi_line() {
let matcher = RegexMatcher::new("(?s)Watson.+Watson").unwrap();
let mut printer = StandardBuilder::new()
.column(true)
.build(NoColor::new(vec![]));
let mut printer =
StandardBuilder::new().column(true).build(NoColor::new(vec![]));
SearcherBuilder::new()
.line_number(false)
.multi_line(true)
@@ -2440,9 +2393,8 @@ and exhibited clearly, with a label attached.
#[test]
fn max_columns_with_count_preview_two_matches() {
let matcher = RegexMatcher::new(
"exhibited|dusted|has to have it",
).unwrap();
let matcher =
RegexMatcher::new("exhibited|dusted|has to have it").unwrap();
let mut printer = StandardBuilder::new()
.stats(true)
.max_columns(Some(46))
@@ -2493,9 +2445,9 @@ but Doctor Watson has to have it taken out for him and dusted,
#[test]
fn max_columns_multi_line_preview() {
let matcher = RegexMatcher::new(
"(?s)clew|cigar ash.+have it|exhibited",
).unwrap();
let matcher =
RegexMatcher::new("(?s)clew|cigar ash.+have it|exhibited")
.unwrap();
let mut printer = StandardBuilder::new()
.stats(true)
.max_columns(Some(46))
@@ -2673,9 +2625,8 @@ For the Doctor Watsons of this world, as opposed to the Sherlock
#[test]
fn max_matches_multi_line2() {
let matcher = RegexMatcher::new(
r"(?s)Watson.+?(Holmeses|clearly)"
).unwrap();
let matcher =
RegexMatcher::new(r"(?s)Watson.+?(Holmeses|clearly)").unwrap();
let mut printer = StandardBuilder::new()
.max_matches(Some(1))
.build(NoColor::new(vec![]));
@@ -2726,9 +2677,8 @@ Holmeses, success in the province of detective work must always
#[test]
fn only_matching_multi_line1() {
let matcher = RegexMatcher::new(
r"(?s:.{0})(Doctor Watsons|Sherlock)"
).unwrap();
let matcher =
RegexMatcher::new(r"(?s:.{0})(Doctor Watsons|Sherlock)").unwrap();
let mut printer = StandardBuilder::new()
.only_matching(true)
.column(true)
@@ -2755,9 +2705,8 @@ Holmeses, success in the province of detective work must always
#[test]
fn only_matching_multi_line2() {
let matcher = RegexMatcher::new(
r"(?s)Watson.+?(Holmeses|clearly)"
).unwrap();
let matcher =
RegexMatcher::new(r"(?s)Watson.+?(Holmeses|clearly)").unwrap();
let mut printer = StandardBuilder::new()
.only_matching(true)
.column(true)
@@ -2844,9 +2793,8 @@ Holmeses, success in the province of detective work must always
// can match across multiple lines without actually doing so. This is
// so we can test multi-line handling in the case of a match on only
// one line.
let matcher = RegexMatcher::new(
r"(?s:.{0})(Doctor Watsons|Sherlock)"
).unwrap();
let matcher =
RegexMatcher::new(r"(?s:.{0})(Doctor Watsons|Sherlock)").unwrap();
let mut printer = StandardBuilder::new()
.only_matching(true)
.max_columns(Some(10))
@@ -2878,9 +2826,8 @@ Holmeses, success in the province of detective work must always
// can match across multiple lines without actually doing so. This is
// so we can test multi-line handling in the case of a match on only
// one line.
let matcher = RegexMatcher::new(
r"(?s:.{0})(Doctor Watsons|Sherlock)"
).unwrap();
let matcher =
RegexMatcher::new(r"(?s:.{0})(Doctor Watsons|Sherlock)").unwrap();
let mut printer = StandardBuilder::new()
.only_matching(true)
.max_columns(Some(10))
@@ -2909,9 +2856,8 @@ Holmeses, success in the province of detective work must always
#[test]
fn only_matching_max_columns_multi_line2() {
let matcher = RegexMatcher::new(
r"(?s)Watson.+?(Holmeses|clearly)"
).unwrap();
let matcher =
RegexMatcher::new(r"(?s)Watson.+?(Holmeses|clearly)").unwrap();
let mut printer = StandardBuilder::new()
.only_matching(true)
.max_columns(Some(50))
@@ -2940,9 +2886,8 @@ Holmeses, success in the province of detective work must always
#[test]
fn only_matching_max_columns_preview_multi_line2() {
let matcher = RegexMatcher::new(
r"(?s)Watson.+?(Holmeses|clearly)"
).unwrap();
let matcher =
RegexMatcher::new(r"(?s)Watson.+?(Holmeses|clearly)").unwrap();
let mut printer = StandardBuilder::new()
.only_matching(true)
.max_columns(Some(50))
@@ -2998,9 +2943,8 @@ Holmeses, success in the province of detective work must always
#[test]
fn per_match_multi_line1() {
let matcher = RegexMatcher::new(
r"(?s:.{0})(Doctor Watsons|Sherlock)"
).unwrap();
let matcher =
RegexMatcher::new(r"(?s:.{0})(Doctor Watsons|Sherlock)").unwrap();
let mut printer = StandardBuilder::new()
.per_match(true)
.column(true)
@@ -3027,9 +2971,8 @@ Holmeses, success in the province of detective work must always
#[test]
fn per_match_multi_line2() {
let matcher = RegexMatcher::new(
r"(?s)Watson.+?(Holmeses|clearly)",
).unwrap();
let matcher =
RegexMatcher::new(r"(?s)Watson.+?(Holmeses|clearly)").unwrap();
let mut printer = StandardBuilder::new()
.per_match(true)
.column(true)
@@ -3057,9 +3000,8 @@ Holmeses, success in the province of detective work must always
#[test]
fn per_match_multi_line3() {
let matcher = RegexMatcher::new(
r"(?s)Watson.+?Holmeses|always.+?be",
).unwrap();
let matcher =
RegexMatcher::new(r"(?s)Watson.+?Holmeses|always.+?be").unwrap();
let mut printer = StandardBuilder::new()
.per_match(true)
.column(true)
@@ -3194,9 +3136,8 @@ Holmeses, success in the province of detective work must always
#[test]
fn replacement_max_columns_preview2() {
let matcher = RegexMatcher::new(
"exhibited|dusted|has to have it",
).unwrap();
let matcher =
RegexMatcher::new("exhibited|dusted|has to have it").unwrap();
let mut printer = StandardBuilder::new()
.max_columns(Some(43))
.max_columns_preview(true)
@@ -3277,8 +3218,7 @@ and xxx clearly, with a label attached.
#[test]
fn invert() {
let matcher = RegexMatcher::new(r"Sherlock").unwrap();
let mut printer = StandardBuilder::new()
.build(NoColor::new(vec![]));
let mut printer = StandardBuilder::new().build(NoColor::new(vec![]));
SearcherBuilder::new()
.line_number(true)
.invert_match(true)
@@ -3303,8 +3243,7 @@ and xxx clearly, with a label attached.
#[test]
fn invert_multi_line() {
let matcher = RegexMatcher::new(r"(?s:.{0})Sherlock").unwrap();
let mut printer = StandardBuilder::new()
.build(NoColor::new(vec![]));
let mut printer = StandardBuilder::new().build(NoColor::new(vec![]));
SearcherBuilder::new()
.multi_line(true)
.line_number(true)
@@ -3330,8 +3269,7 @@ and xxx clearly, with a label attached.
#[test]
fn invert_context() {
let matcher = RegexMatcher::new(r"Sherlock").unwrap();
let mut printer = StandardBuilder::new()
.build(NoColor::new(vec![]));
let mut printer = StandardBuilder::new().build(NoColor::new(vec![]));
SearcherBuilder::new()
.line_number(true)
.invert_match(true)
@@ -3360,8 +3298,7 @@ and xxx clearly, with a label attached.
#[test]
fn invert_context_multi_line() {
let matcher = RegexMatcher::new(r"(?s:.{0})Sherlock").unwrap();
let mut printer = StandardBuilder::new()
.build(NoColor::new(vec![]));
let mut printer = StandardBuilder::new().build(NoColor::new(vec![]));
SearcherBuilder::new()
.multi_line(true)
.line_number(true)

View File

@@ -34,8 +34,8 @@ impl<'a> Add<&'a Stats> for Stats {
Stats {
elapsed: NiceDuration(self.elapsed.0 + rhs.elapsed.0),
searches: self.searches + rhs.searches,
searches_with_match:
self.searches_with_match + rhs.searches_with_match,
searches_with_match: self.searches_with_match
+ rhs.searches_with_match,
bytes_searched: self.bytes_searched + rhs.bytes_searched,
bytes_printed: self.bytes_printed + rhs.bytes_printed,
matched_lines: self.matched_lines + rhs.matched_lines,

View File

@@ -168,10 +168,7 @@ impl SummaryBuilder {
///
/// This is a convenience routine for
/// `SummaryBuilder::build(termcolor::NoColor::new(wtr))`.
pub fn build_no_color<W: io::Write>(
&self,
wtr: W,
) -> Summary<NoColor<W>> {
pub fn build_no_color<W: io::Write>(&self, wtr: W) -> Summary<NoColor<W>> {
self.build(NoColor::new(wtr))
}
@@ -204,10 +201,7 @@ impl SummaryBuilder {
/// builder.
///
/// The default color specifications provide no styling.
pub fn color_specs(
&mut self,
specs: ColorSpecs,
) -> &mut SummaryBuilder {
pub fn color_specs(&mut self, specs: ColorSpecs) -> &mut SummaryBuilder {
self.config.colors = specs;
self
}
@@ -281,10 +275,7 @@ impl SummaryBuilder {
/// `CountMatches` modes.
///
/// By default, this is set to `:`.
pub fn separator_field(
&mut self,
sep: Vec<u8>,
) -> &mut SummaryBuilder {
pub fn separator_field(&mut self, sep: Vec<u8>) -> &mut SummaryBuilder {
self.config.separator_field = Arc::new(sep);
self
}
@@ -300,10 +291,7 @@ impl SummaryBuilder {
/// `\`.
///
/// This is disabled by default.
pub fn separator_path(
&mut self,
sep: Option<u8>,
) -> &mut SummaryBuilder {
pub fn separator_path(&mut self, sep: Option<u8>) -> &mut SummaryBuilder {
self.config.separator_path = sep;
self
}
@@ -382,12 +370,11 @@ impl<W: WriteColor> Summary<W> {
&'s mut self,
matcher: M,
) -> SummarySink<'static, 's, M, W> {
let stats =
if self.config.stats || self.config.kind.requires_stats() {
Some(Stats::new())
} else {
None
};
let stats = if self.config.stats || self.config.kind.requires_stats() {
Some(Stats::new())
} else {
None
};
SummarySink {
matcher: matcher,
summary: self,
@@ -408,20 +395,22 @@ impl<W: WriteColor> Summary<W> {
matcher: M,
path: &'p P,
) -> SummarySink<'p, 's, M, W>
where M: Matcher,
P: ?Sized + AsRef<Path>,
where
M: Matcher,
P: ?Sized + AsRef<Path>,
{
if !self.config.path && !self.config.kind.requires_path() {
return self.sink(matcher);
}
let stats =
if self.config.stats || self.config.kind.requires_stats() {
Some(Stats::new())
} else {
None
};
let stats = if self.config.stats || self.config.kind.requires_stats() {
Some(Stats::new())
} else {
None
};
let ppath = PrinterPath::with_separator(
path.as_ref(), self.config.separator_path);
path.as_ref(),
self.config.separator_path,
);
SummarySink {
matcher: matcher,
summary: self,
@@ -596,10 +585,12 @@ impl<'p, 's, M: Matcher, W: WriteColor> Sink for SummarySink<'p, 's, M, W> {
self.match_count += 1;
if let Some(ref mut stats) = self.stats {
let mut match_count = 0;
self.matcher.find_iter(mat.bytes(), |_| {
match_count += 1;
true
}).map_err(io::Error::error_message)?;
self.matcher
.find_iter(mat.bytes(), |_| {
match_count += 1;
true
})
.map_err(io::Error::error_message)?;
stats.add_matches(match_count);
stats.add_matched_lines(mat.lines().count() as u64);
} else if self.summary.config.kind.quit_early() {
@@ -608,10 +599,7 @@ impl<'p, 's, M: Matcher, W: WriteColor> Sink for SummarySink<'p, 's, M, W> {
Ok(!self.should_quit())
}
fn begin(
&mut self,
_searcher: &Searcher,
) -> Result<bool, io::Error> {
fn begin(&mut self, _searcher: &Searcher) -> Result<bool, io::Error> {
if self.path.is_none() && self.summary.config.kind.requires_path() {
return Err(io::Error::error_message(format!(
"output kind {:?} requires a file path",
@@ -674,8 +662,7 @@ impl<'p, 's, M: Matcher, W: WriteColor> Sink for SummarySink<'p, 's, M, W> {
}
let show_count =
!self.summary.config.exclude_zero
|| self.match_count > 0;
!self.summary.config.exclude_zero || self.match_count > 0;
match self.summary.config.kind {
SummaryKind::Count => {
if show_count {
@@ -686,7 +673,8 @@ impl<'p, 's, M: Matcher, W: WriteColor> Sink for SummarySink<'p, 's, M, W> {
}
SummaryKind::CountMatches => {
if show_count {
let stats = self.stats
let stats = self
.stats
.as_ref()
.expect("CountMatches should enable stats tracking");
self.write_path_field()?;
@@ -716,7 +704,7 @@ mod tests {
use grep_searcher::SearcherBuilder;
use termcolor::NoColor;
use super::{Summary, SummaryKind, SummaryBuilder};
use super::{Summary, SummaryBuilder, SummaryKind};
const SHERLOCK: &'static [u8] = b"\
For the Doctor Watsons of this world, as opposed to the Sherlock
@@ -727,45 +715,41 @@ but Doctor Watson has to have it taken out for him and dusted,
and exhibited clearly, with a label attached.
";
fn printer_contents(
printer: &mut Summary<NoColor<Vec<u8>>>,
) -> String {
fn printer_contents(printer: &mut Summary<NoColor<Vec<u8>>>) -> String {
String::from_utf8(printer.get_mut().get_ref().to_owned()).unwrap()
}
#[test]
fn path_with_match_error() {
let matcher = RegexMatcher::new(
r"Watson"
).unwrap();
let matcher = RegexMatcher::new(r"Watson").unwrap();
let mut printer = SummaryBuilder::new()
.kind(SummaryKind::PathWithMatch)
.build_no_color(vec![]);
let res = SearcherBuilder::new()
.build()
.search_reader(&matcher, SHERLOCK, printer.sink(&matcher));
let res = SearcherBuilder::new().build().search_reader(
&matcher,
SHERLOCK,
printer.sink(&matcher),
);
assert!(res.is_err());
}
#[test]
fn path_without_match_error() {
let matcher = RegexMatcher::new(
r"Watson"
).unwrap();
let matcher = RegexMatcher::new(r"Watson").unwrap();
let mut printer = SummaryBuilder::new()
.kind(SummaryKind::PathWithoutMatch)
.build_no_color(vec![]);
let res = SearcherBuilder::new()
.build()
.search_reader(&matcher, SHERLOCK, printer.sink(&matcher));
let res = SearcherBuilder::new().build().search_reader(
&matcher,
SHERLOCK,
printer.sink(&matcher),
);
assert!(res.is_err());
}
#[test]
fn count_no_path() {
let matcher = RegexMatcher::new(
r"Watson"
).unwrap();
let matcher = RegexMatcher::new(r"Watson").unwrap();
let mut printer = SummaryBuilder::new()
.kind(SummaryKind::Count)
.build_no_color(vec![]);
@@ -780,9 +764,7 @@ and exhibited clearly, with a label attached.
#[test]
fn count_no_path_even_with_path() {
let matcher = RegexMatcher::new(
r"Watson"
).unwrap();
let matcher = RegexMatcher::new(r"Watson").unwrap();
let mut printer = SummaryBuilder::new()
.kind(SummaryKind::Count)
.path(false)
@@ -802,9 +784,7 @@ and exhibited clearly, with a label attached.
#[test]
fn count_path() {
let matcher = RegexMatcher::new(
r"Watson"
).unwrap();
let matcher = RegexMatcher::new(r"Watson").unwrap();
let mut printer = SummaryBuilder::new()
.kind(SummaryKind::Count)
.build_no_color(vec![]);
@@ -823,9 +803,7 @@ and exhibited clearly, with a label attached.
#[test]
fn count_path_with_zero() {
let matcher = RegexMatcher::new(
r"NO MATCH"
).unwrap();
let matcher = RegexMatcher::new(r"NO MATCH").unwrap();
let mut printer = SummaryBuilder::new()
.kind(SummaryKind::Count)
.exclude_zero(false)
@@ -845,9 +823,7 @@ and exhibited clearly, with a label attached.
#[test]
fn count_path_without_zero() {
let matcher = RegexMatcher::new(
r"NO MATCH"
).unwrap();
let matcher = RegexMatcher::new(r"NO MATCH").unwrap();
let mut printer = SummaryBuilder::new()
.kind(SummaryKind::Count)
.exclude_zero(true)
@@ -867,9 +843,7 @@ and exhibited clearly, with a label attached.
#[test]
fn count_path_field_separator() {
let matcher = RegexMatcher::new(
r"Watson"
).unwrap();
let matcher = RegexMatcher::new(r"Watson").unwrap();
let mut printer = SummaryBuilder::new()
.kind(SummaryKind::Count)
.separator_field(b"ZZ".to_vec())
@@ -889,9 +863,7 @@ and exhibited clearly, with a label attached.
#[test]
fn count_path_terminator() {
let matcher = RegexMatcher::new(
r"Watson"
).unwrap();
let matcher = RegexMatcher::new(r"Watson").unwrap();
let mut printer = SummaryBuilder::new()
.kind(SummaryKind::Count)
.path_terminator(Some(b'\x00'))
@@ -911,9 +883,7 @@ and exhibited clearly, with a label attached.
#[test]
fn count_path_separator() {
let matcher = RegexMatcher::new(
r"Watson"
).unwrap();
let matcher = RegexMatcher::new(r"Watson").unwrap();
let mut printer = SummaryBuilder::new()
.kind(SummaryKind::Count)
.separator_path(Some(b'\\'))
@@ -933,9 +903,7 @@ and exhibited clearly, with a label attached.
#[test]
fn count_max_matches() {
let matcher = RegexMatcher::new(
r"Watson"
).unwrap();
let matcher = RegexMatcher::new(r"Watson").unwrap();
let mut printer = SummaryBuilder::new()
.kind(SummaryKind::Count)
.max_matches(Some(1))
@@ -951,9 +919,7 @@ and exhibited clearly, with a label attached.
#[test]
fn count_matches() {
let matcher = RegexMatcher::new(
r"Watson|Sherlock"
).unwrap();
let matcher = RegexMatcher::new(r"Watson|Sherlock").unwrap();
let mut printer = SummaryBuilder::new()
.kind(SummaryKind::CountMatches)
.build_no_color(vec![]);
@@ -972,9 +938,7 @@ and exhibited clearly, with a label attached.
#[test]
fn path_with_match_found() {
let matcher = RegexMatcher::new(
r"Watson"
).unwrap();
let matcher = RegexMatcher::new(r"Watson").unwrap();
let mut printer = SummaryBuilder::new()
.kind(SummaryKind::PathWithMatch)
.build_no_color(vec![]);
@@ -993,9 +957,7 @@ and exhibited clearly, with a label attached.
#[test]
fn path_with_match_not_found() {
let matcher = RegexMatcher::new(
r"ZZZZZZZZ"
).unwrap();
let matcher = RegexMatcher::new(r"ZZZZZZZZ").unwrap();
let mut printer = SummaryBuilder::new()
.kind(SummaryKind::PathWithMatch)
.build_no_color(vec![]);
@@ -1012,12 +974,9 @@ and exhibited clearly, with a label attached.
assert_eq_printed!("", got);
}
#[test]
fn path_without_match_found() {
let matcher = RegexMatcher::new(
r"ZZZZZZZZZ"
).unwrap();
let matcher = RegexMatcher::new(r"ZZZZZZZZZ").unwrap();
let mut printer = SummaryBuilder::new()
.kind(SummaryKind::PathWithoutMatch)
.build_no_color(vec![]);
@@ -1036,9 +995,7 @@ and exhibited clearly, with a label attached.
#[test]
fn path_without_match_not_found() {
let matcher = RegexMatcher::new(
r"Watson"
).unwrap();
let matcher = RegexMatcher::new(r"Watson").unwrap();
let mut printer = SummaryBuilder::new()
.kind(SummaryKind::PathWithoutMatch)
.build_no_color(vec![]);
@@ -1057,9 +1014,7 @@ and exhibited clearly, with a label attached.
#[test]
fn quiet() {
let matcher = RegexMatcher::new(
r"Watson|Sherlock"
).unwrap();
let matcher = RegexMatcher::new(r"Watson|Sherlock").unwrap();
let mut printer = SummaryBuilder::new()
.kind(SummaryKind::Quiet)
.build_no_color(vec![]);
@@ -1081,9 +1036,7 @@ and exhibited clearly, with a label attached.
#[test]
fn quiet_with_stats() {
let matcher = RegexMatcher::new(
r"Watson|Sherlock"
).unwrap();
let matcher = RegexMatcher::new(r"Watson|Sherlock").unwrap();
let mut printer = SummaryBuilder::new()
.kind(SummaryKind::Quiet)
.stats(true)

View File

@@ -7,8 +7,7 @@ use std::time;
use bstr::{ByteSlice, ByteVec};
use grep_matcher::{Captures, LineTerminator, Match, Matcher};
use grep_searcher::{
LineIter,
SinkError, SinkContext, SinkContextKind, SinkMatch,
LineIter, SinkContext, SinkContextKind, SinkError, SinkMatch,
};
#[cfg(feature = "serde1")]
use serde::{Serialize, Serializer};
@@ -58,19 +57,13 @@ impl<M: Matcher> Replacer<M> {
replacement: &[u8],
) -> io::Result<()> {
{
let &mut Space {
ref mut dst,
ref mut caps,
ref mut matches,
} = self.allocate(matcher)?;
let &mut Space { ref mut dst, ref mut caps, ref mut matches } =
self.allocate(matcher)?;
dst.clear();
matches.clear();
matcher.replace_with_captures(
subject,
caps,
dst,
|caps, dst| {
matcher
.replace_with_captures(subject, caps, dst, |caps, dst| {
let start = dst.len();
caps.interpolate(
|name| matcher.capture_index(name),
@@ -81,8 +74,8 @@ impl<M: Matcher> Replacer<M> {
let end = dst.len();
matches.push(Match::new(start, end));
true
},
).map_err(io::Error::error_message)?;
})
.map_err(io::Error::error_message)?;
}
Ok(())
}
@@ -122,14 +115,10 @@ impl<M: Matcher> Replacer<M> {
/// matcher fails.
fn allocate(&mut self, matcher: &M) -> io::Result<&mut Space<M>> {
if self.space.is_none() {
let caps = matcher
.new_captures()
.map_err(io::Error::error_message)?;
self.space = Some(Space {
caps: caps,
dst: vec![],
matches: vec![],
});
let caps =
matcher.new_captures().map_err(io::Error::error_message)?;
self.space =
Some(Space { caps: caps, dst: vec![], matches: vec![] });
}
Ok(self.space.as_mut().unwrap())
}
@@ -176,9 +165,8 @@ impl<'a> Sunk<'a> {
original_matches: &'a [Match],
replacement: Option<(&'a [u8], &'a [Match])>,
) -> Sunk<'a> {
let (bytes, matches) = replacement.unwrap_or_else(|| {
(sunk.bytes(), original_matches)
});
let (bytes, matches) =
replacement.unwrap_or_else(|| (sunk.bytes(), original_matches));
Sunk {
bytes: bytes,
absolute_byte_offset: sunk.absolute_byte_offset(),
@@ -195,9 +183,8 @@ impl<'a> Sunk<'a> {
original_matches: &'a [Match],
replacement: Option<(&'a [u8], &'a [Match])>,
) -> Sunk<'a> {
let (bytes, matches) = replacement.unwrap_or_else(|| {
(sunk.bytes(), original_matches)
});
let (bytes, matches) =
replacement.unwrap_or_else(|| (sunk.bytes(), original_matches));
Sunk {
bytes: bytes,
absolute_byte_offset: sunk.absolute_byte_offset(),
@@ -289,13 +276,17 @@ impl<'a> PrinterPath<'a> {
/// path separators that are both replaced by `new_sep`. In all other
/// environments, only `/` is treated as a path separator.
fn replace_separator(&mut self, new_sep: u8) {
let transformed_path: Vec<u8> = self.0.bytes().map(|b| {
if b == b'/' || (cfg!(windows) && b == b'\\') {
new_sep
} else {
b
}
}).collect();
let transformed_path: Vec<u8> = self
.0
.bytes()
.map(|b| {
if b == b'/' || (cfg!(windows) && b == b'\\') {
new_sep
} else {
b
}
})
.collect();
self.0 = Cow::Owned(transformed_path);
}