diff --git a/src/cargo/ops/fix.rs b/src/cargo/ops/fix.rs index 24dd8b63500..0e45e164418 100644 --- a/src/cargo/ops/fix.rs +++ b/src/cargo/ops/fix.rs @@ -456,18 +456,19 @@ fn add_feature_for_unused_deps(pkg: &Package, parent: &mut dyn toml_edit::TableL for dep in manifest.dependencies() { let dep_name_in_toml = dep.name_in_toml(); if dep.is_optional() && !activated_opt_deps.contains(dep_name_in_toml.as_str()) { - fixes += 1; if let Some(features) = parent .entry("features") .or_insert(toml_edit::table()) .as_table_like_mut() { - features.insert( - dep_name_in_toml.as_str(), - toml_edit::Item::Value(toml_edit::Value::Array(toml_edit::Array::from_iter( - &[format!("dep:{}", dep_name_in_toml)], - ))), - ); + features + .entry(dep_name_in_toml.as_str()) + .or_insert_with(|| { + fixes += 1; + toml_edit::Item::Value(toml_edit::Value::Array( + toml_edit::Array::from_iter(&[format!("dep:{}", dep_name_in_toml)]), + )) + }); } } } diff --git a/tests/testsuite/fix.rs b/tests/testsuite/fix.rs index 606ecc39f07..0c3d7793ade 100644 --- a/tests/testsuite/fix.rs +++ b/tests/testsuite/fix.rs @@ -2705,7 +2705,7 @@ unrelated-dep-feature = ["unrelated-feature/a", "unrelated-feature/b"] .with_stderr( "\ [MIGRATING] Cargo.toml from 2021 edition to 2024 -[FIXED] Cargo.toml (3 fixes) +[FIXED] Cargo.toml (1 fix) [UPDATING] `dummy-registry` index [LOCKING] 5 packages to latest compatible versions [CHECKING] foo v0.1.0 ([CWD]) @@ -2730,10 +2730,10 @@ renamed-feature = { version = "0.1.0", optional = true } unrelated-feature = { version = "0.1.0", optional = true } [features] -dep-feature = ["dep:dep-feature"] +dep-feature = ["dep-feature/a", "dep-feature/b"] dep-and-dep-feature = ["dep:dep-and-dep-feature", "dep-and-dep-feature/a", "dep-and-dep-feature/b"] renamed = ["renamed-feature/a", "renamed-feature/b"] -unrelated-feature = ["dep:unrelated-feature"] +unrelated-feature = [] unrelated-dep-feature = ["unrelated-feature/a", "unrelated-feature/b"] renamed-feature = ["dep:renamed-feature"]