1
0
mirror of https://github.com/BurntSushi/ripgrep.git synced 2025-04-02 20:45:38 +02:00

cleanup: replace try! with ?

This commit is contained in:
Balaji Sivaraman 2018-01-01 19:52:35 +05:30 committed by Andrew Gallant
parent ba1023e1e4
commit b6177f0459
16 changed files with 160 additions and 162 deletions

View File

@ -36,7 +36,7 @@ This example shows how to match a single glob against a single file path.
```rust
use globset::Glob;
let glob = try!(Glob::new("*.rs")).compile_matcher();
let glob = Glob::new("*.rs")?.compile_matcher();
assert!(glob.is_match("foo.rs"));
assert!(glob.is_match("foo/bar.rs"));
@ -51,8 +51,8 @@ semantics. In this example, we prevent wildcards from matching path separators.
```rust
use globset::GlobBuilder;
let glob = try!(GlobBuilder::new("*.rs")
.literal_separator(true).build()).compile_matcher();
let glob = GlobBuilder::new("*.rs")
.literal_separator(true).build()?.compile_matcher();
assert!(glob.is_match("foo.rs"));
assert!(!glob.is_match("foo/bar.rs")); // no longer matches
@ -69,10 +69,10 @@ use globset::{Glob, GlobSetBuilder};
let mut builder = GlobSetBuilder::new();
// A GlobBuilder can be used to configure each glob's match semantics
// independently.
builder.add(try!(Glob::new("*.rs")));
builder.add(try!(Glob::new("src/lib.rs")));
builder.add(try!(Glob::new("src/**/foo.rs")));
let set = try!(builder.build());
builder.add(Glob::new("*.rs")?);
builder.add(Glob::new("src/lib.rs")?);
builder.add(Glob::new("src/**/foo.rs")?);
let set = builder.build()?;
assert_eq!(set.matches("src/bar/baz/foo.rs"), vec![0, 2]);
```

View File

@ -550,7 +550,7 @@ impl<'a> GlobBuilder<'a> {
prev: None,
cur: None,
};
try!(p.parse());
p.parse()?;
if p.stack.is_empty() {
Err(Error {
glob: Some(self.glob.to_string()),
@ -720,18 +720,18 @@ impl<'a> Parser<'a> {
fn parse(&mut self) -> Result<(), Error> {
while let Some(c) = self.bump() {
match c {
'?' => try!(self.push_token(Token::Any)),
'*' => try!(self.parse_star()),
'[' => try!(self.parse_class()),
'{' => try!(self.push_alternate()),
'}' => try!(self.pop_alternate()),
',' => try!(self.parse_comma()),
'?' => self.push_token(Token::Any)?,
'*' => self.parse_star()?,
'[' => self.parse_class()?,
'{' => self.push_alternate()?,
'}' => self.pop_alternate()?,
',' => self.parse_comma()?,
c => {
if is_separator(c) {
// Normalize all patterns to use / as a separator.
try!(self.push_token(Token::Literal('/')))
self.push_token(Token::Literal('/'))?
} else {
try!(self.push_token(Token::Literal(c)))
self.push_token(Token::Literal(c))?
}
}
}
@ -789,19 +789,19 @@ impl<'a> Parser<'a> {
fn parse_star(&mut self) -> Result<(), Error> {
let prev = self.prev;
if self.chars.peek() != Some(&'*') {
try!(self.push_token(Token::ZeroOrMore));
self.push_token(Token::ZeroOrMore)?;
return Ok(());
}
assert!(self.bump() == Some('*'));
if !try!(self.have_tokens()) {
try!(self.push_token(Token::RecursivePrefix));
if !self.have_tokens()? {
self.push_token(Token::RecursivePrefix)?;
let next = self.bump();
if !next.map(is_separator).unwrap_or(true) {
return Err(self.error(ErrorKind::InvalidRecursive));
}
return Ok(());
}
try!(self.pop_token());
self.pop_token()?;
if !prev.map(is_separator).unwrap_or(false) {
if self.stack.len() <= 1
|| (prev != Some(',') && prev != Some('{')) {
@ -873,7 +873,7 @@ impl<'a> Parser<'a> {
// invariant: in_range is only set when there is
// already at least one character seen.
let r = ranges.last_mut().unwrap();
try!(add_to_last_range(&self.glob, r, '-'));
add_to_last_range(&self.glob, r, '-')?;
in_range = false;
} else {
assert!(!ranges.is_empty());
@ -884,8 +884,8 @@ impl<'a> Parser<'a> {
if in_range {
// invariant: in_range is only set when there is
// already at least one character seen.
try!(add_to_last_range(
&self.glob, ranges.last_mut().unwrap(), c));
add_to_last_range(
&self.glob, ranges.last_mut().unwrap(), c)?;
} else {
ranges.push((c, c));
}

View File

@ -22,7 +22,7 @@ This example shows how to match a single glob against a single file path.
# fn example() -> Result<(), globset::Error> {
use globset::Glob;
let glob = try!(Glob::new("*.rs")).compile_matcher();
let glob = Glob::new("*.rs")?.compile_matcher();
assert!(glob.is_match("foo.rs"));
assert!(glob.is_match("foo/bar.rs"));
@ -39,8 +39,8 @@ semantics. In this example, we prevent wildcards from matching path separators.
# fn example() -> Result<(), globset::Error> {
use globset::GlobBuilder;
let glob = try!(GlobBuilder::new("*.rs")
.literal_separator(true).build()).compile_matcher();
let glob = GlobBuilder::new("*.rs")
.literal_separator(true).build()?.compile_matcher();
assert!(glob.is_match("foo.rs"));
assert!(!glob.is_match("foo/bar.rs")); // no longer matches
@ -59,10 +59,10 @@ use globset::{Glob, GlobSetBuilder};
let mut builder = GlobSetBuilder::new();
// A GlobBuilder can be used to configure each glob's match semantics
// independently.
builder.add(try!(Glob::new("*.rs")));
builder.add(try!(Glob::new("src/lib.rs")));
builder.add(try!(Glob::new("src/**/foo.rs")));
let set = try!(builder.build());
builder.add(Glob::new("*.rs")?);
builder.add(Glob::new("src/lib.rs")?);
builder.add(Glob::new("src/**/foo.rs")?);
let set = builder.build()?;
assert_eq!(set.matches("src/bar/baz/foo.rs"), vec![0, 2]);
# Ok(()) } example().unwrap();
@ -412,8 +412,8 @@ impl GlobSet {
GlobSetMatchStrategy::Suffix(suffixes.suffix()),
GlobSetMatchStrategy::Prefix(prefixes.prefix()),
GlobSetMatchStrategy::RequiredExtension(
try!(required_exts.build())),
GlobSetMatchStrategy::Regex(try!(regexes.regex_set())),
required_exts.build()?),
GlobSetMatchStrategy::Regex(regexes.regex_set()?),
],
})
}
@ -767,7 +767,7 @@ impl MultiStrategyBuilder {
fn regex_set(self) -> Result<RegexSetStrategy, Error> {
Ok(RegexSetStrategy {
matcher: try!(new_regex_set(self.literals)),
matcher: new_regex_set(self.literals)?,
map: self.map,
})
}
@ -792,7 +792,7 @@ impl RequiredExtensionStrategyBuilder {
for (ext, regexes) in self.0.into_iter() {
exts.insert(ext.clone(), vec![]);
for (global_index, regex) in regexes {
let compiled = try!(new_regex(&regex));
let compiled = new_regex(&regex)?;
exts.get_mut(&ext).unwrap().push((global_index, compiled));
}
}

View File

@ -44,25 +44,23 @@ pub fn remove(expr: Expr, byte: u8) -> Result<Expr> {
}
Group { e, i, name } => {
Group {
e: Box::new(try!(remove(*e, byte))),
e: Box::new(remove(*e, byte)?),
i: i,
name: name,
}
}
Repeat { e, r, greedy } => {
Repeat {
e: Box::new(try!(remove(*e, byte))),
e: Box::new(remove(*e, byte)?),
r: r,
greedy: greedy,
}
}
Concat(exprs) => {
Concat(try!(
exprs.into_iter().map(|e| remove(e, byte)).collect()))
Concat(exprs.into_iter().map(|e| remove(e, byte)).collect::<Result<Vec<Expr>>>()?)
}
Alternate(exprs) => {
Alternate(try!(
exprs.into_iter().map(|e| remove(e, byte)).collect()))
Alternate(exprs.into_iter().map(|e| remove(e, byte)).collect::<Result<Vec<Expr>>>()?)
}
e => e,
})

View File

@ -141,11 +141,11 @@ impl GrepBuilder {
/// If there was a problem parsing or compiling the regex with the given
/// options, then an error is returned.
pub fn build(self) -> Result<Grep> {
let expr = try!(self.parse());
let expr = self.parse()?;
let literals = LiteralSets::create(&expr);
let re = try!(self.regex(&expr));
let re = self.regex(&expr)?;
let required = match literals.to_regex_builder() {
Some(builder) => Some(try!(self.regex_build(builder))),
Some(builder) => Some(self.regex_build(builder)?),
None => {
match strip_unicode_word_boundaries(&expr) {
None => None,
@ -186,12 +186,12 @@ impl GrepBuilder {
/// the line terminator.
fn parse(&self) -> Result<syntax::Expr> {
let expr =
try!(syntax::ExprBuilder::new()
.allow_bytes(true)
.unicode(true)
.case_insensitive(try!(self.is_case_insensitive()))
.parse(&self.pattern));
let expr = try!(nonl::remove(expr, self.opts.line_terminator));
syntax::ExprBuilder::new()
.allow_bytes(true)
.unicode(true)
.case_insensitive(self.is_case_insensitive()?)
.parse(&self.pattern)?;
let expr = nonl::remove(expr, self.opts.line_terminator)?;
debug!("regex ast:\n{:#?}", expr);
Ok(expr)
}

View File

@ -322,13 +322,13 @@ impl GitignoreBuilder {
pub fn build(&self) -> Result<Gitignore, Error> {
let nignore = self.globs.iter().filter(|g| !g.is_whitelist()).count();
let nwhite = self.globs.iter().filter(|g| g.is_whitelist()).count();
let set = try!(
let set =
self.builder.build().map_err(|err| {
Error::Glob {
glob: None,
err: err.to_string(),
}
}));
})?;
Ok(Gitignore {
set: set,
root: self.root.clone(),
@ -383,7 +383,7 @@ impl GitignoreBuilder {
gitignore: &str,
) -> Result<&mut GitignoreBuilder, Error> {
for line in gitignore.lines() {
try!(self.add_line(from.clone(), line));
self.add_line(from.clone(), line)?;
}
Ok(self)
}
@ -465,7 +465,7 @@ impl GitignoreBuilder {
if glob.actual.ends_with("/**") {
glob.actual = format!("{}/*", glob.actual);
}
let parsed = try!(
let parsed =
GlobBuilder::new(&glob.actual)
.literal_separator(literal_separator)
.case_insensitive(self.case_insensitive)
@ -475,7 +475,7 @@ impl GitignoreBuilder {
glob: Some(glob.original.clone()),
err: err.kind().to_string(),
}
}));
})?;
self.builder.add(parsed);
self.globs.push(glob);
Ok(self)

View File

@ -124,7 +124,7 @@ impl OverrideBuilder {
///
/// Once a matcher is built, no new globs can be added to it.
pub fn build(&self) -> Result<Override, Error> {
Ok(Override(try!(self.builder.build())))
Ok(Override(self.builder.build()?))
}
/// Add a glob to the set of overrides.
@ -134,7 +134,7 @@ impl OverrideBuilder {
/// namely, `!` at the beginning of a glob will ignore a file. Without `!`,
/// all matches of the glob provided are treated as whitelist matches.
pub fn add(&mut self, glob: &str) -> Result<&mut OverrideBuilder, Error> {
try!(self.builder.add_line(None, glob));
self.builder.add_line(None, glob)?;
Ok(self)
}
@ -144,7 +144,7 @@ impl OverrideBuilder {
pub fn case_insensitive(
&mut self, yes: bool
) -> Result<&mut OverrideBuilder, Error> {
try!(self.builder.case_insensitive(yes));
self.builder.case_insensitive(yes)?;
Ok(self)
}
}

View File

@ -526,7 +526,7 @@ impl TypesBuilder {
}
};
for (iglob, glob) in def.globs.iter().enumerate() {
build_set.add(try!(
build_set.add(
GlobBuilder::new(glob)
.literal_separator(true)
.build()
@ -535,14 +535,14 @@ impl TypesBuilder {
glob: Some(glob.to_string()),
err: err.kind().to_string(),
}
})));
})?);
glob_to_selection.push((isel, iglob));
}
selections.push(selection.clone().map(move |_| def));
}
let set = try!(build_set.build().map_err(|err| {
let set = build_set.build().map_err(|err| {
Error::Glob { glob: None, err: err.to_string() }
}));
})?;
Ok(Types {
defs: defs,
selections: selections,
@ -655,7 +655,7 @@ impl TypesBuilder {
for type_name in types {
let globs = self.types.get(type_name).unwrap().globs.clone();
for glob in globs {
try!(self.add(name, &glob));
self.add(name, &glob)?;
}
}
Ok(())

View File

@ -279,13 +279,13 @@ impl DirEntryRaw {
depth: usize,
ent: &fs::DirEntry,
) -> Result<DirEntryRaw, Error> {
let ty = try!(ent.file_type().map_err(|err| {
let ty = ent.file_type().map_err(|err| {
let err = Error::Io(io::Error::from(err)).with_path(ent.path());
Error::WithDepth {
depth: depth,
err: Box::new(err),
}
}));
})?;
Ok(DirEntryRaw::from_entry_os(depth, ent, ty))
}
@ -322,9 +322,9 @@ impl DirEntryRaw {
#[cfg(not(unix))]
fn from_link(depth: usize, pb: PathBuf) -> Result<DirEntryRaw, Error> {
let md = try!(fs::metadata(&pb).map_err(|err| {
let md = fs::metadata(&pb).map_err(|err| {
Error::Io(err).with_path(&pb)
}));
})?;
Ok(DirEntryRaw {
path: pb,
ty: md.file_type(),
@ -337,9 +337,9 @@ impl DirEntryRaw {
fn from_link(depth: usize, pb: PathBuf) -> Result<DirEntryRaw, Error> {
use std::os::unix::fs::MetadataExt;
let md = try!(fs::metadata(&pb).map_err(|err| {
let md = fs::metadata(&pb).map_err(|err| {
Error::Io(err).with_path(&pb)
}));
})?;
Ok(DirEntryRaw {
path: pb,
ty: md.file_type(),

View File

@ -312,27 +312,27 @@ impl<'a> ArgMatches<'a> {
fn to_args(&self) -> Result<Args> {
let paths = self.paths();
let line_number = self.line_number(&paths);
let mmap = try!(self.mmap(&paths));
let mmap = self.mmap(&paths)?;
let with_filename = self.with_filename(&paths);
let (before_context, after_context) = try!(self.contexts());
let (before_context, after_context) = self.contexts()?;
let quiet = self.is_present("quiet");
let args = Args {
paths: paths,
after_context: after_context,
before_context: before_context,
color_choice: self.color_choice(),
colors: try!(self.color_specs()),
colors: self.color_specs()?,
column: self.column(),
context_separator: self.context_separator(),
count: self.is_present("count"),
encoding: try!(self.encoding()),
encoding: self.encoding()?,
files_with_matches: self.is_present("files-with-matches"),
files_without_matches: self.is_present("files-without-match"),
eol: b'\n',
files: self.is_present("files"),
follow: self.is_present("follow"),
glob_overrides: try!(self.overrides()),
grep: try!(self.grep()),
glob_overrides: self.overrides()?,
grep: self.grep()?,
heading: self.heading(),
hidden: self.hidden(),
ignore_files: self.ignore_files(),
@ -340,10 +340,10 @@ impl<'a> ArgMatches<'a> {
line_number: line_number,
line_number_width: try!(self.usize_of("line-number-width")),
line_per_match: self.is_present("vimgrep"),
max_columns: try!(self.usize_of("max-columns")),
max_count: try!(self.usize_of("max-count")).map(|max| max as u64),
max_filesize: try!(self.max_filesize()),
maxdepth: try!(self.usize_of("maxdepth")),
max_columns: self.usize_of("max-columns")?,
max_count: self.usize_of("max-count")?.map(|max| max as u64),
max_filesize: self.max_filesize()?,
maxdepth: self.usize_of("maxdepth")?,
mmap: mmap,
no_ignore: self.no_ignore(),
no_ignore_parent: self.no_ignore_parent(),
@ -351,16 +351,16 @@ impl<'a> ArgMatches<'a> {
no_messages: self.is_present("no-messages"),
null: self.is_present("null"),
only_matching: self.is_present("only-matching"),
path_separator: try!(self.path_separator()),
path_separator: self.path_separator()?,
quiet: quiet,
quiet_matched: QuietMatched::new(quiet),
replace: self.replace(),
sort_files: self.is_present("sort-files"),
stdout_handle: self.stdout_handle(),
text: self.text(),
threads: try!(self.threads()),
threads: self.threads()?,
type_list: self.is_present("type-list"),
types: try!(self.types()),
types: self.types()?,
with_filename: with_filename,
};
if args.mmap {
@ -424,7 +424,7 @@ impl<'a> ArgMatches<'a> {
/// If any part of the pattern isn't valid UTF-8, then an error is
/// returned.
fn pattern(&self) -> Result<String> {
Ok(try!(self.patterns()).join("|"))
Ok(self.patterns()?.join("|"))
}
/// Get a sequence of all available patterns from the command line.
@ -445,13 +445,13 @@ impl<'a> ArgMatches<'a> {
None => {
if self.values_of_os("file").is_none() {
if let Some(os_pat) = self.value_of_os("PATTERN") {
pats.push(try!(self.os_str_pattern(os_pat)));
pats.push(self.os_str_pattern(os_pat)?);
}
}
}
Some(os_pats) => {
for os_pat in os_pats {
pats.push(try!(self.os_str_pattern(os_pat)));
pats.push(self.os_str_pattern(os_pat)?);
}
}
}
@ -460,12 +460,12 @@ impl<'a> ArgMatches<'a> {
if file == "-" {
let stdin = io::stdin();
for line in stdin.lock().lines() {
pats.push(self.str_pattern(&try!(line)));
pats.push(self.str_pattern(&line?));
}
} else {
let f = try!(fs::File::open(file));
let f = fs::File::open(file)?;
for line in io::BufReader::new(f).lines() {
pats.push(self.str_pattern(&try!(line)));
pats.push(self.str_pattern(&line?));
}
}
}
@ -481,7 +481,7 @@ impl<'a> ArgMatches<'a> {
///
/// If the pattern is not valid UTF-8, then an error is returned.
fn os_str_pattern(&self, pat: &OsStr) -> Result<String> {
let s = try!(pattern_to_str(pat));
let s = pattern_to_str(pat)?;
Ok(self.str_pattern(s))
}
@ -581,8 +581,8 @@ impl<'a> ArgMatches<'a> {
/// `paths` should be a slice of all top-level file paths that ripgrep
/// will need to search.
fn mmap(&self, paths: &[PathBuf]) -> Result<bool> {
let (before, after) = try!(self.contexts());
let enc = try!(self.encoding());
let (before, after) = self.contexts()?;
let enc = self.encoding()?;
Ok(if before > 0 || after > 0 || self.is_present("no-mmap") {
false
} else if self.is_present("mmap") {
@ -671,9 +671,9 @@ impl<'a> ArgMatches<'a> {
/// If there was a problem parsing the values from the user as an integer,
/// then an error is returned.
fn contexts(&self) -> Result<(usize, usize)> {
let after = try!(self.usize_of("after-context")).unwrap_or(0);
let before = try!(self.usize_of("before-context")).unwrap_or(0);
let both = try!(self.usize_of("context")).unwrap_or(0);
let after = self.usize_of("after-context")?.unwrap_or(0);
let before = self.usize_of("before-context")?.unwrap_or(0);
let both = self.usize_of("context")?.unwrap_or(0);
Ok(if both > 0 {
(both, both)
} else {
@ -719,7 +719,7 @@ impl<'a> ArgMatches<'a> {
"match:style:bold".parse().unwrap(),
];
for spec_str in self.values_of_lossy_vec("colors") {
specs.push(try!(spec_str.parse()));
specs.push(spec_str.parse()?);
}
Ok(ColorSpecs::new(&specs))
}
@ -752,7 +752,7 @@ impl<'a> ArgMatches<'a> {
if self.is_present("sort-files") {
return Ok(1);
}
let threads = try!(self.usize_of("threads")).unwrap_or(0);
let threads = self.usize_of("threads")?.unwrap_or(0);
Ok(if threads == 0 {
cmp::min(12, num_cpus::get())
} else {
@ -772,15 +772,15 @@ impl<'a> ArgMatches<'a> {
let casei =
self.is_present("ignore-case")
&& !self.is_present("case-sensitive");
let mut gb = GrepBuilder::new(&try!(self.pattern()))
let mut gb = GrepBuilder::new(&self.pattern()?)
.case_smart(smart)
.case_insensitive(casei)
.line_terminator(b'\n');
if let Some(limit) = try!(self.dfa_size_limit()) {
if let Some(limit) = self.dfa_size_limit()? {
gb = gb.dfa_size_limit(limit);
}
if let Some(limit) = try!(self.regex_size_limit()) {
if let Some(limit) = self.regex_size_limit()? {
gb = gb.size_limit(limit);
}
gb.build().map_err(From::from)
@ -788,17 +788,17 @@ impl<'a> ArgMatches<'a> {
/// Builds the set of glob overrides from the command line flags.
fn overrides(&self) -> Result<Override> {
let mut ovr = OverrideBuilder::new(try!(env::current_dir()));
let mut ovr = OverrideBuilder::new(env::current_dir()?);
for glob in self.values_of_lossy_vec("glob") {
try!(ovr.add(&glob));
ovr.add(&glob)?;
}
// this is smelly. In the long run it might make sense
// to change overridebuilder to be like globsetbuilder
// but this would be a breaking change to the ignore crate
// so it is being shelved for now...
try!(ovr.case_insensitive(true));
ovr.case_insensitive(true)?;
for glob in self.values_of_lossy_vec("iglob") {
try!(ovr.add(&glob));
ovr.add(&glob)?;
}
ovr.build().map_err(From::from)
}
@ -811,7 +811,7 @@ impl<'a> ArgMatches<'a> {
btypes.clear(&ty);
}
for def in self.values_of_lossy_vec("type-add") {
try!(btypes.add_def(&def));
btypes.add_def(&def)?;
}
for ty in self.values_of_lossy_vec("type") {
btypes.select(&ty);
@ -835,12 +835,12 @@ impl<'a> ArgMatches<'a> {
None => return Ok(None)
};
let re = regex::Regex::new("^([0-9]+)([KMG])?$").unwrap();
let caps = try!(
let caps =
re.captures(&arg_value).ok_or_else(|| {
format!("invalid format for {}", arg_name)
}));
})?;
let value = try!(caps[1].parse::<u64>());
let value = caps[1].parse::<u64>()?;
let suffix = caps.get(2).map(|x| x.as_str());
let v_10 = value.checked_mul(1024);
@ -865,13 +865,13 @@ impl<'a> ArgMatches<'a> {
/// Parse the dfa-size-limit argument option into a byte count.
fn dfa_size_limit(&self) -> Result<Option<usize>> {
let r = try!(self.parse_human_readable_size_arg("dfa-size-limit"));
let r = self.parse_human_readable_size_arg("dfa-size-limit")?;
human_readable_to_usize("dfa-size-limit", r)
}
/// Parse the regex-size-limit argument option into a byte count.
fn regex_size_limit(&self) -> Result<Option<usize>> {
let r = try!(self.parse_human_readable_size_arg("regex-size-limit"));
let r = self.parse_human_readable_size_arg("regex-size-limit")?;
human_readable_to_usize("regex-size-limit", r)
}

View File

@ -62,7 +62,7 @@ impl<R: io::Read> BomPeeker<R> {
}
self.bom = Some(Bom { bytes: [0; 3], len: 0 });
let mut buf = [0u8; 3];
let bom_len = try!(read_full(&mut self.rdr, &mut buf));
let bom_len = read_full(&mut self.rdr, &mut buf)?;
self.bom = Some(Bom { bytes: buf, len: bom_len });
Ok(self.bom.unwrap())
}
@ -71,7 +71,7 @@ impl<R: io::Read> BomPeeker<R> {
impl<R: io::Read> io::Read for BomPeeker<R> {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
if self.nread < 3 {
let bom = try!(self.peek_bom());
let bom = self.peek_bom()?;
let bom = bom.as_slice();
if self.nread < bom.len() {
let rest = &bom[self.nread..];
@ -81,7 +81,7 @@ impl<R: io::Read> io::Read for BomPeeker<R> {
return Ok(len);
}
}
let nread = try!(self.rdr.read(buf));
let nread = self.rdr.read(buf)?;
self.nread += nread;
Ok(nread)
}
@ -196,7 +196,7 @@ impl<R: io::Read, B: AsMut<[u8]>> DecodeReader<R, B> {
}
self.pos = 0;
self.buflen +=
try!(self.rdr.read(&mut self.buf.as_mut()[self.buflen..]));
self.rdr.read(&mut self.buf.as_mut()[self.buflen..])?;
Ok(())
}
@ -219,7 +219,7 @@ impl<R: io::Read, B: AsMut<[u8]>> DecodeReader<R, B> {
return Ok(0);
}
if self.pos >= self.buflen {
try!(self.fill());
self.fill()?;
}
let mut nwrite = 0;
loop {
@ -235,7 +235,7 @@ impl<R: io::Read, B: AsMut<[u8]>> DecodeReader<R, B> {
}
// Otherwise, we know that our internal buffer has insufficient
// data to transcode at least one char, so we attempt to refill it.
try!(self.fill());
self.fill()?;
// Quit on EOF.
if self.buflen == 0 {
self.pos = 0;
@ -251,7 +251,7 @@ impl<R: io::Read, B: AsMut<[u8]>> DecodeReader<R, B> {
#[inline(never)] // impacts perf...
fn detect(&mut self) -> io::Result<()> {
let bom = try!(self.rdr.peek_bom());
let bom = self.rdr.peek_bom()?;
self.decoder = bom.decoder();
Ok(())
}
@ -261,7 +261,7 @@ impl<R: io::Read, B: AsMut<[u8]>> io::Read for DecodeReader<R, B> {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
if self.first {
self.first = false;
try!(self.detect());
self.detect()?;
}
if self.decoder.is_none() {
return self.rdr.read(buf);

View File

@ -741,28 +741,28 @@ impl FromStr for Spec {
if pieces.len() <= 1 || pieces.len() > 3 {
return Err(Error::InvalidFormat(s.to_string()));
}
let otype: OutType = try!(pieces[0].parse());
match try!(pieces[1].parse()) {
let otype: OutType = pieces[0].parse()?;
match pieces[1].parse()? {
SpecType::None => Ok(Spec { ty: otype, value: SpecValue::None }),
SpecType::Style => {
if pieces.len() < 3 {
return Err(Error::InvalidFormat(s.to_string()));
}
let style: Style = try!(pieces[2].parse());
let style: Style = pieces[2].parse()?;
Ok(Spec { ty: otype, value: SpecValue::Style(style) })
}
SpecType::Fg => {
if pieces.len() < 3 {
return Err(Error::InvalidFormat(s.to_string()));
}
let color: Color = try!(pieces[2].parse());
let color: Color = pieces[2].parse()?;
Ok(Spec { ty: otype, value: SpecValue::Fg(color) })
}
SpecType::Bg => {
if pieces.len() < 3 {
return Err(Error::InvalidFormat(s.to_string()));
}
let color: Color = try!(pieces[2].parse());
let color: Color = pieces[2].parse()?;
Ok(Spec { ty: otype, value: SpecValue::Bg(color) })
}
}

View File

@ -264,7 +264,7 @@ impl<'a, R: io::Read, W: WriteColor> Searcher<'a, R, W> {
while !self.terminate() {
let upto = self.inp.lastnl;
self.print_after_context(upto);
if !try!(self.fill()) {
if !self.fill()? {
break;
}
while !self.terminate() && self.inp.pos < self.inp.lastnl {
@ -301,7 +301,7 @@ impl<'a, R: io::Read, W: WriteColor> Searcher<'a, R, W> {
}
if self.after_context_remaining > 0 {
if self.last_printed == self.inp.lastnl {
try!(self.fill());
self.fill()?;
}
let upto = self.inp.lastnl;
if upto > 0 {
@ -349,9 +349,9 @@ impl<'a, R: io::Read, W: WriteColor> Searcher<'a, R, W> {
self.count_lines(keep);
self.last_line = 0;
}
let ok = try!(self.inp.fill(&mut self.haystack, keep).map_err(|err| {
let ok = self.inp.fill(&mut self.haystack, keep).map_err(|err| {
Error::from_io(err, &self.path)
}));
})?;
Ok(ok)
}
@ -595,8 +595,8 @@ impl InputBuffer {
let new_len = cmp::max(min_len, self.buf.len() * 2);
self.buf.resize(new_len, 0);
}
let n = try!(rdr.read(
&mut self.buf[self.end..self.end + self.read_size]));
let n = rdr.read(
&mut self.buf[self.end..self.end + self.read_size])?;
if !self.text {
if is_binary(&self.buf[self.end..self.end + n], self.first) {
return Ok(false);

View File

@ -282,7 +282,7 @@ impl Worker {
path: &Path,
file: &File,
) -> Result<u64> {
if try!(file.metadata()).len() == 0 {
if file.metadata()?.len() == 0 {
// Opening a memory map with an empty file results in an error.
// However, this may not actually be an empty file! For example,
// /proc/cpuinfo reports itself as an empty file, but it can
@ -290,7 +290,7 @@ impl Worker {
// regular read calls.
return self.search(printer, path, file);
}
let mmap = unsafe { try!(Mmap::map(file)) };
let mmap = unsafe { Mmap::map(file)? };
let buf = &*mmap;
if buf.len() >= 3 && Encoding::for_bom(buf).is_some() {
// If we have a UTF-16 bom in our memory map, then we need to fall

View File

@ -62,8 +62,8 @@ use std::io::Write;
use termcolor::{Color, ColorChoice, ColorSpec, StandardStream, WriteColor};
let mut stdout = StandardStream::stdout(ColorChoice::Always);
try!(stdout.set_color(ColorSpec::new().set_fg(Some(Color::Green))));
try!(writeln!(&mut stdout, "green text!"));
stdout.set_color(ColorSpec::new().set_fg(Some(Color::Green)))?;
writeln!(&mut stdout, "green text!")?;
```
### Example: using `BufferWriter`
@ -80,7 +80,7 @@ use termcolor::{BufferWriter, Color, ColorChoice, ColorSpec, WriteColor};
let mut bufwtr = BufferWriter::stderr(ColorChoice::Always);
let mut buffer = bufwtr.buffer();
try!(buffer.set_color(ColorSpec::new().set_fg(Some(Color::Green))));
try!(writeln!(&mut buffer, "green text!"));
try!(bufwtr.print(&buffer));
buffer.set_color(ColorSpec::new().set_fg(Some(Color::Green)))?;
writeln!(&mut buffer, "green text!")?;
bufwtr.print(&buffer)?;
```

View File

@ -42,8 +42,8 @@ use std::io::Write;
use termcolor::{Color, ColorChoice, ColorSpec, StandardStream, WriteColor};
let mut stdout = StandardStream::stdout(ColorChoice::Always);
try!(stdout.set_color(ColorSpec::new().set_fg(Some(Color::Green))));
try!(writeln!(&mut stdout, "green text!"));
stdout.set_color(ColorSpec::new().set_fg(Some(Color::Green)))?;
writeln!(&mut stdout, "green text!")?;
# Ok(()) }
```
@ -62,9 +62,9 @@ use termcolor::{BufferWriter, Color, ColorChoice, ColorSpec, WriteColor};
let mut bufwtr = BufferWriter::stderr(ColorChoice::Always);
let mut buffer = bufwtr.buffer();
try!(buffer.set_color(ColorSpec::new().set_fg(Some(Color::Green))));
try!(writeln!(&mut buffer, "green text!"));
try!(bufwtr.print(&buffer));
buffer.set_color(ColorSpec::new().set_fg(Some(Color::Green)))?;
writeln!(&mut buffer, "green text!")?;
bufwtr.print(&buffer)?;
# Ok(()) }
```
*/
@ -486,7 +486,7 @@ impl<W: io::Write> WriteColor for WriterInner<W> {
WriterInner::Ansi(ref mut wtr) => wtr.set_color(spec),
#[cfg(windows)]
WriterInner::Windows { ref mut wtr, ref console } => {
try!(wtr.flush());
wtr.flush()?;
let mut console = console.lock().unwrap();
spec.write_console(&mut *console)
}
@ -499,8 +499,8 @@ impl<W: io::Write> WriteColor for WriterInner<W> {
WriterInner::Ansi(ref mut wtr) => wtr.reset(),
#[cfg(windows)]
WriterInner::Windows { ref mut wtr, ref mut console } => {
try!(wtr.flush());
try!(console.lock().unwrap().reset());
wtr.flush()?;
console.lock().unwrap().reset()?;
Ok(())
}
}
@ -547,7 +547,7 @@ impl<'a, W: io::Write> WriteColor for WriterInnerLock<'a, W> {
WriterInnerLock::Ansi(ref mut wtr) => wtr.set_color(spec),
#[cfg(windows)]
WriterInnerLock::Windows { ref mut wtr, ref mut console } => {
try!(wtr.flush());
wtr.flush()?;
spec.write_console(console)
}
}
@ -560,8 +560,8 @@ impl<'a, W: io::Write> WriteColor for WriterInnerLock<'a, W> {
WriterInnerLock::Ansi(ref mut wtr) => wtr.reset(),
#[cfg(windows)]
WriterInnerLock::Windows { ref mut wtr, ref mut console } => {
try!(wtr.flush());
try!(console.reset());
wtr.flush()?;
console.reset()?;
Ok(())
}
}
@ -689,13 +689,13 @@ impl BufferWriter {
let mut stream = self.stream.wrap(self.stream.get_ref().lock());
if let Some(ref sep) = self.separator {
if self.printed.load(Ordering::SeqCst) {
try!(stream.write_all(sep));
try!(stream.write_all(b"\n"));
stream.write_all(sep)?;
stream.write_all(b"\n")?;
}
}
match buf.0 {
BufferInner::NoColor(ref b) => try!(stream.write_all(&b.0)),
BufferInner::Ansi(ref b) => try!(stream.write_all(&b.0)),
BufferInner::NoColor(ref b) => stream.write_all(&b.0)?,
BufferInner::Ansi(ref b) => stream.write_all(&b.0)?,
#[cfg(windows)]
BufferInner::Windows(ref b) => {
// We guarantee by construction that we have a console here.
@ -703,7 +703,7 @@ impl BufferWriter {
let console_mutex = self.console.as_ref()
.expect("got Windows buffer but have no Console");
let mut console = console_mutex.lock().unwrap();
try!(b.print(&mut *console, &mut stream));
b.print(&mut *console, &mut stream)?;
}
}
self.printed.store(true, Ordering::SeqCst);
@ -959,15 +959,15 @@ impl<W: io::Write> WriteColor for Ansi<W> {
fn supports_color(&self) -> bool { true }
fn set_color(&mut self, spec: &ColorSpec) -> io::Result<()> {
try!(self.reset());
self.reset()?;
if let Some(ref c) = spec.fg_color {
try!(self.write_color(true, c, spec.intense));
self.write_color(true, c, spec.intense)?;
}
if let Some(ref c) = spec.bg_color {
try!(self.write_color(false, c, spec.intense));
self.write_color(false, c, spec.intense)?;
}
if spec.bold {
try!(self.write_str("\x1B[1m"));
self.write_str("\x1B[1m")?;
}
Ok(())
}
@ -1090,15 +1090,15 @@ impl WindowsBuffer {
) -> io::Result<()> {
let mut last = 0;
for &(pos, ref spec) in &self.colors {
try!(stream.write_all(&self.buf[last..pos]));
try!(stream.flush());
stream.write_all(&self.buf[last..pos])?;
stream.flush()?;
last = pos;
match *spec {
None => try!(console.reset()),
Some(ref spec) => try!(spec.write_console(console)),
None => console.reset()?,
Some(ref spec) => spec.write_console(console)?,
}
}
try!(stream.write_all(&self.buf[last..]));
stream.write_all(&self.buf[last..])?;
stream.flush()
}
@ -1213,10 +1213,10 @@ impl ColorSpec {
let intense = if self.intense { Intense::Yes } else { Intense::No };
if let Some(color) = self.fg_color.as_ref().map(|c| c.to_windows()) {
try!(console.fg(intense, color));
console.fg(intense, color)?;
}
if let Some(color) = self.bg_color.as_ref().map(|c| c.to_windows()) {
try!(console.bg(intense, color));
console.bg(intense, color)?;
}
Ok(())
}
@ -1368,7 +1368,7 @@ fn write_lossy_utf8<W: io::Write>(mut w: W, buf: &[u8]) -> io::Result<usize> {
match ::std::str::from_utf8(buf) {
Ok(s) => w.write(s.as_bytes()),
Err(ref e) if e.valid_up_to() == 0 => {
try!(w.write(b"\xEF\xBF\xBD"));
w.write(b"\xEF\xBF\xBD")?;
Ok(1)
}
Err(e) => w.write(&buf[..e.valid_up_to()]),