Skip to content

Commit 163097c

Browse files
committed
Auto merge of #9367 - weihanglo:refactor/remove-CargoResultExt, r=alexcrichton
refactor: remove `CargoResultExt` All `chain_err` -> `with_context` are done by IDE refactoring. - Remove `CargoResultExt`. - Call `format!` instead of `anyhow::format_err!` to reduce unnecessary macro expansions. https://github.com/rust-lang/cargo/blob/e870eac9967b132825116525476d6875c305e4d8/src/cargo/util/errors.rs#L12-L18
2 parents 57b7597 + 9099b49 commit 163097c

Some content is hidden

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

42 files changed

+282
-282
lines changed

src/bin/cargo/commands/describe_future_incompatibilities.rs

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,7 @@
11
use crate::command_prelude::*;
2-
use anyhow::anyhow;
2+
use anyhow::{anyhow, Context as _};
33
use cargo::core::compiler::future_incompat::{OnDiskReport, FUTURE_INCOMPAT_FILE};
44
use cargo::drop_eprint;
5-
use cargo::util::CargoResultExt;
65
use std::io::Read;
76

87
pub fn cli() -> App {
@@ -37,9 +36,9 @@ pub fn exec(config: &mut Config, args: &ArgMatches<'_>) -> CliResult {
3736
report_file
3837
.file()
3938
.read_to_string(&mut file_contents)
40-
.chain_err(|| "failed to read report")?;
39+
.with_context(|| "failed to read report")?;
4140
let on_disk_report: OnDiskReport =
42-
serde_json::from_str(&file_contents).chain_err(|| "failed to load report")?;
41+
serde_json::from_str(&file_contents).with_context(|| "failed to load report")?;
4342

4443
let id = args.value_of("id").unwrap();
4544
if id != on_disk_report.id {

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

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,8 @@ use crate::core::compiler::{
33
};
44
use crate::core::{Dependency, Target, TargetKind, Workspace};
55
use crate::util::config::{Config, StringList, TargetConfig};
6-
use crate::util::{CargoResult, CargoResultExt, Rustc};
6+
use crate::util::{CargoResult, Rustc};
7+
use anyhow::Context as _;
78
use cargo_platform::{Cfg, CfgExpr};
89
use cargo_util::{paths, ProcessBuilder};
910
use serde::{Deserialize, Serialize};
@@ -176,7 +177,7 @@ impl TargetInfo {
176177

177178
let (output, error) = rustc
178179
.cached_output(&process, extra_fingerprint)
179-
.chain_err(|| "failed to run `rustc` to learn about target-specific information")?;
180+
.with_context(|| "failed to run `rustc` to learn about target-specific information")?;
180181

181182
let mut lines = output.lines();
182183
let mut map = HashMap::new();
@@ -212,7 +213,7 @@ impl TargetInfo {
212213
.map(|line| Ok(Cfg::from_str(line)?))
213214
.filter(TargetInfo::not_user_specific_cfg)
214215
.collect::<CargoResult<Vec<_>>>()
215-
.chain_err(|| {
216+
.with_context(|| {
216217
format!(
217218
"failed to parse the cfg from `rustc --print=cfg`, got:\n{}",
218219
output
@@ -413,7 +414,7 @@ impl TargetInfo {
413414

414415
process.arg("--crate-type").arg(crate_type.as_str());
415416

416-
let output = process.exec_with_output().chain_err(|| {
417+
let output = process.exec_with_output().with_context(|| {
417418
format!(
418419
"failed to run `rustc` to learn about crate-type {} information",
419420
crate_type

src/cargo/core/compiler/compile_kind.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
use crate::core::Target;
2-
use crate::util::errors::{CargoResult, CargoResultExt};
2+
use crate::util::errors::CargoResult;
33
use crate::util::interning::InternedString;
44
use crate::util::{Config, StableHasher};
5-
use anyhow::bail;
5+
use anyhow::{bail, Context as _};
66
use serde::Serialize;
77
use std::collections::BTreeSet;
88
use std::fs;
@@ -143,7 +143,7 @@ impl CompileTarget {
143143
// with different paths always produce the same result.
144144
let path = Path::new(name)
145145
.canonicalize()
146-
.chain_err(|| anyhow::format_err!("target path {:?} is not a valid file", name))?;
146+
.with_context(|| format!("target path {:?} is not a valid file", name))?;
147147

148148
let name = path
149149
.into_os_string()

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

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,14 @@ use std::collections::{BTreeSet, HashMap, HashSet};
22
use std::path::{Path, PathBuf};
33
use std::sync::{Arc, Mutex};
44

5+
use anyhow::Context as _;
56
use filetime::FileTime;
67
use jobserver::Client;
78

89
use crate::core::compiler::compilation::{self, UnitOutput};
910
use crate::core::compiler::{self, Unit};
1011
use crate::core::PackageId;
11-
use crate::util::errors::{CargoResult, CargoResultExt};
12+
use crate::util::errors::CargoResult;
1213
use crate::util::profile;
1314

1415
use super::build_plan::BuildPlan;
@@ -96,7 +97,7 @@ impl<'a, 'cfg> Context<'a, 'cfg> {
9697
Some(c) => c.clone(),
9798
None => {
9899
let client = Client::new(bcx.build_config.jobs as usize)
99-
.chain_err(|| "failed to create jobserver")?;
100+
.with_context(|| "failed to create jobserver")?;
100101
client.acquire_raw()?;
101102
client
102103
}
@@ -324,11 +325,11 @@ impl<'a, 'cfg> Context<'a, 'cfg> {
324325
self.files_mut()
325326
.host
326327
.prepare()
327-
.chain_err(|| "couldn't prepare build directories")?;
328+
.with_context(|| "couldn't prepare build directories")?;
328329
for target in self.files.as_mut().unwrap().target.values_mut() {
329330
target
330331
.prepare()
331-
.chain_err(|| "couldn't prepare build directories")?;
332+
.with_context(|| "couldn't prepare build directories")?;
332333
}
333334

334335
let files = self.files.as_ref().unwrap();
@@ -559,11 +560,11 @@ impl<'a, 'cfg> Context<'a, 'cfg> {
559560

560561
pub fn new_jobserver(&mut self) -> CargoResult<Client> {
561562
let tokens = self.bcx.build_config.jobs as usize;
562-
let client = Client::new(tokens).chain_err(|| "failed to create jobserver")?;
563+
let client = Client::new(tokens).with_context(|| "failed to create jobserver")?;
563564

564565
// Drain the client fully
565566
for i in 0..tokens {
566-
client.acquire_raw().chain_err(|| {
567+
client.acquire_raw().with_context(|| {
567568
format!(
568569
"failed to fully drain {}/{} token from jobserver at startup",
569570
i, tokens,

src/cargo/core/compiler/custom_build.rs

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,11 @@ use super::{fingerprint, Context, LinkType, Unit};
33
use crate::core::compiler::context::Metadata;
44
use crate::core::compiler::job_queue::JobState;
55
use crate::core::{profiles::ProfileRoot, PackageId};
6-
use crate::util::errors::{CargoResult, CargoResultExt};
6+
use crate::util::errors::CargoResult;
77
use crate::util::interning::InternedString;
88
use crate::util::machine_message::{self, Message};
99
use crate::util::{internal, profile};
10+
use anyhow::Context as _;
1011
use cargo_platform::Cfg;
1112
use cargo_util::paths;
1213
use std::collections::hash_map::{Entry, HashMap};
@@ -308,7 +309,7 @@ fn build_work(cx: &mut Context<'_, '_>, unit: &Unit) -> CargoResult<Job> {
308309
// If we have an old build directory, then just move it into place,
309310
// otherwise create it!
310311
paths::create_dir_all(&script_out_dir)
311-
.chain_err(|| "failed to create script output directory for build command")?;
312+
.with_context(|| "failed to create script output directory for build command")?;
312313

313314
// For all our native lib dependencies, pick up their metadata to pass
314315
// 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> {
370371
},
371372
true,
372373
)
373-
.chain_err(|| format!("failed to run custom build command for `{}`", pkg_descr));
374+
.with_context(|| format!("failed to run custom build command for `{}`", pkg_descr));
374375

375376
if let Err(error) = output {
376377
insert_warnings_in_build_outputs(

src/cargo/core/compiler/fingerprint.rs

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -321,7 +321,7 @@ use std::str;
321321
use std::sync::{Arc, Mutex};
322322
use std::time::SystemTime;
323323

324-
use anyhow::{bail, format_err};
324+
use anyhow::{bail, format_err, Context as _};
325325
use cargo_util::{paths, ProcessBuilder};
326326
use filetime::FileTime;
327327
use log::{debug, info};
@@ -332,7 +332,7 @@ use serde::{Deserialize, Serialize};
332332
use crate::core::compiler::unit_graph::UnitDep;
333333
use crate::core::Package;
334334
use crate::util;
335-
use crate::util::errors::{CargoResult, CargoResultExt};
335+
use crate::util::errors::CargoResult;
336336
use crate::util::interning::InternedString;
337337
use crate::util::{internal, path_args, profile};
338338
use crate::CARGO_ENV;
@@ -1311,7 +1311,7 @@ fn calculate_normal(cx: &mut Context<'_, '_>, unit: &Unit) -> CargoResult<Finger
13111311
let target_root = target_root(cx);
13121312
let local = if unit.mode.is_doc() {
13131313
// rustdoc does not have dep-info files.
1314-
let fingerprint = pkg_fingerprint(cx.bcx, &unit.pkg).chain_err(|| {
1314+
let fingerprint = pkg_fingerprint(cx.bcx, &unit.pkg).with_context(|| {
13151315
format!(
13161316
"failed to determine package fingerprint for documenting {}",
13171317
unit.pkg
@@ -1400,7 +1400,7 @@ fn calculate_run_custom_build(cx: &mut Context<'_, '_>, unit: &Unit) -> CargoRes
14001400
let local = (gen_local)(
14011401
deps,
14021402
Some(&|| {
1403-
pkg_fingerprint(cx.bcx, &unit.pkg).chain_err(|| {
1403+
pkg_fingerprint(cx.bcx, &unit.pkg).with_context(|| {
14041404
format!(
14051405
"failed to determine package fingerprint for build script for {}",
14061406
unit.pkg
@@ -1668,7 +1668,7 @@ fn compare_old_fingerprint(
16681668

16691669
let old_fingerprint_json = paths::read(&loc.with_extension("json"))?;
16701670
let old_fingerprint: Fingerprint = serde_json::from_str(&old_fingerprint_json)
1671-
.chain_err(|| internal("failed to deserialize json"))?;
1671+
.with_context(|| internal("failed to deserialize json"))?;
16721672
// Fingerprint can be empty after a failed rebuild (see comment in prepare_target).
16731673
if !old_fingerprint_short.is_empty() {
16741674
debug_assert_eq!(util::to_hex(old_fingerprint.hash()), old_fingerprint_short);

src/cargo/core/compiler/job_queue.rs

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@ use std::marker;
5656
use std::sync::Arc;
5757
use std::time::Duration;
5858

59-
use anyhow::format_err;
59+
use anyhow::{format_err, Context as _};
6060
use cargo_util::ProcessBuilder;
6161
use crossbeam_utils::thread::Scope;
6262
use jobserver::{Acquired, Client, HelperThread};
@@ -78,8 +78,8 @@ use crate::core::{PackageId, Shell, TargetKind};
7878
use crate::drop_eprint;
7979
use crate::util::diagnostic_server::{self, DiagnosticPrinter};
8080
use crate::util::machine_message::{self, Message as _};
81+
use crate::util::CargoResult;
8182
use crate::util::{self, internal, profile};
82-
use crate::util::{CargoResult, CargoResultExt};
8383
use crate::util::{Config, DependencyQueue, Progress, ProgressStyle, Queue};
8484

8585
/// This structure is backed by the `DependencyQueue` type and manages the
@@ -440,7 +440,7 @@ impl<'cfg> JobQueue<'cfg> {
440440
.into_helper_thread(move |token| {
441441
messages.push(Message::Token(token));
442442
})
443-
.chain_err(|| "failed to create helper thread for jobserver management")?;
443+
.with_context(|| "failed to create helper thread for jobserver management")?;
444444

445445
// Create a helper thread to manage the diagnostics for rustfix if
446446
// necessary.
@@ -537,7 +537,7 @@ impl<'cfg> DrainState<'cfg> {
537537
.push(token);
538538
client
539539
.release_raw()
540-
.chain_err(|| "failed to release jobserver token")?;
540+
.with_context(|| "failed to release jobserver token")?;
541541
}
542542

543543
Ok(())
@@ -617,7 +617,7 @@ impl<'cfg> DrainState<'cfg> {
617617
.push(FutureIncompatReportCrate { package_id, report });
618618
}
619619
Message::Token(acquired_token) => {
620-
let token = acquired_token.chain_err(|| "failed to acquire jobserver token")?;
620+
let token = acquired_token.with_context(|| "failed to acquire jobserver token")?;
621621
self.tokens.push(token);
622622
}
623623
Message::NeedsToken(id) => {

src/cargo/core/compiler/mod.rs

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ use std::io::{BufRead, Write};
2828
use std::path::{Path, PathBuf};
2929
use std::sync::Arc;
3030

31-
use anyhow::Error;
31+
use anyhow::{Context as _, Error};
3232
use lazycell::LazyCell;
3333
use log::debug;
3434

@@ -54,7 +54,7 @@ pub use crate::core::compiler::unit::{Unit, UnitInterner};
5454
use crate::core::manifest::TargetSourcePath;
5555
use crate::core::profiles::{PanicStrategy, Profile, Strip};
5656
use crate::core::{Feature, PackageId, Target};
57-
use crate::util::errors::{CargoResult, CargoResultExt, VerboseError};
57+
use crate::util::errors::{CargoResult, VerboseError};
5858
use crate::util::interning::InternedString;
5959
use crate::util::machine_message::{self, Message};
6060
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
331331
},
332332
)
333333
.map_err(verbose_if_simple_exit_code)
334-
.chain_err(|| format!("could not compile `{}`", name))?;
334+
.with_context(|| format!("could not compile `{}`", name))?;
335335
}
336336

337337
if rustc_dep_info_loc.exists() {
@@ -345,7 +345,7 @@ fn rustc(cx: &mut Context<'_, '_>, unit: &Unit, exec: &Arc<dyn Executor>) -> Car
345345
// Do not track source files in the fingerprint for registry dependencies.
346346
is_local,
347347
)
348-
.chain_err(|| {
348+
.with_context(|| {
349349
internal(format!(
350350
"could not parse/generate dep info at: {}",
351351
rustc_dep_info_loc.display()
@@ -665,7 +665,7 @@ fn rustdoc(cx: &mut Context<'_, '_>, unit: &Unit) -> CargoResult<Work> {
665665
},
666666
false,
667667
)
668-
.chain_err(|| format!("could not document `{}`", name))?;
668+
.with_context(|| format!("could not document `{}`", name))?;
669669
Ok(())
670670
}))
671671
}

src/cargo/core/compiler/timings.rs

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,8 @@ use crate::core::compiler::BuildContext;
88
use crate::core::PackageId;
99
use crate::util::cpu::State;
1010
use crate::util::machine_message::{self, Message};
11-
use crate::util::{CargoResult, CargoResultExt, Config};
11+
use crate::util::{CargoResult, Config};
12+
use anyhow::Context as _;
1213
use cargo_util::paths;
1314
use std::collections::HashMap;
1415
use std::io::{BufWriter, Write};
@@ -324,7 +325,7 @@ impl<'cfg> Timings<'cfg> {
324325
.sort_unstable_by(|a, b| a.start.partial_cmp(&b.start).unwrap());
325326
if self.report_html {
326327
self.report_html(bcx, error)
327-
.chain_err(|| "failed to save timing report")?;
328+
.with_context(|| "failed to save timing report")?;
328329
}
329330
Ok(())
330331
}

src/cargo/core/dependency.rs

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
use anyhow::Context as _;
12
use cargo_platform::Platform;
23
use log::trace;
34
use semver::ReqParseError;
@@ -8,7 +9,7 @@ use std::path::PathBuf;
89
use std::rc::Rc;
910

1011
use crate::core::{PackageId, SourceId, Summary};
11-
use crate::util::errors::{CargoResult, CargoResultExt};
12+
use crate::util::errors::CargoResult;
1213
use crate::util::interning::InternedString;
1314
use crate::util::Config;
1415

@@ -132,7 +133,7 @@ this warning.
132133
}
133134
Err(e) => {
134135
let err: CargoResult<VersionReq> = Err(e.into());
135-
let v: VersionReq = err.chain_err(|| {
136+
let v: VersionReq = err.with_context(|| {
136137
format!(
137138
"failed to parse the version requirement `{}` for dependency `{}`",
138139
req, name

0 commit comments

Comments
 (0)