Skip to content

Commit

Permalink
Auto merge of #7776 - alexcrichton:anyhow, r=ehuss
Browse files Browse the repository at this point in the history
Migrate from the `failure` crate to `anyhow`

The `anyhow` crate interoperates with the `std::error::Error` trait
rather than a custom `Fail` trait, and this is the general trend of
error handling in Rust as well.

Note that this is mostly mechanical (sed) and intended to get the test
suite passing. As usual there's still more idiomatic cleanup that can
happen, but that's left to later commits.
  • Loading branch information
bors committed Jan 8, 2020
2 parents 7059559 + d0430dd commit bb3f2c5
Show file tree
Hide file tree
Showing 94 changed files with 429 additions and 438 deletions.
4 changes: 2 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ curl = { version = "0.4.23", features = ["http2"] }
curl-sys = "0.4.22"
env_logger = "0.7.0"
pretty_env_logger = { version = "0.3", optional = true }
failure = "0.1.5"
anyhow = "1.0"
filetime = "0.2"
flate2 = { version = "1.0.3", features = ["zlib"] }
fs2 = "0.4"
Expand All @@ -51,7 +51,7 @@ num_cpus = "1.0"
opener = "0.4"
percent-encoding = "2.0"
remove_dir_all = "0.5.2"
rustfix = "0.4.6"
rustfix = "0.5.0"
same-file = "1"
semver = { version = "0.9.0", features = ["serde"] }
serde = { version = "1.0.82", features = ["derive"] }
Expand Down
6 changes: 1 addition & 5 deletions crates/cargo-test-support/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -916,11 +916,7 @@ impl Execs {
{
return self.match_output(out);
}
let mut s = format!("could not exec process {}: {}", process, e);
for cause in e.iter_causes() {
s.push_str(&format!("\ncaused by: {}", cause));
}
Err(s)
Err(format!("could not exec process {}: {:?}", process, e))
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion crates/crates-io/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ path = "lib.rs"

[dependencies]
curl = "0.4"
failure = "0.1.1"
anyhow = "1.0.0"
percent-encoding = "2.0"
serde = { version = "1.0", features = ['derive'] }
serde_derive = "1.0"
Expand Down
4 changes: 1 addition & 3 deletions crates/crates-io/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,13 @@ use std::io::prelude::*;
use std::io::Cursor;
use std::time::Instant;

use anyhow::{bail, Result};
use curl::easy::{Easy, List};
use failure::bail;
use percent_encoding::{percent_encode, NON_ALPHANUMERIC};
use serde::{Deserialize, Serialize};
use serde_json;
use url::Url;

pub type Result<T> = std::result::Result<T, failure::Error>;

pub struct Registry {
/// The base URL for issuing API requests.
host: String,
Expand Down
2 changes: 1 addition & 1 deletion src/bin/cargo/commands/bench.rs
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ pub fn exec(config: &mut Config, args: &ArgMatches<'_>) -> CliResult {
match err {
None => Ok(()),
Some(err) => Err(match err.exit.as_ref().and_then(|e| e.code()) {
Some(i) => CliError::new(failure::format_err!("bench failed"), i),
Some(i) => CliError::new(anyhow::format_err!("bench failed"), i),
None => CliError::new(err.into(), 101),
}),
}
Expand Down
2 changes: 1 addition & 1 deletion src/bin/cargo/commands/check.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ pub fn exec(config: &mut Config, args: &ArgMatches<'_>) -> CliResult {
Some("test") => true,
None => false,
Some(profile) => {
let err = failure::format_err!(
let err = anyhow::format_err!(
"unknown profile: `{}`, only `test` is \
currently supported",
profile
Expand Down
2 changes: 1 addition & 1 deletion src/bin/cargo/commands/clippy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ pub fn exec(config: &mut Config, args: &ArgMatches<'_>) -> CliResult {
args.compile_options(config, mode, Some(&ws), ProfileChecking::Checked)?;

if !config.cli_unstable().unstable_options {
return Err(failure::format_err!(
return Err(anyhow::format_err!(
"`clippy-preview` is unstable, pass `-Z unstable-options` to enable it"
)
.into());
Expand Down
4 changes: 2 additions & 2 deletions src/bin/cargo/commands/fix.rs
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ pub fn exec(config: &mut Config, args: &ArgMatches<'_>) -> CliResult {
Some("test") => true,
None => false,
Some(profile) => {
let err = failure::format_err!(
let err = anyhow::format_err!(
"unknown profile: `{}`, only `test` is \
currently supported",
profile
Expand All @@ -143,7 +143,7 @@ pub fn exec(config: &mut Config, args: &ArgMatches<'_>) -> CliResult {
.filter(|_| use_clippy);

if use_clippy && !config.cli_unstable().unstable_options {
return Err(failure::format_err!(
return Err(anyhow::format_err!(
"`cargo fix --clippy` is unstable, pass `-Z unstable-options` to enable it"
)
.into());
Expand Down
2 changes: 1 addition & 1 deletion src/bin/cargo/commands/locate_project.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ pub fn exec(config: &mut Config, args: &ArgMatches<'_>) -> CliResult {
let root = root
.to_str()
.ok_or_else(|| {
failure::format_err!(
anyhow::format_err!(
"your package path contains characters \
not representable in Unicode"
)
Expand Down
2 changes: 1 addition & 1 deletion src/bin/cargo/commands/rustc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ pub fn exec(config: &mut Config, args: &ArgMatches<'_>) -> CliResult {
Some("bench") => CompileMode::Bench,
Some("check") => CompileMode::Check { test: false },
Some(mode) => {
let err = failure::format_err!(
let err = anyhow::format_err!(
"unknown profile: `{}`, use dev,
test, or bench",
mode
Expand Down
12 changes: 6 additions & 6 deletions src/bin/cargo/commands/test.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use crate::command_prelude::*;
use anyhow::Error;
use cargo::ops::{self, CompileFilter, FilterRule, LibRule};
use cargo::util::errors;
use failure::Fail;

pub fn cli() -> App {
subcommand("test")
Expand Down Expand Up @@ -126,13 +126,13 @@ pub fn exec(config: &mut Config, args: &ArgMatches<'_>) -> CliResult {
if doc {
if let CompileFilter::Only { .. } = compile_opts.filter {
return Err(CliError::new(
failure::format_err!("Can't mix --doc with other target selecting options"),
anyhow::format_err!("Can't mix --doc with other target selecting options"),
101,
));
}
if no_run {
return Err(CliError::new(
failure::format_err!("Can't skip running doc tests with --no-run"),
anyhow::format_err!("Can't skip running doc tests with --no-run"),
101,
));
}
Expand Down Expand Up @@ -166,12 +166,12 @@ pub fn exec(config: &mut Config, args: &ArgMatches<'_>) -> CliResult {
match err {
None => Ok(()),
Some(err) => {
let context = failure::format_err!("{}", err.hint(&ws, &ops.compile_opts));
let context = anyhow::format_err!("{}", err.hint(&ws, &ops.compile_opts));
let e = match err.exit.as_ref().and_then(|e| e.code()) {
// Don't show "process didn't exit successfully" for simple errors.
Some(i) if errors::is_simple_exit_code(i) => CliError::new(context, i),
Some(i) => CliError::new(err.context(context).into(), i),
None => CliError::new(err.context(context).into(), 101),
Some(i) => CliError::new(Error::from(err).context(context), i),
None => CliError::new(Error::from(err).context(context), 101),
};
Err(e)
}
Expand Down
2 changes: 1 addition & 1 deletion src/bin/cargo/commands/vendor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ pub fn exec(config: &mut Config, args: &ArgMatches<'_>) -> CliResult {
None
};
if let Some(flag) = crates_io_cargo_vendor_flag {
return Err(failure::format_err!(
return Err(anyhow::format_err!(
"\
the crates.io `cargo vendor` command has now been merged into Cargo itself
and does not support the flag `{}` currently; to continue using the flag you
Expand Down
2 changes: 1 addition & 1 deletion src/bin/cargo/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@ fn execute_external_subcommand(config: &Config, cmd: &str, args: &[&str]) -> Cli
let aliases = list_aliases(config);
let suggestions = commands.iter().chain(aliases.iter());
let did_you_mean = closest_msg(cmd, suggestions, |c| c);
let err = failure::format_err!("no such subcommand: `{}`{}", cmd, did_you_mean);
let err = anyhow::format_err!("no such subcommand: `{}`{}", cmd, did_you_mean);
return Err(CliError::new(err, 101));
}
};
Expand Down
2 changes: 1 addition & 1 deletion src/cargo/core/compiler/build_config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ impl BuildConfig {
};

if jobs == Some(0) {
failure::bail!("jobs must be at least 1")
anyhow::bail!("jobs must be at least 1")
}
if jobs.is_some() && config.jobserver_from_env().is_some() {
config.shell().warn(
Expand Down
6 changes: 3 additions & 3 deletions src/cargo/core/compiler/build_context/target_info.rs
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ impl TargetInfo {

let line = match lines.next() {
Some(line) => line,
None => failure::bail!(
None => anyhow::bail!(
"output of --print=sysroot missing when learning about \
target-specific information from rustc\n{}",
output_err_info(&process, &output, &error)
Expand Down Expand Up @@ -329,7 +329,7 @@ fn parse_crate_type(
}
let line = match lines.next() {
Some(line) => line,
None => failure::bail!(
None => anyhow::bail!(
"malformed output when learning about crate-type {} information\n{}",
crate_type,
output_err_info(cmd, output, error)
Expand All @@ -339,7 +339,7 @@ fn parse_crate_type(
let prefix = parts.next().unwrap();
let suffix = match parts.next() {
Some(part) => part,
None => failure::bail!(
None => anyhow::bail!(
"output of --print=file-names has changed in the compiler, cannot parse\n{}",
output_err_info(cmd, output, error)
),
Expand Down
6 changes: 3 additions & 3 deletions src/cargo/core/compiler/build_plan.rs
Original file line number Diff line number Diff line change
Expand Up @@ -74,13 +74,13 @@ impl Invocation {
self.program = cmd
.get_program()
.to_str()
.ok_or_else(|| failure::format_err!("unicode program string required"))?
.ok_or_else(|| anyhow::format_err!("unicode program string required"))?
.to_string();
self.cwd = Some(cmd.get_cwd().unwrap().to_path_buf());
for arg in cmd.get_args().iter() {
self.args.push(
arg.to_str()
.ok_or_else(|| failure::format_err!("unicode argument string required"))?
.ok_or_else(|| anyhow::format_err!("unicode argument string required"))?
.to_string(),
);
}
Expand All @@ -93,7 +93,7 @@ impl Invocation {
var.clone(),
value
.to_str()
.ok_or_else(|| failure::format_err!("unicode environment value required"))?
.ok_or_else(|| anyhow::format_err!("unicode environment value required"))?
.to_string(),
);
}
Expand Down
2 changes: 1 addition & 1 deletion src/cargo/core/compiler/compilation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -304,7 +304,7 @@ fn target_runner(
.filter(|(key, _runner)| CfgExpr::matches_key(key, target_cfg));
let matching_runner = cfgs.next();
if let Some((key, runner)) = cfgs.next() {
failure::bail!(
anyhow::bail!(
"several matching instances of `target.'cfg(..)'.runner` in `.cargo/config`\n\
first match `{}` located in {}\n\
second match `{}` located in {}",
Expand Down
6 changes: 3 additions & 3 deletions src/cargo/core/compiler/compile_kind.rs
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ impl CompileTarget {
pub fn new(name: &str) -> CargoResult<CompileTarget> {
let name = name.trim();
if name.is_empty() {
failure::bail!("target was empty");
anyhow::bail!("target was empty");
}
if !name.ends_with(".json") {
return Ok(CompileTarget { name: name.into() });
Expand All @@ -88,12 +88,12 @@ impl CompileTarget {
// with different paths always produce the same result.
let path = Path::new(name)
.canonicalize()
.chain_err(|| failure::format_err!("target path {:?} is not a valid file", name))?;
.chain_err(|| anyhow::format_err!("target path {:?} is not a valid file", name))?;

let name = path
.into_os_string()
.into_string()
.map_err(|_| failure::format_err!("target path is not valid unicode"))?;
.map_err(|_| anyhow::format_err!("target path is not valid unicode"))?;
Ok(CompileTarget { name: name.into() })
}

Expand Down
4 changes: 2 additions & 2 deletions src/cargo/core/compiler/context/compilation_files.rs
Original file line number Diff line number Diff line change
Expand Up @@ -431,15 +431,15 @@ impl<'a, 'cfg: 'a> CompilationFiles<'a, 'cfg> {
}
if ret.is_empty() {
if !unsupported.is_empty() {
failure::bail!(
anyhow::bail!(
"cannot produce {} for `{}` as the target `{}` \
does not support these crate types",
unsupported.join(", "),
unit.pkg,
unit.kind.short_name(bcx),
)
}
failure::bail!(
anyhow::bail!(
"cannot compile `{}` as the target `{}` does not \
support any of the output crate types",
unit.pkg,
Expand Down
8 changes: 4 additions & 4 deletions src/cargo/core/compiler/custom_build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -460,7 +460,7 @@ impl BuildOutput {
let (key, value) = match (key, value) {
(Some(a), Some(b)) => (a, b.trim_end()),
// Line started with `cargo:` but didn't match `key=value`.
_ => failure::bail!("Wrong output in {}: `{}`", whence, line),
_ => anyhow::bail!("Wrong output in {}: `{}`", whence, line),
};

// This will rewrite paths if the target directory has been moved.
Expand Down Expand Up @@ -520,7 +520,7 @@ impl BuildOutput {
if value.is_empty() {
value = match flags_iter.next() {
Some(v) => v,
None => failure::bail! {
None => anyhow::bail! {
"Flag in rustc-flags has no value in {}: {}",
whence,
value
Expand All @@ -536,7 +536,7 @@ impl BuildOutput {
_ => unreachable!(),
};
} else {
failure::bail!(
anyhow::bail!(
"Only `-l` and `-L` flags are allowed in {}: `{}`",
whence,
value
Expand All @@ -552,7 +552,7 @@ impl BuildOutput {
let val = iter.next();
match (name, val) {
(Some(n), Some(v)) => Ok((n.to_owned(), v.to_owned())),
_ => failure::bail!("Variable rustc-env has no value in {}: {}", whence, value),
_ => anyhow::bail!("Variable rustc-env has no value in {}: {}", whence, value),
}
}
}
Expand Down
8 changes: 2 additions & 6 deletions src/cargo/core/compiler/fingerprint.rs
Original file line number Diff line number Diff line change
Expand Up @@ -194,7 +194,7 @@ use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
use std::time::SystemTime;

use failure::{bail, format_err};
use anyhow::{bail, format_err};
use filetime::FileTime;
use log::{debug, info};
use serde::de;
Expand Down Expand Up @@ -1414,11 +1414,7 @@ fn log_compare(unit: &Unit<'_>, compare: &CargoResult<()>) {
"fingerprint error for {}/{:?}/{:?}",
unit.pkg, unit.mode, unit.target,
);
info!(" err: {}", ce);

for cause in ce.iter_causes() {
info!(" cause: {}", cause);
}
info!(" err: {:?}", ce);
}

// Parse the dep-info into a list of paths
Expand Down
4 changes: 2 additions & 2 deletions src/cargo/core/compiler/job_queue.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@ use std::sync::mpsc::{channel, Receiver, Sender};
use std::sync::Arc;
use std::time::Duration;

use anyhow::format_err;
use crossbeam_utils::thread::Scope;
use failure::format_err;
use jobserver::{Acquired, HelperThread};
use log::{debug, info, trace};

Expand Down Expand Up @@ -393,7 +393,7 @@ impl<'a, 'cfg> JobQueue<'a, 'cfg> {
self.emit_warnings(Some(msg), &unit, cx)?;

if !self.active.is_empty() {
error = Some(failure::format_err!("build failed"));
error = Some(anyhow::format_err!("build failed"));
handle_error(&e, &mut *cx.bcx.config.shell());
cx.bcx.config.shell().warn(
"build failed, waiting for other \
Expand Down
2 changes: 1 addition & 1 deletion src/cargo/core/compiler/links.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ pub fn validate_links(resolve: &Resolve, unit_graph: &UnitGraph<'_>) -> CargoRes
dep_path_desc
};

failure::bail!(
anyhow::bail!(
"multiple packages link to native library `{}`, \
but a native library can be linked only once\n\
\n\
Expand Down
2 changes: 1 addition & 1 deletion src/cargo/core/compiler/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ use std::io::{BufRead, Write};
use std::path::PathBuf;
use std::sync::Arc;

use failure::Error;
use anyhow::Error;
use lazycell::LazyCell;
use log::debug;

Expand Down
Loading

0 comments on commit bb3f2c5

Please sign in to comment.