diff --git a/src/bin/cargo/commands/describe_future_incompatibilities.rs b/src/bin/cargo/commands/describe_future_incompatibilities.rs index dd1b5f2b10b..79fd971857d 100644 --- a/src/bin/cargo/commands/describe_future_incompatibilities.rs +++ b/src/bin/cargo/commands/describe_future_incompatibilities.rs @@ -1,8 +1,7 @@ use crate::command_prelude::*; -use anyhow::anyhow; +use anyhow::{anyhow, Context as _}; use cargo::core::compiler::future_incompat::{OnDiskReport, FUTURE_INCOMPAT_FILE}; use cargo::drop_eprint; -use cargo::util::CargoResultExt; use std::io::Read; pub fn cli() -> App { @@ -37,9 +36,9 @@ pub fn exec(config: &mut Config, args: &ArgMatches<'_>) -> CliResult { report_file .file() .read_to_string(&mut file_contents) - .chain_err(|| "failed to read report")?; + .with_context(|| "failed to read report")?; let on_disk_report: OnDiskReport = - serde_json::from_str(&file_contents).chain_err(|| "failed to load report")?; + serde_json::from_str(&file_contents).with_context(|| "failed to load report")?; let id = args.value_of("id").unwrap(); if id != on_disk_report.id { diff --git a/src/cargo/core/compiler/build_context/target_info.rs b/src/cargo/core/compiler/build_context/target_info.rs index 44a46209b0e..8ab4af9b7d9 100644 --- a/src/cargo/core/compiler/build_context/target_info.rs +++ b/src/cargo/core/compiler/build_context/target_info.rs @@ -3,7 +3,8 @@ use crate::core::compiler::{ }; use crate::core::{Dependency, Target, TargetKind, Workspace}; use crate::util::config::{Config, StringList, TargetConfig}; -use crate::util::{CargoResult, CargoResultExt, Rustc}; +use crate::util::{CargoResult, Rustc}; +use anyhow::Context as _; use cargo_platform::{Cfg, CfgExpr}; use cargo_util::{paths, ProcessBuilder}; use serde::{Deserialize, Serialize}; @@ -176,7 +177,7 @@ impl TargetInfo { let (output, error) = rustc .cached_output(&process, extra_fingerprint) - .chain_err(|| "failed to run `rustc` to learn about target-specific information")?; + .with_context(|| "failed to run `rustc` to learn about target-specific information")?; let mut lines = output.lines(); let mut map = HashMap::new(); @@ -212,7 +213,7 @@ impl TargetInfo { .map(|line| Ok(Cfg::from_str(line)?)) .filter(TargetInfo::not_user_specific_cfg) .collect::>>() - .chain_err(|| { + .with_context(|| { format!( "failed to parse the cfg from `rustc --print=cfg`, got:\n{}", output @@ -413,7 +414,7 @@ impl TargetInfo { process.arg("--crate-type").arg(crate_type.as_str()); - let output = process.exec_with_output().chain_err(|| { + let output = process.exec_with_output().with_context(|| { format!( "failed to run `rustc` to learn about crate-type {} information", crate_type diff --git a/src/cargo/core/compiler/compile_kind.rs b/src/cargo/core/compiler/compile_kind.rs index 41d5f64aac1..adfa55fce17 100644 --- a/src/cargo/core/compiler/compile_kind.rs +++ b/src/cargo/core/compiler/compile_kind.rs @@ -1,8 +1,8 @@ use crate::core::Target; -use crate::util::errors::{CargoResult, CargoResultExt}; +use crate::util::errors::CargoResult; use crate::util::interning::InternedString; use crate::util::{Config, StableHasher}; -use anyhow::bail; +use anyhow::{bail, Context as _}; use serde::Serialize; use std::collections::BTreeSet; use std::fs; @@ -143,7 +143,7 @@ impl CompileTarget { // with different paths always produce the same result. let path = Path::new(name) .canonicalize() - .chain_err(|| anyhow::format_err!("target path {:?} is not a valid file", name))?; + .with_context(|| format!("target path {:?} is not a valid file", name))?; let name = path .into_os_string() diff --git a/src/cargo/core/compiler/context/mod.rs b/src/cargo/core/compiler/context/mod.rs index cb1dbb6240b..4502ba3c5f3 100644 --- a/src/cargo/core/compiler/context/mod.rs +++ b/src/cargo/core/compiler/context/mod.rs @@ -2,13 +2,14 @@ use std::collections::{BTreeSet, HashMap, HashSet}; use std::path::{Path, PathBuf}; use std::sync::{Arc, Mutex}; +use anyhow::Context as _; use filetime::FileTime; use jobserver::Client; use crate::core::compiler::compilation::{self, UnitOutput}; use crate::core::compiler::{self, Unit}; use crate::core::PackageId; -use crate::util::errors::{CargoResult, CargoResultExt}; +use crate::util::errors::CargoResult; use crate::util::profile; use super::build_plan::BuildPlan; @@ -96,7 +97,7 @@ impl<'a, 'cfg> Context<'a, 'cfg> { Some(c) => c.clone(), None => { let client = Client::new(bcx.build_config.jobs as usize) - .chain_err(|| "failed to create jobserver")?; + .with_context(|| "failed to create jobserver")?; client.acquire_raw()?; client } @@ -324,11 +325,11 @@ impl<'a, 'cfg> Context<'a, 'cfg> { self.files_mut() .host .prepare() - .chain_err(|| "couldn't prepare build directories")?; + .with_context(|| "couldn't prepare build directories")?; for target in self.files.as_mut().unwrap().target.values_mut() { target .prepare() - .chain_err(|| "couldn't prepare build directories")?; + .with_context(|| "couldn't prepare build directories")?; } let files = self.files.as_ref().unwrap(); @@ -559,11 +560,11 @@ impl<'a, 'cfg> Context<'a, 'cfg> { pub fn new_jobserver(&mut self) -> CargoResult { let tokens = self.bcx.build_config.jobs as usize; - let client = Client::new(tokens).chain_err(|| "failed to create jobserver")?; + let client = Client::new(tokens).with_context(|| "failed to create jobserver")?; // Drain the client fully for i in 0..tokens { - client.acquire_raw().chain_err(|| { + client.acquire_raw().with_context(|| { format!( "failed to fully drain {}/{} token from jobserver at startup", i, tokens, diff --git a/src/cargo/core/compiler/custom_build.rs b/src/cargo/core/compiler/custom_build.rs index dbf86e73a1b..a7a5ca1ba92 100644 --- a/src/cargo/core/compiler/custom_build.rs +++ b/src/cargo/core/compiler/custom_build.rs @@ -3,10 +3,11 @@ use super::{fingerprint, Context, LinkType, Unit}; use crate::core::compiler::context::Metadata; use crate::core::compiler::job_queue::JobState; use crate::core::{profiles::ProfileRoot, PackageId}; -use crate::util::errors::{CargoResult, CargoResultExt}; +use crate::util::errors::CargoResult; use crate::util::interning::InternedString; use crate::util::machine_message::{self, Message}; use crate::util::{internal, profile}; +use anyhow::Context as _; use cargo_platform::Cfg; use cargo_util::paths; use std::collections::hash_map::{Entry, HashMap}; @@ -308,7 +309,7 @@ fn build_work(cx: &mut Context<'_, '_>, unit: &Unit) -> CargoResult { // If we have an old build directory, then just move it into place, // otherwise create it! paths::create_dir_all(&script_out_dir) - .chain_err(|| "failed to create script output directory for build command")?; + .with_context(|| "failed to create script output directory for build command")?; // For all our native lib dependencies, pick up their metadata to pass // along to this custom build command. We're also careful to augment our @@ -370,7 +371,7 @@ fn build_work(cx: &mut Context<'_, '_>, unit: &Unit) -> CargoResult { }, true, ) - .chain_err(|| format!("failed to run custom build command for `{}`", pkg_descr)); + .with_context(|| format!("failed to run custom build command for `{}`", pkg_descr)); if let Err(error) = output { insert_warnings_in_build_outputs( diff --git a/src/cargo/core/compiler/fingerprint.rs b/src/cargo/core/compiler/fingerprint.rs index 4a9339bd992..afed819f98c 100644 --- a/src/cargo/core/compiler/fingerprint.rs +++ b/src/cargo/core/compiler/fingerprint.rs @@ -321,7 +321,7 @@ use std::str; use std::sync::{Arc, Mutex}; use std::time::SystemTime; -use anyhow::{bail, format_err}; +use anyhow::{bail, format_err, Context as _}; use cargo_util::{paths, ProcessBuilder}; use filetime::FileTime; use log::{debug, info}; @@ -332,7 +332,7 @@ use serde::{Deserialize, Serialize}; use crate::core::compiler::unit_graph::UnitDep; use crate::core::Package; use crate::util; -use crate::util::errors::{CargoResult, CargoResultExt}; +use crate::util::errors::CargoResult; use crate::util::interning::InternedString; use crate::util::{internal, path_args, profile}; @@ -1286,7 +1286,7 @@ fn calculate_normal(cx: &mut Context<'_, '_>, unit: &Unit) -> CargoResult, unit: &Unit) -> CargoRes let local = (gen_local)( deps, Some(&|| { - pkg_fingerprint(cx.bcx, &unit.pkg).chain_err(|| { + pkg_fingerprint(cx.bcx, &unit.pkg).with_context(|| { format!( "failed to determine package fingerprint for build script for {}", unit.pkg @@ -1643,7 +1643,7 @@ fn compare_old_fingerprint( let old_fingerprint_json = paths::read(&loc.with_extension("json"))?; let old_fingerprint: Fingerprint = serde_json::from_str(&old_fingerprint_json) - .chain_err(|| internal("failed to deserialize json"))?; + .with_context(|| internal("failed to deserialize json"))?; // Fingerprint can be empty after a failed rebuild (see comment in prepare_target). if !old_fingerprint_short.is_empty() { debug_assert_eq!(util::to_hex(old_fingerprint.hash()), old_fingerprint_short); diff --git a/src/cargo/core/compiler/job_queue.rs b/src/cargo/core/compiler/job_queue.rs index 4491b1fd649..e67cfc1ce3e 100644 --- a/src/cargo/core/compiler/job_queue.rs +++ b/src/cargo/core/compiler/job_queue.rs @@ -56,7 +56,7 @@ use std::marker; use std::sync::Arc; use std::time::Duration; -use anyhow::format_err; +use anyhow::{format_err, Context as _}; use cargo_util::ProcessBuilder; use crossbeam_utils::thread::Scope; use jobserver::{Acquired, Client, HelperThread}; @@ -78,8 +78,8 @@ use crate::core::{PackageId, Shell, TargetKind}; use crate::drop_eprint; use crate::util::diagnostic_server::{self, DiagnosticPrinter}; use crate::util::machine_message::{self, Message as _}; +use crate::util::CargoResult; use crate::util::{self, internal, profile}; -use crate::util::{CargoResult, CargoResultExt}; use crate::util::{Config, DependencyQueue, Progress, ProgressStyle, Queue}; /// This structure is backed by the `DependencyQueue` type and manages the @@ -440,7 +440,7 @@ impl<'cfg> JobQueue<'cfg> { .into_helper_thread(move |token| { messages.push(Message::Token(token)); }) - .chain_err(|| "failed to create helper thread for jobserver management")?; + .with_context(|| "failed to create helper thread for jobserver management")?; // Create a helper thread to manage the diagnostics for rustfix if // necessary. @@ -537,7 +537,7 @@ impl<'cfg> DrainState<'cfg> { .push(token); client .release_raw() - .chain_err(|| "failed to release jobserver token")?; + .with_context(|| "failed to release jobserver token")?; } Ok(()) @@ -617,7 +617,7 @@ impl<'cfg> DrainState<'cfg> { .push(FutureIncompatReportCrate { package_id, report }); } Message::Token(acquired_token) => { - let token = acquired_token.chain_err(|| "failed to acquire jobserver token")?; + let token = acquired_token.with_context(|| "failed to acquire jobserver token")?; self.tokens.push(token); } Message::NeedsToken(id) => { diff --git a/src/cargo/core/compiler/mod.rs b/src/cargo/core/compiler/mod.rs index a1dddf1ad82..ad43d1d9fa2 100644 --- a/src/cargo/core/compiler/mod.rs +++ b/src/cargo/core/compiler/mod.rs @@ -28,7 +28,7 @@ use std::io::{BufRead, Write}; use std::path::{Path, PathBuf}; use std::sync::Arc; -use anyhow::Error; +use anyhow::{Context as _, Error}; use lazycell::LazyCell; use log::debug; @@ -54,7 +54,7 @@ pub use crate::core::compiler::unit::{Unit, UnitInterner}; use crate::core::manifest::TargetSourcePath; use crate::core::profiles::{PanicStrategy, Profile, Strip}; use crate::core::{Feature, PackageId, Target}; -use crate::util::errors::{CargoResult, CargoResultExt, VerboseError}; +use crate::util::errors::{CargoResult, VerboseError}; use crate::util::interning::InternedString; use crate::util::machine_message::{self, Message}; use crate::util::{add_path_args, internal, iter_join_onto, profile}; @@ -331,7 +331,7 @@ fn rustc(cx: &mut Context<'_, '_>, unit: &Unit, exec: &Arc) -> Car }, ) .map_err(verbose_if_simple_exit_code) - .chain_err(|| format!("could not compile `{}`", name))?; + .with_context(|| format!("could not compile `{}`", name))?; } if rustc_dep_info_loc.exists() { @@ -345,7 +345,7 @@ fn rustc(cx: &mut Context<'_, '_>, unit: &Unit, exec: &Arc) -> Car // Do not track source files in the fingerprint for registry dependencies. is_local, ) - .chain_err(|| { + .with_context(|| { internal(format!( "could not parse/generate dep info at: {}", rustc_dep_info_loc.display() @@ -665,7 +665,7 @@ fn rustdoc(cx: &mut Context<'_, '_>, unit: &Unit) -> CargoResult { }, false, ) - .chain_err(|| format!("could not document `{}`", name))?; + .with_context(|| format!("could not document `{}`", name))?; Ok(()) })) } diff --git a/src/cargo/core/compiler/timings.rs b/src/cargo/core/compiler/timings.rs index 182c078da74..836acac5cdb 100644 --- a/src/cargo/core/compiler/timings.rs +++ b/src/cargo/core/compiler/timings.rs @@ -8,7 +8,8 @@ use crate::core::compiler::BuildContext; use crate::core::PackageId; use crate::util::cpu::State; use crate::util::machine_message::{self, Message}; -use crate::util::{CargoResult, CargoResultExt, Config}; +use crate::util::{CargoResult, Config}; +use anyhow::Context as _; use cargo_util::paths; use std::collections::HashMap; use std::io::{BufWriter, Write}; @@ -324,7 +325,7 @@ impl<'cfg> Timings<'cfg> { .sort_unstable_by(|a, b| a.start.partial_cmp(&b.start).unwrap()); if self.report_html { self.report_html(bcx, error) - .chain_err(|| "failed to save timing report")?; + .with_context(|| "failed to save timing report")?; } Ok(()) } diff --git a/src/cargo/core/dependency.rs b/src/cargo/core/dependency.rs index 483ecef75bf..71bab190185 100644 --- a/src/cargo/core/dependency.rs +++ b/src/cargo/core/dependency.rs @@ -1,3 +1,4 @@ +use anyhow::Context as _; use cargo_platform::Platform; use log::trace; use semver::ReqParseError; @@ -8,7 +9,7 @@ use std::path::PathBuf; use std::rc::Rc; use crate::core::{PackageId, SourceId, Summary}; -use crate::util::errors::{CargoResult, CargoResultExt}; +use crate::util::errors::CargoResult; use crate::util::interning::InternedString; use crate::util::Config; @@ -132,7 +133,7 @@ this warning. } Err(e) => { let err: CargoResult = Err(e.into()); - let v: VersionReq = err.chain_err(|| { + let v: VersionReq = err.with_context(|| { format!( "failed to parse the version requirement `{}` for dependency `{}`", req, name diff --git a/src/cargo/core/manifest.rs b/src/cargo/core/manifest.rs index 458ab128170..ec297fca61f 100644 --- a/src/cargo/core/manifest.rs +++ b/src/cargo/core/manifest.rs @@ -5,6 +5,7 @@ use std::path::{Path, PathBuf}; use std::rc::Rc; use std::sync::Arc; +use anyhow::Context as _; use semver::Version; use serde::ser; use serde::Serialize; @@ -496,11 +497,9 @@ impl Manifest { if self.im_a_teapot.is_some() { self.unstable_features .require(Feature::test_dummy_unstable()) - .chain_err(|| { - anyhow::format_err!( - "the `im-a-teapot` manifest key is unstable and may \ - not work properly in England" - ) + .with_context(|| { + "the `im-a-teapot` manifest key is unstable and may \ + not work properly in England" })?; } diff --git a/src/cargo/core/package.rs b/src/cargo/core/package.rs index 301c11c23ce..2400c78327f 100644 --- a/src/cargo/core/package.rs +++ b/src/cargo/core/package.rs @@ -26,7 +26,7 @@ use crate::core::{Dependency, Manifest, PackageId, SourceId, Target}; use crate::core::{SourceMap, Summary, Workspace}; use crate::ops; use crate::util::config::PackageCacheLock; -use crate::util::errors::{CargoResult, CargoResultExt, HttpNot200}; +use crate::util::errors::{CargoResult, HttpNot200}; use crate::util::interning::InternedString; use crate::util::network::Retry; use crate::util::{self, internal, Config, Progress, ProgressStyle}; @@ -416,7 +416,7 @@ impl<'cfg> PackageSet<'cfg> { let multiplexing = config.http_config()?.multiplexing.unwrap_or(true); multi .pipelining(false, multiplexing) - .chain_err(|| "failed to enable multiplexing/pipelining in curl")?; + .with_context(|| "failed to enable multiplexing/pipelining in curl")?; // let's not flood crates.io with connections multi.set_max_host_connections(2)?; @@ -612,7 +612,7 @@ impl<'a, 'cfg> Downloads<'a, 'cfg> { /// the package is ready and doesn't need to be downloaded. pub fn start(&mut self, id: PackageId) -> CargoResult> { self.start_inner(id) - .chain_err(|| format!("failed to download `{}`", id)) + .with_context(|| format!("failed to download `{}`", id)) } fn start_inner(&mut self, id: PackageId) -> CargoResult> { @@ -636,7 +636,7 @@ impl<'a, 'cfg> Downloads<'a, 'cfg> { .ok_or_else(|| internal(format!("couldn't find source for `{}`", id)))?; let pkg = source .download(id) - .chain_err(|| anyhow::format_err!("unable to get packages from source"))?; + .with_context(|| "unable to get packages from source")?; let (url, descriptor) = match pkg { MaybePackage::Ready(pkg) => { debug!("{} doesn't need a download", id); @@ -810,7 +810,7 @@ impl<'a, 'cfg> Downloads<'a, 'cfg> { } Ok(()) }) - .chain_err(|| format!("failed to download from `{}`", dl.url))? + .with_context(|| format!("failed to download from `{}`", dl.url))? }; match ret { Some(()) => break (dl, data), @@ -908,7 +908,7 @@ impl<'a, 'cfg> Downloads<'a, 'cfg> { self.set .multi .perform() - .chain_err(|| "failed to perform http requests") + .with_context(|| "failed to perform http requests") })?; debug!("handles remaining: {}", n); let results = &mut self.results; @@ -935,7 +935,7 @@ impl<'a, 'cfg> Downloads<'a, 'cfg> { self.set .multi .wait(&mut [], timeout) - .chain_err(|| "failed to wait on curl `Multi`")?; + .with_context(|| "failed to wait on curl `Multi`")?; } } diff --git a/src/cargo/core/package_id_spec.rs b/src/cargo/core/package_id_spec.rs index 6049e981fa9..723b624e8bf 100644 --- a/src/cargo/core/package_id_spec.rs +++ b/src/cargo/core/package_id_spec.rs @@ -1,13 +1,13 @@ use std::collections::HashMap; use std::fmt; -use anyhow::bail; +use anyhow::{bail, Context as _}; use semver::Version; use serde::{de, ser}; use url::Url; use crate::core::PackageId; -use crate::util::errors::{CargoResult, CargoResultExt}; +use crate::util::errors::CargoResult; use crate::util::interning::InternedString; use crate::util::lev_distance; use crate::util::{validate_package_name, IntoUrl, ToSemver}; @@ -85,9 +85,9 @@ impl PackageIdSpec { I: IntoIterator, { let i: Vec<_> = i.into_iter().collect(); - let spec = PackageIdSpec::parse(spec).chain_err(|| { + let spec = PackageIdSpec::parse(spec).with_context(|| { let suggestion = lev_distance::closest_msg(spec, i.iter(), |id| id.name().as_str()); - anyhow::format_err!("invalid package ID specification: `{}`{}", spec, suggestion) + format!("invalid package ID specification: `{}`{}", spec, suggestion) })?; spec.query(i) } diff --git a/src/cargo/core/profiles.rs b/src/cargo/core/profiles.rs index d1baaa24442..a86f0899e58 100644 --- a/src/cargo/core/profiles.rs +++ b/src/cargo/core/profiles.rs @@ -1,11 +1,10 @@ use crate::core::compiler::{CompileKind, CompileMode, Unit}; use crate::core::resolver::features::FeaturesFor; use crate::core::{Feature, PackageId, PackageIdSpec, Resolve, Shell, Target, Workspace}; -use crate::util::errors::CargoResultExt; use crate::util::interning::InternedString; use crate::util::toml::{ProfilePackageSpec, StringOrBool, TomlProfile, TomlProfiles, U32OrBool}; use crate::util::{closest_msg, config, CargoResult, Config}; -use anyhow::bail; +use anyhow::{bail, Context as _}; use std::collections::{BTreeMap, HashMap, HashSet}; use std::hash::Hash; use std::{cmp, env, fmt, hash}; @@ -1142,11 +1141,10 @@ fn get_config_profile(ws: &Workspace<'_>, name: &str) -> CargoResult PackageRegistry<'cfg> { // normally would and then ask it directly for the list of summaries // corresponding to this `dep`. self.ensure_loaded(dep.source_id(), Kind::Normal) - .chain_err(|| { - anyhow::format_err!( + .with_context(|| { + format!( "failed to load source for dependency `{}`", dep.package_name() ) @@ -293,14 +293,16 @@ impl<'cfg> PackageRegistry<'cfg> { .get_mut(dep.source_id()) .expect("loaded source not present"); let summaries = source.query_vec(dep)?; - let (summary, should_unlock) = - summary_for_patch(orig_patch, locked, summaries, source).chain_err(|| { - format!( - "patch for `{}` in `{}` failed to resolve", - orig_patch.package_name(), - url, - ) - })?; + let (summary, should_unlock) = summary_for_patch( + orig_patch, locked, summaries, source, + ) + .with_context(|| { + format!( + "patch for `{}` in `{}` failed to resolve", + orig_patch.package_name(), + url, + ) + })?; debug!( "patch summary is {:?} should_unlock={:?}", summary, should_unlock @@ -320,7 +322,7 @@ impl<'cfg> PackageRegistry<'cfg> { Ok(summary) }) .collect::>>() - .chain_err(|| anyhow::format_err!("failed to resolve patches for `{}`", url))?; + .with_context(|| format!("failed to resolve patches for `{}`", url))?; let mut name_and_version = HashSet::new(); for summary in unlocked_summaries.iter() { @@ -388,7 +390,7 @@ impl<'cfg> PackageRegistry<'cfg> { let _p = profile::start(format!("updating: {}", source_id)); self.sources.get_mut(source_id).unwrap().update() })() - .chain_err(|| anyhow::format_err!("Unable to update {}", source_id))?; + .with_context(|| format!("Unable to update {}", source_id))?; Ok(()) } @@ -539,8 +541,8 @@ impl<'cfg> Registry for PackageRegistry<'cfg> { // Ensure the requested source_id is loaded self.ensure_loaded(dep.source_id(), Kind::Normal) - .chain_err(|| { - anyhow::format_err!( + .with_context(|| { + format!( "failed to load source for dependency `{}`", dep.package_name() ) diff --git a/src/cargo/core/resolver/dep_cache.rs b/src/cargo/core/resolver/dep_cache.rs index 063626639a2..91afa13f709 100644 --- a/src/cargo/core/resolver/dep_cache.rs +++ b/src/cargo/core/resolver/dep_cache.rs @@ -16,8 +16,10 @@ use crate::core::resolver::{ ActivateError, ActivateResult, CliFeatures, RequestedFeatures, ResolveOpts, }; use crate::core::{Dependency, FeatureValue, PackageId, PackageIdSpec, Registry, Summary}; -use crate::util::errors::{CargoResult, CargoResultExt}; +use crate::util::errors::CargoResult; use crate::util::interning::InternedString; + +use anyhow::Context as _; use log::debug; use std::cmp::Ordering; use std::collections::{BTreeSet, HashMap, HashSet}; @@ -222,8 +224,8 @@ impl<'a> RegistryQueryer<'a> { let mut deps = deps .into_iter() .map(|(dep, features)| { - let candidates = self.query(&dep).chain_err(|| { - anyhow::format_err!( + let candidates = self.query(&dep).with_context(|| { + format!( "failed to get `{}` as a dependency of {}", dep.package_name(), describe_path(&cx.parents.path_to_bottom(&candidate.package_id())), diff --git a/src/cargo/core/resolver/encode.rs b/src/cargo/core/resolver/encode.rs index 9b93a744980..19de1049ded 100644 --- a/src/cargo/core/resolver/encode.rs +++ b/src/cargo/core/resolver/encode.rs @@ -113,10 +113,10 @@ use super::{Resolve, ResolveVersion}; use crate::core::{Dependency, GitReference, Package, PackageId, SourceId, Workspace}; -use crate::util::errors::{CargoResult, CargoResultExt}; +use crate::util::errors::CargoResult; use crate::util::interning::InternedString; use crate::util::{internal, Graph}; -use anyhow::bail; +use anyhow::{bail, Context as _}; use log::debug; use serde::de; use serde::ser; @@ -333,7 +333,7 @@ impl EncodableResolve { let k = &k[prefix.len()..]; let enc_id: EncodablePackageId = k .parse() - .chain_err(|| internal("invalid encoding of checksum in lockfile"))?; + .with_context(|| internal("invalid encoding of checksum in lockfile"))?; let id = match lookup_id(&enc_id) { Some(id) => id, _ => continue, diff --git a/src/cargo/core/workspace.rs b/src/cargo/core/workspace.rs index fc5608c1ae8..d00c5e47e1c 100644 --- a/src/cargo/core/workspace.rs +++ b/src/cargo/core/workspace.rs @@ -5,7 +5,7 @@ use std::path::{Path, PathBuf}; use std::rc::Rc; use std::slice; -use anyhow::bail; +use anyhow::{bail, Context as _}; use glob::glob; use log::debug; use url::Url; @@ -18,7 +18,7 @@ use crate::core::{Dependency, Edition, FeatureValue, PackageId, PackageIdSpec}; use crate::core::{EitherManifest, Package, SourceId, VirtualManifest}; use crate::ops; use crate::sources::{PathSource, CRATES_IO_INDEX, CRATES_IO_REGISTRY}; -use crate::util::errors::{CargoResult, CargoResultExt, ManifestError}; +use crate::util::errors::{CargoResult, ManifestError}; use crate::util::interning::InternedString; use crate::util::toml::{read_manifest, TomlDependency, TomlProfiles}; use crate::util::{config::ConfigRelativePath, Config, Filesystem, IntoUrl}; @@ -386,7 +386,7 @@ impl<'cfg> Workspace<'cfg> { .config .get_registry_index(url) .or_else(|_| url.into_url()) - .chain_err(|| { + .with_context(|| { format!("[patch] entry `{}` should be a URL or registry name", url) })?, }; @@ -1415,12 +1415,9 @@ impl WorkspaceRootConfig { Some(p) => p, None => return Ok(Vec::new()), }; - let res = - glob(path).chain_err(|| anyhow::format_err!("could not parse pattern `{}`", &path))?; + let res = glob(path).with_context(|| format!("could not parse pattern `{}`", &path))?; let res = res - .map(|p| { - p.chain_err(|| anyhow::format_err!("unable to match path to pattern `{}`", &path)) - }) + .map(|p| p.with_context(|| format!("unable to match path to pattern `{}`", &path))) .collect::, _>>()?; Ok(res) } diff --git a/src/cargo/ops/cargo_clean.rs b/src/cargo/ops/cargo_clean.rs index ad2171e827b..76b6927519a 100644 --- a/src/cargo/ops/cargo_clean.rs +++ b/src/cargo/ops/cargo_clean.rs @@ -2,10 +2,12 @@ use crate::core::compiler::{CompileKind, CompileMode, Layout, RustcTargetData}; use crate::core::profiles::Profiles; use crate::core::{PackageIdSpec, TargetKind, Workspace}; use crate::ops; -use crate::util::errors::{CargoResult, CargoResultExt}; +use crate::util::errors::CargoResult; use crate::util::interning::InternedString; use crate::util::lev_distance; use crate::util::Config; + +use anyhow::Context as _; use cargo_util::paths; use std::fs; use std::path::Path; @@ -222,14 +224,12 @@ fn rm_rf(path: &Path, config: &Config) -> CargoResult<()> { config .shell() .verbose(|shell| shell.status("Removing", path.display()))?; - paths::remove_dir_all(path) - .chain_err(|| anyhow::format_err!("could not remove build directory"))?; + paths::remove_dir_all(path).with_context(|| "could not remove build directory")?; } else if m.is_ok() { config .shell() .verbose(|shell| shell.status("Removing", path.display()))?; - paths::remove_file(path) - .chain_err(|| anyhow::format_err!("failed to remove build artifact"))?; + paths::remove_file(path).with_context(|| "failed to remove build artifact")?; } Ok(()) } diff --git a/src/cargo/ops/cargo_install.rs b/src/cargo/ops/cargo_install.rs index 93276fa51b7..1df7e56f532 100644 --- a/src/cargo/ops/cargo_install.rs +++ b/src/cargo/ops/cargo_install.rs @@ -7,10 +7,11 @@ use crate::core::compiler::{CompileKind, DefaultExecutor, Executor, Freshness, U use crate::core::{Dependency, Edition, Package, PackageId, Source, SourceId, Workspace}; use crate::ops::common_for_install_and_uninstall::*; use crate::sources::{GitSource, PathSource, SourceConfigMap}; -use crate::util::errors::{CargoResult, CargoResultExt}; +use crate::util::errors::CargoResult; use crate::util::{Config, Filesystem, Rustc, ToSemver}; use crate::{drop_println, ops}; -use anyhow::{bail, format_err}; + +use anyhow::{bail, format_err, Context as _}; use cargo_util::paths; use semver::VersionReq; use tempfile::Builder as TempFileBuilder; @@ -350,13 +351,13 @@ fn install_one( check_yanked_install(&ws)?; let exec: Arc = Arc::new(DefaultExecutor); - let compile = ops::compile_ws(&ws, opts, &exec).chain_err(|| { + let compile = ops::compile_ws(&ws, opts, &exec).with_context(|| { if let Some(td) = td_opt.take() { // preserve the temporary directory, so the user can inspect it td.into_path(); } - format_err!( + format!( "failed to compile `{}`, intermediate artifacts can be \ found at `{}`", pkg, @@ -420,8 +421,8 @@ fn install_one( let src = staging_dir.path().join(bin); let dst = dst.join(bin); config.shell().status("Installing", dst.display())?; - fs::rename(&src, &dst).chain_err(|| { - format_err!("failed to move `{}` to `{}`", src.display(), dst.display()) + fs::rename(&src, &dst).with_context(|| { + format!("failed to move `{}` to `{}`", src.display(), dst.display()) })?; installed.bins.push(dst); successful_bins.insert(bin.to_string()); @@ -435,8 +436,8 @@ fn install_one( let src = staging_dir.path().join(bin); let dst = dst.join(bin); config.shell().status("Replacing", dst.display())?; - fs::rename(&src, &dst).chain_err(|| { - format_err!("failed to move `{}` to `{}`", src.display(), dst.display()) + fs::rename(&src, &dst).with_context(|| { + format!("failed to move `{}` to `{}`", src.display(), dst.display()) })?; successful_bins.insert(bin.to_string()); } @@ -463,7 +464,7 @@ fn install_one( } match tracker.save() { - Err(err) => replace_result.chain_err(|| err)?, + Err(err) => replace_result.with_context(|| err)?, Ok(_) => replace_result?, } } @@ -736,7 +737,7 @@ fn remove_orphaned_bins( ), )?; paths::remove_file(&full_path) - .chain_err(|| format!("failed to remove {:?}", full_path))?; + .with_context(|| format!("failed to remove {:?}", full_path))?; } } } diff --git a/src/cargo/ops/cargo_new.rs b/src/cargo/ops/cargo_new.rs index c25c016c056..64b1d3620af 100644 --- a/src/cargo/ops/cargo_new.rs +++ b/src/cargo/ops/cargo_new.rs @@ -1,7 +1,8 @@ use crate::core::{Edition, Shell, Workspace}; -use crate::util::errors::{CargoResult, CargoResultExt}; +use crate::util::errors::CargoResult; use crate::util::{existing_vcs_repo, FossilRepo, GitRepo, HgRepo, PijulRepo}; use crate::util::{restricted_names, Config}; +use anyhow::Context as _; use cargo_util::paths; use serde::de; use serde::Deserialize; @@ -416,8 +417,8 @@ pub fn new(opts: &NewOptions, config: &Config) -> CargoResult<()> { registry: opts.registry.as_deref(), }; - mk(config, &mkopts).chain_err(|| { - anyhow::format_err!( + mk(config, &mkopts).with_context(|| { + format!( "Failed to create package `{}` at `{}`", name, path.display() @@ -500,8 +501,8 @@ pub fn init(opts: &NewOptions, config: &Config) -> CargoResult<()> { registry: opts.registry.as_deref(), }; - mk(config, &mkopts).chain_err(|| { - anyhow::format_err!( + mk(config, &mkopts).with_context(|| { + format!( "Failed to create package `{}` at `{}`", name, path.display() diff --git a/src/cargo/ops/cargo_package.rs b/src/cargo/ops/cargo_package.rs index fd37e2c730e..1056d73fdaa 100644 --- a/src/cargo/ops/cargo_package.rs +++ b/src/cargo/ops/cargo_package.rs @@ -11,10 +11,11 @@ use crate::core::resolver::CliFeatures; use crate::core::{Feature, Shell, Verbosity, Workspace}; use crate::core::{Package, PackageId, PackageSet, Resolve, Source, SourceId}; use crate::sources::PathSource; -use crate::util::errors::{CargoResult, CargoResultExt}; +use crate::util::errors::CargoResult; use crate::util::toml::TomlManifest; use crate::util::{self, restricted_names, Config, FileLock}; use crate::{drop_println, ops}; +use anyhow::Context as _; use cargo_util::paths; use flate2::read::GzDecoder; use flate2::{Compression, GzBuilder}; @@ -122,17 +123,17 @@ pub fn package(ws: &Workspace<'_>, opts: &PackageOpts<'_>) -> CargoResult