Skip to content

Commit 8de65af

Browse files
authored
Fix unified diff including up to 2 * context_lines before first hunk when near input start (#35)
* Add a regression test * Fix including up to `2 * context_lines` before first hunk when near start
1 parent 055f8e3 commit 8de65af

File tree

2 files changed

+56
-4
lines changed

2 files changed

+56
-4
lines changed

src/tests.rs

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -203,6 +203,58 @@ fn simple_insert() {
203203
}
204204
}
205205

206+
#[test]
207+
fn unified_diff_context_lines_near_input_start_and_end() {
208+
let before = r#"a
209+
b
210+
c
211+
d
212+
e
213+
f
214+
g
215+
h
216+
i
217+
"#;
218+
219+
let after = r#"a
220+
b
221+
c
222+
d
223+
edit
224+
f
225+
g
226+
h
227+
i
228+
"#;
229+
230+
let input = InternedInput::new(before, after);
231+
for algorithm in Algorithm::ALL {
232+
println!("{algorithm:?}");
233+
let mut diff = Diff::compute(algorithm, &input);
234+
diff.postprocess_lines(&input);
235+
expect![[r#"
236+
@@ -2,7 +2,7 @@
237+
b
238+
c
239+
d
240+
-e
241+
+edit
242+
f
243+
g
244+
h
245+
"#]]
246+
.assert_eq(
247+
&diff
248+
.unified_diff(
249+
&BasicLineDiffPrinter(&input.interner),
250+
UnifiedDiffConfig::default(),
251+
&input,
252+
)
253+
.to_string(),
254+
);
255+
}
256+
}
257+
206258
pub fn project_root() -> PathBuf {
207259
let dir = env!("CARGO_MANIFEST_DIR");
208260
let mut res = PathBuf::from(dir);

src/unified_diff.rs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -143,18 +143,18 @@ pub struct UnifiedDiff<'a, P: UnifiedDiffPrinter> {
143143

144144
impl<P: UnifiedDiffPrinter> Display for UnifiedDiff<'_, P> {
145145
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
146-
let mut pos = 0;
147-
let mut before_context_len = 0;
148-
let mut after_context_len = 0;
149146
let first_hunk = self.diff.hunks().next().unwrap_or_default();
150-
let mut before_context_start = first_hunk
147+
let mut pos = first_hunk
151148
.before
152149
.start
153150
.saturating_sub(self.config.context_len);
151+
let mut before_context_start = pos;
154152
let mut after_context_start = first_hunk
155153
.after
156154
.start
157155
.saturating_sub(self.config.context_len);
156+
let mut before_context_len = 0;
157+
let mut after_context_len = 0;
158158
let mut buffer = String::new();
159159
for hunk in self.diff.hunks() {
160160
if hunk.before.start - pos > 2 * self.config.context_len {

0 commit comments

Comments
 (0)