Skip to content

Commit

Permalink
(Unify workspace and package fuzzy dependency lookup)
Browse files Browse the repository at this point in the history
  • Loading branch information
dohse committed May 2, 2024
1 parent c7890fa commit 6e1e369
Showing 1 changed file with 36 additions and 17 deletions.
53 changes: 36 additions & 17 deletions src/cargo/ops/cargo_add/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -364,23 +364,8 @@ fn resolve_dependency(
};
selected_dep = populate_dependency(selected_dep, arg);

let mut old_dep = get_existing_dependency(manifest, selected_dep.toml_key(), section)?;
if old_dep.is_none() && selected_dep.source().is_none() && selected_dep.rename().is_none() {
for name_permutation in [
selected_dep.name.replace('-', "_"),
selected_dep.name.replace('_', "-"),
] {
old_dep = get_existing_dependency(manifest, &name_permutation, section)?;
if old_dep.is_some() {
gctx.shell().warn(format!(
"translating `{}` to `{}`",
selected_dep.name, &name_permutation,
))?;
selected_dep.name = name_permutation;
break;
}
}
}
let lookup = |dep_key: &_| get_existing_dependency(manifest, dep_key, section);
let old_dep = fuzzy_lookup(&mut selected_dep, lookup, gctx)?;

let mut dependency = if let Some(mut old_dep) = old_dep.clone() {
if old_dep.name != selected_dep.name {
Expand Down Expand Up @@ -488,6 +473,40 @@ fn resolve_dependency(
Ok(dependency)
}

fn fuzzy_lookup(
dependency: &mut Dependency,
lookup: impl Fn(&str) -> CargoResult<Option<Dependency>>,
gctx: &GlobalContext,
) -> CargoResult<Option<Dependency>> {
if let Some(rename) = dependency.rename() {
return lookup(rename);
}

for name_permutation in [
dependency.name.clone(),
dependency.name.replace('-', "_"),
dependency.name.replace('_', "-"),
] {
let Some(dep) = lookup(&name_permutation)? else {
continue;
};

if dependency.name != name_permutation {
if !matches!(dep.source, Some(Source::Registry(_))) {
continue;
}
gctx.shell().warn(format!(
"translating `{}` to `{}`",
dependency.name, &name_permutation,
))?;
dependency.name = name_permutation;
}
return Ok(Some(dep));
}

Ok(None)
}

/// When { workspace = true } you cannot define other keys that configure
/// the source of the dependency such as `version`, `registry`, `registry-index`,
/// `path`, `git`, `branch`, `tag`, `rev`, or `package`. You can also not define
Expand Down

0 comments on commit 6e1e369

Please sign in to comment.