Skip to content

Commit

Permalink
fix(cargo-fix): dont apply same suggestion twice
Browse files Browse the repository at this point in the history
This assumes that if any of the machine applicable fixes (`solution`)
in a diagnostic is a duplicate, then `cargo fix` should only apply
the entire suggestion once.
  • Loading branch information
weihanglo committed Apr 10, 2024
1 parent 1e1d773 commit 8d69122
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 5 deletions.
10 changes: 10 additions & 0 deletions src/cargo/ops/fix.rs
Original file line number Diff line number Diff line change
Expand Up @@ -738,7 +738,17 @@ fn rustfix_and_fix(
// As mentioned above in `rustfix_crate`, we don't immediately warn
// about suggestions that fail to apply here, and instead we save them
// off for later processing.
let mut already_applied = HashSet::new();
for suggestion in suggestions.iter().rev() {
// Skip seemly duplicate suggestions.
if suggestion
.solutions
.iter()
.any(|sol| !already_applied.insert(sol))
{
// already applied
break;
}
match fixed.apply(suggestion) {
Ok(()) => fixed_file.fixes_applied += 1,
Err(e) => fixed_file.errors_applying_fixes.push(e.to_string()),
Expand Down
10 changes: 5 additions & 5 deletions tests/testsuite/fix.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1924,18 +1924,18 @@ fn fix_only_once_for_duplicates() {
.build();

p.cargo("fix --allow-no-vcs")
.with_stderr_contains(
.with_stderr(
"\
[CHECKING] foo v0.0.1 ([CWD])
[FIXED] src/lib.rs (2 fixes)
[FIXED] src/lib.rs (1 fix)
[FINISHED] `dev` profile [..]
",
)
.with_stderr_contains("[WARNING] unnecessary `unsafe` block[..]")
.run();

assert_eq!(
p.read_file("src/lib.rs").matches("unsafe").count(),
5,
"2 in lint name, 1 from original unsafe fn, 2 from newly-applied unsafe blocks"
4,
"2 in lint name, 1 from original unsafe fn, 1 from newly-applied unsafe blocks"
);
}

0 comments on commit 8d69122

Please sign in to comment.