diff --git a/src/cargo/util/toml_mut/manifest.rs b/src/cargo/util/toml_mut/manifest.rs index a1a8ba8f64c..80562b03f49 100644 --- a/src/cargo/util/toml_mut/manifest.rs +++ b/src/cargo/util/toml_mut/manifest.rs @@ -540,5 +540,42 @@ fn non_existent_dependency_err( } fn remove_array_index(array: &mut toml_edit::Array, index: usize) { - array.remove(index); + let value = array.remove(index); + + // Captures all lines before leading whitespace + let prefix_lines = value + .decor() + .prefix() + .and_then(|p| p.as_str().expect("spans removed").rsplit_once('\n')) + .map(|(lines, _current)| lines); + // Captures all lines after trailing whitespace, before the next comma + let suffix_lines = value + .decor() + .suffix() + .and_then(|p| p.as_str().expect("spans removed").split_once('\n')) + .map(|(_current, lines)| lines); + let mut merged_lines = String::new(); + if let Some(prefix_lines) = prefix_lines { + merged_lines.push_str(prefix_lines); + merged_lines.push('\n'); + } + if let Some(suffix_lines) = suffix_lines { + merged_lines.push_str(suffix_lines); + merged_lines.push('\n'); + } + + let next_index = index; // Since `index` was removed, that effectively auto-advances us + if let Some(next) = array.get_mut(next_index) { + let next_decor = next.decor_mut(); + let next_prefix = next_decor + .prefix() + .map(|s| s.as_str().expect("spans removed")) + .unwrap_or_default(); + merged_lines.push_str(next_prefix); + next_decor.set_prefix(merged_lines); + } else { + let trailing = array.trailing().as_str().expect("spans removed"); + merged_lines.push_str(trailing); + array.set_trailing(merged_lines); + } } diff --git a/tests/testsuite/cargo_remove/optional_dep_feature_formatting/out/Cargo.toml b/tests/testsuite/cargo_remove/optional_dep_feature_formatting/out/Cargo.toml index c535b19749d..0398c8beb06 100644 --- a/tests/testsuite/cargo_remove/optional_dep_feature_formatting/out/Cargo.toml +++ b/tests/testsuite/cargo_remove/optional_dep_feature_formatting/out/Cargo.toml @@ -21,7 +21,10 @@ serde = "1.0.90" [features] std = [ # Leading clippy - "dep:clippy", # trailing docopt + "dep:clippy", # trailing clippy + + # Leading docopt + # trailing docopt # Leading rustc-serialize "dep:rustc-serialize", # trailing rustc-serialize @@ -30,5 +33,8 @@ std = [ "serde/std", # trailing serde/std # Leading semver/std - "semver/std", # trailing toml + "semver/std", # trailing semver/std + + # Leading toml + # trailing toml ]