Skip to content

Commit

Permalink
fix(remove): On error, suggest other dependencies
Browse files Browse the repository at this point in the history
`cargo remove` already will suggest other tables if appropriate.
`cargo add` auto-corrects `_` and `-`.

This is an extension of the two by suggesting existing dependencies
within the same table that are "close".

I chose to make alt tables and alt deps mutually exclusive in the
message because I didn't wantto deal with how to separate things if both
show up.
Most likely, people will only expect one or the other and if its in an
alt table, then most likely they mean that.

Related to rust-lang#14814
  • Loading branch information
epage committed Nov 13, 2024
1 parent 4da1b2e commit 33d1361
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 2 deletions.
12 changes: 12 additions & 0 deletions src/cargo/util/toml_mut/manifest.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ use anyhow::Context as _;
use super::dependency::Dependency;
use crate::core::dependency::DepKind;
use crate::core::{FeatureValue, Features, Workspace};
use crate::util::closest;
use crate::util::interning::InternedString;
use crate::{CargoResult, GlobalContext};

Expand Down Expand Up @@ -381,6 +382,13 @@ impl LocalManifest {
}
}
None => {
let names = parent_table
.as_table_like()
.map(|t| t.iter())
.into_iter()
.flatten();
let alt_name = closest(name, names.map(|(k, _)| k), |k| k).map(|n| n.to_owned());

// Search in other tables.
let sections = self.get_sections();
let found_table_path = sections.iter().find_map(|(t, i)| {
Expand All @@ -393,6 +401,7 @@ impl LocalManifest {
name,
table_path.join("."),
found_table_path,
alt_name.as_deref(),
));
}
}
Expand Down Expand Up @@ -605,10 +614,13 @@ fn non_existent_dependency_err(
name: impl std::fmt::Display,
search_table: impl std::fmt::Display,
found_table: Option<impl std::fmt::Display>,
alt_name: Option<&str>,
) -> anyhow::Error {
let mut msg = format!("the dependency `{name}` could not be found in `{search_table}`");
if let Some(found_table) = found_table {
msg.push_str(&format!("; it is present in `{found_table}`",));
} else if let Some(alt_name) = alt_name {
msg.push_str(&format!("; dependency `{alt_name}` exists",));
}
anyhow::format_err!(msg)
}
Expand Down
4 changes: 2 additions & 2 deletions tests/testsuite/cargo_remove/invalid_dep/stderr.term.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.

0 comments on commit 33d1361

Please sign in to comment.