From f9fc948127d8b2a44d42f0ff77dc61674398028b Mon Sep 17 00:00:00 2001 From: Samuel Moelius Date: Tue, 25 Feb 2025 23:08:04 +0000 Subject: [PATCH] Warn rather than panic when hunk is malformed --- dylint/src/package_options/auto_correct/mod.rs | 2 +- .../auto_correct/rewrite/mod.rs | 18 ++++++++++++++++-- 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/dylint/src/package_options/auto_correct/mod.rs b/dylint/src/package_options/auto_correct/mod.rs index f8a77d9c8..95164038b 100644 --- a/dylint/src/package_options/auto_correct/mod.rs +++ b/dylint/src/package_options/auto_correct/mod.rs @@ -92,7 +92,7 @@ pub fn auto_correct_revertible( let repository = clippy_repository(opts.quiet)?; - let rewrites = collect_rewrites(old_channel, new_oid, &repository)?; + let rewrites = collect_rewrites(opts, old_channel, new_oid, &repository)?; loop { let mut rewriters = BTreeMap::new(); diff --git a/dylint/src/package_options/auto_correct/rewrite/mod.rs b/dylint/src/package_options/auto_correct/rewrite/mod.rs index e5a81e091..22f172449 100644 --- a/dylint/src/package_options/auto_correct/rewrite/mod.rs +++ b/dylint/src/package_options/auto_correct/rewrite/mod.rs @@ -1,4 +1,5 @@ use super::{common, highlight::Highlight, short_id::ShortId, tokenization::tokenize_lines}; +use crate::{error::warn, opts}; use anyhow::Result; use dylint_internal::{ env, @@ -142,6 +143,7 @@ fn subslice_position(xs: &[T], ys: &[T]) -> Option { } pub fn collect_rewrites( + opts: &opts::Dylint, old_channel: &str, new_oid: Oid, repository: &Repository, @@ -182,7 +184,7 @@ pub fn collect_rewrites( let mut rewrites = HashMap::new(); for (patch, oid) in patches_with_oids { let rewrites_unflattened = - rewrites_from_patch(&patch, &mut n_insertions, &mut n_refactors)?; + rewrites_from_patch(opts, &patch, &mut n_insertions, &mut n_refactors)?; for rewrite in rewrites_unflattened { rewrites.entry(rewrite).or_insert(oid); } @@ -202,6 +204,7 @@ pub fn collect_rewrites( // smoelius: You need a `Patch` to get a `DiffHunk`'s lines. So there would be no easy way to write // a `hunks_from_patch` function. See, for example, `hunk_lines` below. fn rewrites_from_patch( + opts: &opts::Dylint, patch: &Patch<'_>, n_insertions: &mut usize, n_refactors: &mut usize, @@ -210,7 +213,18 @@ fn rewrites_from_patch( let n_hunks = patch.num_hunks(); for hunk_idx in 0..n_hunks { let (hunk, line_count) = patch.hunk(hunk_idx)?; - debug_assert_eq!((hunk.old_lines() + hunk.new_lines()) as usize, line_count); + if (hunk.old_lines() + hunk.new_lines()) as usize != line_count { + warn( + opts, + &format!( + "Malformed hunk: old lines ({}) + new lines ({}) != line count ({})", + hunk.old_lines(), + hunk.new_lines(), + line_count + ), + ); + continue; + } // smoelius: `hunk.old_lines()` must be non-zero for there to be something to rewrite. if hunk.old_lines() == 0 { *n_insertions += 1;