Skip to content

Commit

Permalink
refactor: remove CargoResultExt
Browse files Browse the repository at this point in the history
weihanglo committed Apr 16, 2021

Verified

This commit was signed with the committer’s verified signature. The key has expired.
weihanglo Weihang Lo
1 parent e870eac commit ebca519
Showing 42 changed files with 268 additions and 256 deletions.
7 changes: 3 additions & 4 deletions src/bin/cargo/commands/describe_future_incompatibilities.rs
Original file line number Diff line number Diff line change
@@ -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 {
9 changes: 5 additions & 4 deletions src/cargo/core/compiler/build_context/target_info.rs
Original file line number Diff line number Diff line change
@@ -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::<CargoResult<Vec<_>>>()
.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
6 changes: 3 additions & 3 deletions src/cargo/core/compiler/compile_kind.rs
Original file line number Diff line number Diff line change
@@ -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(|| anyhow::format_err!("target path {:?} is not a valid file", name))?;

let name = path
.into_os_string()
13 changes: 7 additions & 6 deletions src/cargo/core/compiler/context/mod.rs
Original file line number Diff line number Diff line change
@@ -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<Client> {
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,
7 changes: 4 additions & 3 deletions src/cargo/core/compiler/custom_build.rs
Original file line number Diff line number Diff line change
@@ -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<Job> {
// 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<Job> {
},
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(
10 changes: 5 additions & 5 deletions src/cargo/core/compiler/fingerprint.rs
Original file line number Diff line number Diff line change
@@ -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<Finger
let target_root = target_root(cx);
let local = if unit.mode.is_doc() {
// rustdoc does not have dep-info files.
let fingerprint = pkg_fingerprint(cx.bcx, &unit.pkg).chain_err(|| {
let fingerprint = pkg_fingerprint(cx.bcx, &unit.pkg).with_context(|| {
format!(
"failed to determine package fingerprint for documenting {}",
unit.pkg
@@ -1375,7 +1375,7 @@ fn calculate_run_custom_build(cx: &mut Context<'_, '_>, 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);
10 changes: 5 additions & 5 deletions src/cargo/core/compiler/job_queue.rs
Original file line number Diff line number Diff line change
@@ -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) => {
10 changes: 5 additions & 5 deletions src/cargo/core/compiler/mod.rs
Original file line number Diff line number Diff line change
@@ -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<dyn Executor>) -> 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<dyn Executor>) -> 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<Work> {
},
false,
)
.chain_err(|| format!("could not document `{}`", name))?;
.with_context(|| format!("could not document `{}`", name))?;
Ok(())
}))
}
5 changes: 3 additions & 2 deletions src/cargo/core/compiler/timings.rs
Original file line number Diff line number Diff line change
@@ -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(())
}
5 changes: 3 additions & 2 deletions src/cargo/core/dependency.rs
Original file line number Diff line number Diff line change
@@ -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<VersionReq> = 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
3 changes: 2 additions & 1 deletion src/cargo/core/manifest.rs
Original file line number Diff line number Diff line change
@@ -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,7 +497,7 @@ impl Manifest {
if self.im_a_teapot.is_some() {
self.unstable_features
.require(Feature::test_dummy_unstable())
.chain_err(|| {
.with_context(|| {
anyhow::format_err!(
"the `im-a-teapot` manifest key is unstable and may \
not work properly in England"
Loading

0 comments on commit ebca519

Please sign in to comment.