Skip to content

Commit

Permalink
switch to color-eyre
Browse files Browse the repository at this point in the history
color-eyre has much nicer error displays.
  • Loading branch information
sunshowers committed Dec 17, 2021
1 parent 44b62fa commit fdcc0c4
Show file tree
Hide file tree
Showing 15 changed files with 88 additions and 70 deletions.
9 changes: 5 additions & 4 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion cargo-guppy/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,9 @@ license = "MIT OR Apache-2.0"
edition = "2018"

[dependencies]
anyhow = "1.0.44"
camino = "1.0.5"
# disable tracing integration since we don't use it
color-eyre = { version = "0.5.11", default-features = false }
clap = "2.33.3"
dialoguer = "0.9.0"
guppy = { version = "0.12.0", path = "../guppy", features = ["summaries"] }
Expand Down
13 changes: 5 additions & 8 deletions cargo-guppy/src/core.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@

//! Implementations for options shared by commands.

use anyhow::{anyhow, ensure, Context};
use clap::arg_enum;
use color_eyre::eyre::{ensure, eyre, Result, WrapErr};
use guppy::{
graph::{DependencyDirection, DependencyReq, PackageGraph, PackageLink, PackageQuery},
platform::EnabledTernary,
Expand Down Expand Up @@ -50,10 +50,7 @@ pub struct QueryOptions {

impl QueryOptions {
/// Constructs a `PackageQuery` based on these options.
pub fn apply<'g>(
&self,
pkg_graph: &'g PackageGraph,
) -> Result<PackageQuery<'g>, anyhow::Error> {
pub fn apply<'g>(&self, pkg_graph: &'g PackageGraph) -> Result<PackageQuery<'g>> {
if !self.roots.is_empty() {
// NOTE: The root set packages are specified by name. The tool currently
// does not handle multiple version of the same package as the current use
Expand All @@ -64,7 +61,7 @@ impl QueryOptions {
} else {
ensure!(
self.direction == DependencyDirection::Forward,
anyhow!("--query-reverse requires roots to be specified")
eyre!("--query-reverse requires roots to be specified")
);
Ok(pkg_graph.query_workspace())
}
Expand Down Expand Up @@ -122,12 +119,12 @@ impl FilterOptions {
pub fn make_resolver<'g>(
&'g self,
pkg_graph: &'g PackageGraph,
) -> anyhow::Result<impl Fn(&PackageQuery<'g>, PackageLink<'g>) -> bool + 'g> {
) -> Result<impl Fn(&PackageQuery<'g>, PackageLink<'g>) -> bool + 'g> {
let omitted_package_ids: HashSet<_> =
self.base_opts.omitted_package_ids(pkg_graph).collect();

let platform_spec = string_to_platform_spec(self.target.as_deref())
.with_context(|| "target platform isn't known")?;
.wrap_err_with(|| "target platform isn't known")?;

let ret = move |_: &PackageQuery<'g>, link| {
// filter by the kind of dependency (--kind)
Expand Down
23 changes: 12 additions & 11 deletions cargo-guppy/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,8 @@ mod mv;

pub use crate::{core::*, mv::*};

use anyhow::{bail, Context, Result};
use clap::arg_enum;
use color_eyre::eyre::{bail, Result, WrapErr};
use guppy::{
graph::{
cargo::{CargoOptions, CargoSet},
Expand All @@ -68,7 +68,7 @@ use std::{
};
use structopt::StructOpt;

pub fn cmd_diff(json: bool, old: &str, new: &str) -> Result<(), anyhow::Error> {
pub fn cmd_diff(json: bool, old: &str, new: &str) -> Result<()> {
let old_json = fs::read_to_string(old)?;
let new_json = fs::read_to_string(new)?;

Expand Down Expand Up @@ -103,14 +103,14 @@ pub struct DiffSummariesOptions {
impl DiffSummariesOptions {
pub fn exec(&self) -> Result<()> {
let old_summary = fs::read_to_string(&self.old)
.with_context(|| format!("reading old summary {} failed", self.old.display()))?;
.wrap_err_with(|| format!("reading old summary {} failed", self.old.display()))?;
let old_summary = Summary::parse(&old_summary)
.with_context(|| format!("parsing old summary {} failed", self.old.display()))?;
.wrap_err_with(|| format!("parsing old summary {} failed", self.old.display()))?;

let new_summary = fs::read_to_string(&self.new)
.with_context(|| format!("reading new summary {} failed", self.new.display()))?;
.wrap_err_with(|| format!("reading new summary {} failed", self.new.display()))?;
let new_summary = Summary::parse(&new_summary)
.with_context(|| format!("parsing new summary {} failed", self.new.display()))?;
.wrap_err_with(|| format!("parsing new summary {} failed", self.new.display()))?;

let diff = old_summary.diff(&new_summary);

Expand All @@ -133,7 +133,7 @@ pub struct DupsOptions {
metadata_opts: CargoMetadataOptions,
}

pub fn cmd_dups(opts: &DupsOptions) -> Result<(), anyhow::Error> {
pub fn cmd_dups(opts: &DupsOptions) -> Result<()> {
let command = opts.metadata_opts.make_command();
let pkg_graph = command.build_graph()?;

Expand Down Expand Up @@ -203,7 +203,7 @@ pub struct ResolveCargoOptions {
metadata_opts: CargoMetadataOptions,
}

pub fn cmd_resolve_cargo(opts: &ResolveCargoOptions) -> Result<(), anyhow::Error> {
pub fn cmd_resolve_cargo(opts: &ResolveCargoOptions) -> Result<()> {
let target_platform = string_to_platform_spec(opts.target_platform.as_deref())?;
let host_platform = string_to_platform_spec(opts.host_platform.as_deref())?;
let command = opts.metadata_opts.make_command();
Expand Down Expand Up @@ -318,8 +318,9 @@ pub struct CmdSelectOptions {
metadata_opts: CargoMetadataOptions,
}

pub fn cmd_select(options: &CmdSelectOptions) -> Result<(), anyhow::Error> {
let command = options.metadata_opts.make_command();
pub fn cmd_select(options: &CmdSelectOptions) -> Result<()> {
let mut command = options.metadata_opts.make_command();
command.other_options(["--no-deps"]);
let pkg_graph = command.build_graph()?;

let query = options.query_opts.apply(&pkg_graph)?;
Expand Down Expand Up @@ -366,7 +367,7 @@ pub struct SubtreeSizeOptions {
metadata_opts: CargoMetadataOptions,
}

pub fn cmd_subtree_size(options: &SubtreeSizeOptions) -> Result<(), anyhow::Error> {
pub fn cmd_subtree_size(options: &SubtreeSizeOptions) -> Result<()> {
let command = options.metadata_opts.make_command();
let pkg_graph = command.build_graph()?;

Expand Down
4 changes: 3 additions & 1 deletion cargo-guppy/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
// Copyright (c) The cargo-guppy Contributors
// SPDX-License-Identifier: MIT OR Apache-2.0

use anyhow::Result;
use cargo_guppy::{
CmdSelectOptions, DiffSummariesOptions, DupsOptions, MvOptions, ResolveCargoOptions,
SubtreeSizeOptions,
};
use color_eyre::Result;
use structopt::StructOpt;

#[derive(Debug, StructOpt)]
Expand Down Expand Up @@ -76,6 +76,8 @@ fn args() -> impl Iterator<Item = String> {
}

fn main() -> Result<()> {
color_eyre::install()?;

let args = Args::from_iter(args());

match args.cmd {
Expand Down
48 changes: 23 additions & 25 deletions cargo-guppy/src/mv.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
// Copyright (c) The cargo-guppy Contributors
// SPDX-License-Identifier: MIT OR Apache-2.0

use anyhow::{anyhow, bail, Context, Result};
use camino::{Utf8Path, Utf8PathBuf};
use color_eyre::eyre::{bail, eyre, Result, WrapErr};
use dialoguer::Confirm;
use guppy::graph::{PackageGraph, PackageLink, PackageMetadata};
use guppy_cmdlib::CargoMetadataOptions;
Expand Down Expand Up @@ -150,7 +150,7 @@ impl MvOptions {
// Next, update the root manifest. Do this before moving directories because this relies
// on the old directories existing.
update_root_toml(workspace_root, &src_moves)
.with_context(|| anyhow!("error while updating root toml at {}", workspace_root))?;
.wrap_err_with(|| eyre!("error while updating root toml at {}", workspace_root))?;

// Finally, move directories into their new spots.
// Rely on the fact that BTreeMap is sorted so that "foo" always shows up before
Expand All @@ -172,8 +172,8 @@ impl MvOptions {
);
// fs::rename behaves differently on Unix and Windows if the destination exists.
// But we don't expect it to, as the assertion above checks.
fs::rename(&abs_src, &abs_dest).with_context(|| {
anyhow!("renaming {} to {} failed", src_dir, package_move.new_path)
fs::rename(&abs_src, &abs_dest).wrap_err_with(|| {
eyre!("renaming {} to {} failed", src_dir, package_move.new_path)
})?;
done.insert(src_dir);
}
Expand Down Expand Up @@ -209,10 +209,10 @@ impl DestDir {
// Canonicalize the parent, then glue the last component to it.
let last_component = dest_dir
.file_name()
.with_context(|| anyhow!("destination {} cannot end with ..", dest_dir))?;
.ok_or_else(|| eyre!("destination {} cannot end with ..", dest_dir))?;
let parent = dest_dir
.parent()
.with_context(|| anyhow!("destination {} cannot be /", dest_dir))?;
.ok_or_else(|| eyre!("destination {} cannot end with ..", dest_dir))?;
let parent = if parent.as_os_str() == "" {
Utf8Path::new(".")
} else {
Expand All @@ -222,9 +222,7 @@ impl DestDir {
let parent = canonicalize_dir(pkg_graph, parent)?;
Ok(DestDir::Create(parent.join(last_component)))
}
Err(err) => {
Err(err).with_context(|| anyhow!("reading destination {} failed", dest_dir))
}
Err(err) => Err(err).wrap_err_with(|| eyre!("reading destination {} failed", dest_dir)),
}
}

Expand Down Expand Up @@ -272,7 +270,7 @@ fn canonicalize_dir(pkg_graph: &PackageGraph, path: impl AsRef<Utf8Path>) -> Res
let path = path.as_ref();
let canonical_path = path
.canonicalize()
.with_context(|| anyhow!("reading path {} failed", path))?;
.wrap_err_with(|| eyre!("reading path {} failed", path))?;
if !canonical_path.is_dir() {
bail!("path {} is not a directory", canonical_path.display());
}
Expand All @@ -281,15 +279,15 @@ fn canonicalize_dir(pkg_graph: &PackageGraph, path: impl AsRef<Utf8Path>) -> Res
}

fn rel_path<'a>(path: &'a Path, workspace_root: &Utf8Path) -> Result<&'a Utf8Path> {
let rel_path = path.strip_prefix(workspace_root).with_context(|| {
anyhow!(
let rel_path = path.strip_prefix(workspace_root).wrap_err_with(|| {
eyre!(
"path {} not in workspace root {}",
path.display(),
workspace_root
)
})?;
Utf8Path::from_path(rel_path)
.ok_or_else(|| anyhow!("rel path {} is invalid UTF-8", rel_path.display()))
.ok_or_else(|| eyre!("rel path {} is invalid UTF-8", rel_path.display()))
}

fn moves_for<'g: 'a, 'a>(
Expand Down Expand Up @@ -382,7 +380,7 @@ fn apply_edits(manifest_path: &Utf8Path, edits: &[ManifestEdit<'_>]) -> Result<(
// * [target.'foo'.dependencies], .build-dependencies and .dev-dependencies
for edit in edits {
apply_edit(table, edit)
.with_context(|| anyhow!("error while applying edits to {}", manifest_path))?;
.wrap_err_with(|| eyre!("error while applying edits to {}", manifest_path))?;
for target in &all_targets {
let target_table = match &mut table["target"][target] {
Item::Table(target_table) => target_table,
Expand All @@ -391,8 +389,8 @@ fn apply_edits(manifest_path: &Utf8Path, edits: &[ManifestEdit<'_>]) -> Result<(
continue;
}
};
apply_edit(target_table, edit).with_context(|| {
anyhow!(
apply_edit(target_table, edit).wrap_err_with(|| {
eyre!(
"error while applying edits to {}, section [target.'{}']",
manifest_path,
target
Expand All @@ -402,7 +400,7 @@ fn apply_edits(manifest_path: &Utf8Path, edits: &[ManifestEdit<'_>]) -> Result<(
}

fs::write(manifest_path, document.to_string())
.with_context(|| anyhow!("error while writing manifest {}", manifest_path))?;
.wrap_err_with(|| eyre!("error while writing manifest {}", manifest_path))?;

Ok(())
}
Expand All @@ -428,7 +426,7 @@ fn apply_edit(table: &mut Table, edit: &ManifestEdit<'_>) -> Result<()> {
match section_table.get_mut(dep_name) {
Some(item) => {
let dep_table = item.as_table_like_mut().ok_or_else(|| {
anyhow!("in section [{}], {} is not a table", section_name, dep_name)
eyre!("in section [{}], {} is not a table", section_name, dep_name)
})?;
// The dep table should have a path entry.
match dep_table.get_mut("path") {
Expand Down Expand Up @@ -462,7 +460,7 @@ fn update_root_toml(
let workspace_table = match document.as_table_mut().get_mut("workspace") {
Some(item) => item
.as_table_mut()
.ok_or_else(|| anyhow!("[workspace] is not a table"))?,
.ok_or_else(|| eyre!("[workspace] is not a table"))?,
None => {
// No [workspace] section -- possibly a single-crate manifest?
return Ok(());
Expand All @@ -475,7 +473,7 @@ fn update_root_toml(
let members = match workspace_table.get_mut(to_update) {
Some(item) => item
.as_array_mut()
.ok_or_else(|| anyhow!("in [workspace], {} is not an array", to_update))?,
.ok_or_else(|| eyre!("in [workspace], {} is not an array", to_update))?,
None => {
// default-members may not always exist.
continue;
Expand All @@ -488,8 +486,8 @@ fn update_root_toml(
Some(path) => {
let abs_member_dir = workspace_root.join(path);
// The workspace path saved in the TOML may not be in canonical form.
let abs_member_dir = abs_member_dir.canonicalize().with_context(|| {
anyhow!(
let abs_member_dir = abs_member_dir.canonicalize().wrap_err_with(|| {
eyre!(
"in [workspace] {}, error while canonicalizing path {}",
to_update,
path
Expand All @@ -509,17 +507,17 @@ fn update_root_toml(
}

let mut out = fs::File::create(&root_manifest_path)
.with_context(|| anyhow!("Error while opening {}", root_manifest_path))?;
.wrap_err_with(|| eyre!("Error while opening {}", root_manifest_path))?;
write!(out, "{}", document)?;

Ok(())
}

fn read_toml(manifest_path: &Utf8Path) -> Result<Document> {
let toml = fs::read_to_string(manifest_path)
.with_context(|| anyhow!("error while reading manifest {}", manifest_path))?;
.wrap_err_with(|| eyre!("error while reading manifest {}", manifest_path))?;
toml.parse::<Document>()
.with_context(|| anyhow!("error while parsing manifest {}", manifest_path))
.wrap_err_with(|| eyre!("error while parsing manifest {}", manifest_path))
}

/// Replace the value while retaining the decor.
Expand Down
3 changes: 2 additions & 1 deletion guppy-cmdlib/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@ edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
anyhow = "1.0.44"
# disable tracing integration since we don't use it
color-eyre = { version = "0.5.11", default-features = false }
guppy = { path = "../guppy" }
structopt = "0.3.25"
proptest = { version = "1.0.0", optional = true }
Expand Down
2 changes: 1 addition & 1 deletion guppy-cmdlib/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
#[cfg(feature = "proptest1")]
pub mod proptest;

use anyhow::Result;
use color_eyre::eyre::Result;
use guppy::{
graph::{
cargo::{CargoResolverVersion, InitialsPlatform},
Expand Down
3 changes: 2 additions & 1 deletion internal-tools/cargo-compare/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,9 @@ authors = ["Rain <rain1@fb.com>"]
edition = "2018"

[dependencies]
anyhow = "1.0.44"
anyhow = "1.0.51"
cargo = "0.57.0"
color-eyre = { version = "0.5.11", default-features = false }
diffus = "0.10.0"
either = "1.6.1"
itertools = "0.10.1"
Expand Down
Loading

0 comments on commit fdcc0c4

Please sign in to comment.