Skip to content

Commit bb3f2c5

Browse files
committed
Auto merge of #7776 - alexcrichton:anyhow, r=ehuss
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.
2 parents 7059559 + d0430dd commit bb3f2c5

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

94 files changed

+429
-438
lines changed

Cargo.toml

+2-2
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ curl = { version = "0.4.23", features = ["http2"] }
2929
curl-sys = "0.4.22"
3030
env_logger = "0.7.0"
3131
pretty_env_logger = { version = "0.3", optional = true }
32-
failure = "0.1.5"
32+
anyhow = "1.0"
3333
filetime = "0.2"
3434
flate2 = { version = "1.0.3", features = ["zlib"] }
3535
fs2 = "0.4"
@@ -51,7 +51,7 @@ num_cpus = "1.0"
5151
opener = "0.4"
5252
percent-encoding = "2.0"
5353
remove_dir_all = "0.5.2"
54-
rustfix = "0.4.6"
54+
rustfix = "0.5.0"
5555
same-file = "1"
5656
semver = { version = "0.9.0", features = ["serde"] }
5757
serde = { version = "1.0.82", features = ["derive"] }

crates/cargo-test-support/src/lib.rs

+1-5
Original file line numberDiff line numberDiff line change
@@ -916,11 +916,7 @@ impl Execs {
916916
{
917917
return self.match_output(out);
918918
}
919-
let mut s = format!("could not exec process {}: {}", process, e);
920-
for cause in e.iter_causes() {
921-
s.push_str(&format!("\ncaused by: {}", cause));
922-
}
923-
Err(s)
919+
Err(format!("could not exec process {}: {:?}", process, e))
924920
}
925921
}
926922
}

crates/crates-io/Cargo.toml

+1-1
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ path = "lib.rs"
1515

1616
[dependencies]
1717
curl = "0.4"
18-
failure = "0.1.1"
18+
anyhow = "1.0.0"
1919
percent-encoding = "2.0"
2020
serde = { version = "1.0", features = ['derive'] }
2121
serde_derive = "1.0"

crates/crates-io/lib.rs

+1-3
Original file line numberDiff line numberDiff line change
@@ -7,15 +7,13 @@ use std::io::prelude::*;
77
use std::io::Cursor;
88
use std::time::Instant;
99

10+
use anyhow::{bail, Result};
1011
use curl::easy::{Easy, List};
11-
use failure::bail;
1212
use percent_encoding::{percent_encode, NON_ALPHANUMERIC};
1313
use serde::{Deserialize, Serialize};
1414
use serde_json;
1515
use url::Url;
1616

17-
pub type Result<T> = std::result::Result<T, failure::Error>;
18-
1917
pub struct Registry {
2018
/// The base URL for issuing API requests.
2119
host: String,

src/bin/cargo/commands/bench.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -100,7 +100,7 @@ pub fn exec(config: &mut Config, args: &ArgMatches<'_>) -> CliResult {
100100
match err {
101101
None => Ok(()),
102102
Some(err) => Err(match err.exit.as_ref().and_then(|e| e.code()) {
103-
Some(i) => CliError::new(failure::format_err!("bench failed"), i),
103+
Some(i) => CliError::new(anyhow::format_err!("bench failed"), i),
104104
None => CliError::new(err.into(), 101),
105105
}),
106106
}

src/bin/cargo/commands/check.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,7 @@ pub fn exec(config: &mut Config, args: &ArgMatches<'_>) -> CliResult {
6060
Some("test") => true,
6161
None => false,
6262
Some(profile) => {
63-
let err = failure::format_err!(
63+
let err = anyhow::format_err!(
6464
"unknown profile: `{}`, only `test` is \
6565
currently supported",
6666
profile

src/bin/cargo/commands/clippy.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,7 @@ pub fn exec(config: &mut Config, args: &ArgMatches<'_>) -> CliResult {
6666
args.compile_options(config, mode, Some(&ws), ProfileChecking::Checked)?;
6767

6868
if !config.cli_unstable().unstable_options {
69-
return Err(failure::format_err!(
69+
return Err(anyhow::format_err!(
7070
"`clippy-preview` is unstable, pass `-Z unstable-options` to enable it"
7171
)
7272
.into());

src/bin/cargo/commands/fix.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -120,7 +120,7 @@ pub fn exec(config: &mut Config, args: &ArgMatches<'_>) -> CliResult {
120120
Some("test") => true,
121121
None => false,
122122
Some(profile) => {
123-
let err = failure::format_err!(
123+
let err = anyhow::format_err!(
124124
"unknown profile: `{}`, only `test` is \
125125
currently supported",
126126
profile
@@ -143,7 +143,7 @@ pub fn exec(config: &mut Config, args: &ArgMatches<'_>) -> CliResult {
143143
.filter(|_| use_clippy);
144144

145145
if use_clippy && !config.cli_unstable().unstable_options {
146-
return Err(failure::format_err!(
146+
return Err(anyhow::format_err!(
147147
"`cargo fix --clippy` is unstable, pass `-Z unstable-options` to enable it"
148148
)
149149
.into());

src/bin/cargo/commands/locate_project.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ pub fn exec(config: &mut Config, args: &ArgMatches<'_>) -> CliResult {
2121
let root = root
2222
.to_str()
2323
.ok_or_else(|| {
24-
failure::format_err!(
24+
anyhow::format_err!(
2525
"your package path contains characters \
2626
not representable in Unicode"
2727
)

src/bin/cargo/commands/rustc.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,7 @@ pub fn exec(config: &mut Config, args: &ArgMatches<'_>) -> CliResult {
5555
Some("bench") => CompileMode::Bench,
5656
Some("check") => CompileMode::Check { test: false },
5757
Some(mode) => {
58-
let err = failure::format_err!(
58+
let err = anyhow::format_err!(
5959
"unknown profile: `{}`, use dev,
6060
test, or bench",
6161
mode

src/bin/cargo/commands/test.rs

+6-6
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
use crate::command_prelude::*;
2+
use anyhow::Error;
23
use cargo::ops::{self, CompileFilter, FilterRule, LibRule};
34
use cargo::util::errors;
4-
use failure::Fail;
55

66
pub fn cli() -> App {
77
subcommand("test")
@@ -126,13 +126,13 @@ pub fn exec(config: &mut Config, args: &ArgMatches<'_>) -> CliResult {
126126
if doc {
127127
if let CompileFilter::Only { .. } = compile_opts.filter {
128128
return Err(CliError::new(
129-
failure::format_err!("Can't mix --doc with other target selecting options"),
129+
anyhow::format_err!("Can't mix --doc with other target selecting options"),
130130
101,
131131
));
132132
}
133133
if no_run {
134134
return Err(CliError::new(
135-
failure::format_err!("Can't skip running doc tests with --no-run"),
135+
anyhow::format_err!("Can't skip running doc tests with --no-run"),
136136
101,
137137
));
138138
}
@@ -166,12 +166,12 @@ pub fn exec(config: &mut Config, args: &ArgMatches<'_>) -> CliResult {
166166
match err {
167167
None => Ok(()),
168168
Some(err) => {
169-
let context = failure::format_err!("{}", err.hint(&ws, &ops.compile_opts));
169+
let context = anyhow::format_err!("{}", err.hint(&ws, &ops.compile_opts));
170170
let e = match err.exit.as_ref().and_then(|e| e.code()) {
171171
// Don't show "process didn't exit successfully" for simple errors.
172172
Some(i) if errors::is_simple_exit_code(i) => CliError::new(context, i),
173-
Some(i) => CliError::new(err.context(context).into(), i),
174-
None => CliError::new(err.context(context).into(), 101),
173+
Some(i) => CliError::new(Error::from(err).context(context), i),
174+
None => CliError::new(Error::from(err).context(context), 101),
175175
};
176176
Err(e)
177177
}

src/bin/cargo/commands/vendor.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -90,7 +90,7 @@ pub fn exec(config: &mut Config, args: &ArgMatches<'_>) -> CliResult {
9090
None
9191
};
9292
if let Some(flag) = crates_io_cargo_vendor_flag {
93-
return Err(failure::format_err!(
93+
return Err(anyhow::format_err!(
9494
"\
9595
the crates.io `cargo vendor` command has now been merged into Cargo itself
9696
and does not support the flag `{}` currently; to continue using the flag you

src/bin/cargo/main.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -133,7 +133,7 @@ fn execute_external_subcommand(config: &Config, cmd: &str, args: &[&str]) -> Cli
133133
let aliases = list_aliases(config);
134134
let suggestions = commands.iter().chain(aliases.iter());
135135
let did_you_mean = closest_msg(cmd, suggestions, |c| c);
136-
let err = failure::format_err!("no such subcommand: `{}`{}", cmd, did_you_mean);
136+
let err = anyhow::format_err!("no such subcommand: `{}`{}", cmd, did_you_mean);
137137
return Err(CliError::new(err, 101));
138138
}
139139
};

src/cargo/core/compiler/build_config.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,7 @@ impl BuildConfig {
7878
};
7979

8080
if jobs == Some(0) {
81-
failure::bail!("jobs must be at least 1")
81+
anyhow::bail!("jobs must be at least 1")
8282
}
8383
if jobs.is_some() && config.jobserver_from_env().is_some() {
8484
config.shell().warn(

src/cargo/core/compiler/build_context/target_info.rs

+3-3
Original file line numberDiff line numberDiff line change
@@ -137,7 +137,7 @@ impl TargetInfo {
137137

138138
let line = match lines.next() {
139139
Some(line) => line,
140-
None => failure::bail!(
140+
None => anyhow::bail!(
141141
"output of --print=sysroot missing when learning about \
142142
target-specific information from rustc\n{}",
143143
output_err_info(&process, &output, &error)
@@ -329,7 +329,7 @@ fn parse_crate_type(
329329
}
330330
let line = match lines.next() {
331331
Some(line) => line,
332-
None => failure::bail!(
332+
None => anyhow::bail!(
333333
"malformed output when learning about crate-type {} information\n{}",
334334
crate_type,
335335
output_err_info(cmd, output, error)
@@ -339,7 +339,7 @@ fn parse_crate_type(
339339
let prefix = parts.next().unwrap();
340340
let suffix = match parts.next() {
341341
Some(part) => part,
342-
None => failure::bail!(
342+
None => anyhow::bail!(
343343
"output of --print=file-names has changed in the compiler, cannot parse\n{}",
344344
output_err_info(cmd, output, error)
345345
),

src/cargo/core/compiler/build_plan.rs

+3-3
Original file line numberDiff line numberDiff line change
@@ -74,13 +74,13 @@ impl Invocation {
7474
self.program = cmd
7575
.get_program()
7676
.to_str()
77-
.ok_or_else(|| failure::format_err!("unicode program string required"))?
77+
.ok_or_else(|| anyhow::format_err!("unicode program string required"))?
7878
.to_string();
7979
self.cwd = Some(cmd.get_cwd().unwrap().to_path_buf());
8080
for arg in cmd.get_args().iter() {
8181
self.args.push(
8282
arg.to_str()
83-
.ok_or_else(|| failure::format_err!("unicode argument string required"))?
83+
.ok_or_else(|| anyhow::format_err!("unicode argument string required"))?
8484
.to_string(),
8585
);
8686
}
@@ -93,7 +93,7 @@ impl Invocation {
9393
var.clone(),
9494
value
9595
.to_str()
96-
.ok_or_else(|| failure::format_err!("unicode environment value required"))?
96+
.ok_or_else(|| anyhow::format_err!("unicode environment value required"))?
9797
.to_string(),
9898
);
9999
}

src/cargo/core/compiler/compilation.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -304,7 +304,7 @@ fn target_runner(
304304
.filter(|(key, _runner)| CfgExpr::matches_key(key, target_cfg));
305305
let matching_runner = cfgs.next();
306306
if let Some((key, runner)) = cfgs.next() {
307-
failure::bail!(
307+
anyhow::bail!(
308308
"several matching instances of `target.'cfg(..)'.runner` in `.cargo/config`\n\
309309
first match `{}` located in {}\n\
310310
second match `{}` located in {}",

src/cargo/core/compiler/compile_kind.rs

+3-3
Original file line numberDiff line numberDiff line change
@@ -77,7 +77,7 @@ impl CompileTarget {
7777
pub fn new(name: &str) -> CargoResult<CompileTarget> {
7878
let name = name.trim();
7979
if name.is_empty() {
80-
failure::bail!("target was empty");
80+
anyhow::bail!("target was empty");
8181
}
8282
if !name.ends_with(".json") {
8383
return Ok(CompileTarget { name: name.into() });
@@ -88,12 +88,12 @@ impl CompileTarget {
8888
// with different paths always produce the same result.
8989
let path = Path::new(name)
9090
.canonicalize()
91-
.chain_err(|| failure::format_err!("target path {:?} is not a valid file", name))?;
91+
.chain_err(|| anyhow::format_err!("target path {:?} is not a valid file", name))?;
9292

9393
let name = path
9494
.into_os_string()
9595
.into_string()
96-
.map_err(|_| failure::format_err!("target path is not valid unicode"))?;
96+
.map_err(|_| anyhow::format_err!("target path is not valid unicode"))?;
9797
Ok(CompileTarget { name: name.into() })
9898
}
9999

src/cargo/core/compiler/context/compilation_files.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -431,15 +431,15 @@ impl<'a, 'cfg: 'a> CompilationFiles<'a, 'cfg> {
431431
}
432432
if ret.is_empty() {
433433
if !unsupported.is_empty() {
434-
failure::bail!(
434+
anyhow::bail!(
435435
"cannot produce {} for `{}` as the target `{}` \
436436
does not support these crate types",
437437
unsupported.join(", "),
438438
unit.pkg,
439439
unit.kind.short_name(bcx),
440440
)
441441
}
442-
failure::bail!(
442+
anyhow::bail!(
443443
"cannot compile `{}` as the target `{}` does not \
444444
support any of the output crate types",
445445
unit.pkg,

src/cargo/core/compiler/custom_build.rs

+4-4
Original file line numberDiff line numberDiff line change
@@ -460,7 +460,7 @@ impl BuildOutput {
460460
let (key, value) = match (key, value) {
461461
(Some(a), Some(b)) => (a, b.trim_end()),
462462
// Line started with `cargo:` but didn't match `key=value`.
463-
_ => failure::bail!("Wrong output in {}: `{}`", whence, line),
463+
_ => anyhow::bail!("Wrong output in {}: `{}`", whence, line),
464464
};
465465

466466
// This will rewrite paths if the target directory has been moved.
@@ -520,7 +520,7 @@ impl BuildOutput {
520520
if value.is_empty() {
521521
value = match flags_iter.next() {
522522
Some(v) => v,
523-
None => failure::bail! {
523+
None => anyhow::bail! {
524524
"Flag in rustc-flags has no value in {}: {}",
525525
whence,
526526
value
@@ -536,7 +536,7 @@ impl BuildOutput {
536536
_ => unreachable!(),
537537
};
538538
} else {
539-
failure::bail!(
539+
anyhow::bail!(
540540
"Only `-l` and `-L` flags are allowed in {}: `{}`",
541541
whence,
542542
value
@@ -552,7 +552,7 @@ impl BuildOutput {
552552
let val = iter.next();
553553
match (name, val) {
554554
(Some(n), Some(v)) => Ok((n.to_owned(), v.to_owned())),
555-
_ => failure::bail!("Variable rustc-env has no value in {}: {}", whence, value),
555+
_ => anyhow::bail!("Variable rustc-env has no value in {}: {}", whence, value),
556556
}
557557
}
558558
}

src/cargo/core/compiler/fingerprint.rs

+2-6
Original file line numberDiff line numberDiff line change
@@ -194,7 +194,7 @@ use std::path::{Path, PathBuf};
194194
use std::sync::{Arc, Mutex};
195195
use std::time::SystemTime;
196196

197-
use failure::{bail, format_err};
197+
use anyhow::{bail, format_err};
198198
use filetime::FileTime;
199199
use log::{debug, info};
200200
use serde::de;
@@ -1414,11 +1414,7 @@ fn log_compare(unit: &Unit<'_>, compare: &CargoResult<()>) {
14141414
"fingerprint error for {}/{:?}/{:?}",
14151415
unit.pkg, unit.mode, unit.target,
14161416
);
1417-
info!(" err: {}", ce);
1418-
1419-
for cause in ce.iter_causes() {
1420-
info!(" cause: {}", cause);
1421-
}
1417+
info!(" err: {:?}", ce);
14221418
}
14231419

14241420
// Parse the dep-info into a list of paths

src/cargo/core/compiler/job_queue.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,8 @@ use std::sync::mpsc::{channel, Receiver, Sender};
77
use std::sync::Arc;
88
use std::time::Duration;
99

10+
use anyhow::format_err;
1011
use crossbeam_utils::thread::Scope;
11-
use failure::format_err;
1212
use jobserver::{Acquired, HelperThread};
1313
use log::{debug, info, trace};
1414

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

395395
if !self.active.is_empty() {
396-
error = Some(failure::format_err!("build failed"));
396+
error = Some(anyhow::format_err!("build failed"));
397397
handle_error(&e, &mut *cx.bcx.config.shell());
398398
cx.bcx.config.shell().warn(
399399
"build failed, waiting for other \

src/cargo/core/compiler/links.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ pub fn validate_links(resolve: &Resolve, unit_graph: &UnitGraph<'_>) -> CargoRes
3939
dep_path_desc
4040
};
4141

42-
failure::bail!(
42+
anyhow::bail!(
4343
"multiple packages link to native library `{}`, \
4444
but a native library can be linked only once\n\
4545
\n\

src/cargo/core/compiler/mod.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ use std::io::{BufRead, Write};
2323
use std::path::PathBuf;
2424
use std::sync::Arc;
2525

26-
use failure::Error;
26+
use anyhow::Error;
2727
use lazycell::LazyCell;
2828
use log::debug;
2929

0 commit comments

Comments
 (0)