1use std::borrow::Cow;
8
9use similar::{ChangeTag, TextDiff};
10
11use crate::diff::options::DiffOptions;
12use crate::objects::FileMode;
13
14#[path = "diff/line_engine.rs"]
15mod line_engine;
16
17#[cfg(test)]
18pub(crate) use line_engine::structured_hunk_for_id_from_unified_slice;
19pub(crate) use line_engine::{
20 hash_hunk_body_from_unified_slice, hunk_body_digest_from_unified_slice,
21};
22
23#[derive(Debug, Clone, PartialEq, Eq)]
25pub struct SideBytes {
26 pub data: Vec<u8>,
28 pub encoding_lossy: bool,
30 pub size: u64,
32}
33
34impl SideBytes {
35 #[must_use]
37 pub fn from_bytes(data: Vec<u8>) -> Self {
38 let size = data.len() as u64;
39 let encoding_lossy = !data.is_empty() && std::str::from_utf8(&data).is_err();
40 Self {
41 data,
42 encoding_lossy,
43 size,
44 }
45 }
46
47 #[must_use]
50 pub fn unread(size: u64) -> Self {
51 Self {
52 data: Vec::new(),
53 encoding_lossy: false,
54 size,
55 }
56 }
57
58 #[must_use]
60 pub fn byte_len(&self) -> u64 {
61 self.size
62 }
63
64 #[must_use]
66 pub fn text(&self) -> String {
67 String::from_utf8_lossy(&self.data).into_owned()
68 }
69}
70
71#[derive(Debug, Clone, PartialEq, Eq)]
73pub struct StructuredSegment {
74 pub text: String,
76 pub emphasis: bool,
78}
79
80#[derive(Debug, Clone, Copy, PartialEq, Eq)]
82pub enum StructuredLineKind {
83 Context,
85 Add,
87 Del,
89}
90
91#[derive(Debug, Clone, PartialEq, Eq)]
93pub struct StructuredLine {
94 pub kind: StructuredLineKind,
96 pub old: Option<usize>,
98 pub new: Option<usize>,
100 pub segments: Vec<StructuredSegment>,
102 pub no_newline_at_eof: bool,
104}
105
106#[derive(Debug, Clone, PartialEq, Eq)]
108pub struct StructuredHunk {
109 pub old_start: usize,
111 pub new_start: usize,
113 pub old_lines: usize,
115 pub new_lines: usize,
117 pub context: Option<String>,
119 pub lines: Vec<StructuredLine>,
121}
122
123#[derive(Debug, Clone, PartialEq, Eq)]
125pub struct StructuredTextDiff {
126 pub hunks: Vec<StructuredHunk>,
128}
129
130#[derive(Debug, Clone, PartialEq, Eq)]
132pub struct StructuredFileDiff {
133 pub old_mode: Option<String>,
135 pub new_mode: Option<String>,
137 pub old_encoding_lossy: bool,
139 pub new_encoding_lossy: bool,
141 pub hunks: Vec<StructuredHunk>,
143}
144
145#[derive(Debug, Clone)]
147struct TextLines<'a> {
148 lines: Vec<&'a str>,
149}
150
151impl<'a> TextLines<'a> {
152 fn from_text(text: &'a str) -> Self {
153 let (parts, _) = lines_with_trailing_newline(text);
154 Self {
155 lines: parts.into_iter().map(strip_diff_newline_only).collect(),
156 }
157 }
158}
159
160pub(crate) fn text_bytes_for_diff(data: &[u8]) -> Cow<'_, str> {
162 if data.is_empty() {
163 return Cow::Borrowed("");
164 }
165 match std::str::from_utf8(data) {
166 Ok(text) => Cow::Borrowed(text),
167 Err(_) => Cow::Owned(String::from_utf8_lossy(data).into_owned()),
168 }
169}
170
171fn side_text_for_diff(side: &SideBytes) -> Cow<'_, str> {
173 text_bytes_for_diff(&side.data)
174}
175
176fn structured_text_diff_cow(
178 old_text: Cow<'_, str>,
179 new_text: Cow<'_, str>,
180 options: DiffOptions,
181) -> StructuredTextDiff {
182 structured_text_diff(old_text.as_ref(), new_text.as_ref(), options)
183}
184
185#[must_use]
187pub fn structured_text_diff(
188 old_text: &str,
189 new_text: &str,
190 options: DiffOptions,
191) -> StructuredTextDiff {
192 let mut hunks = line_engine::line_hunks(old_text, new_text, &options, options.function_context);
193 if options.word_level_inline {
194 apply_word_level_inline(&mut hunks, old_text, new_text);
195 }
196 StructuredTextDiff { hunks }
197}
198
199fn apply_word_level_inline(hunks: &mut [StructuredHunk], old_text: &str, new_text: &str) {
200 let old = TextLines::from_text(old_text);
201 let new = TextLines::from_text(new_text);
202
203 for hunk in &mut *hunks {
204 let mut i = 0usize;
205 while i < hunk.lines.len() {
206 if hunk.lines[i].kind != StructuredLineKind::Del {
207 i += 1;
208 continue;
209 }
210 let del_start = i;
211 while i < hunk.lines.len() && hunk.lines[i].kind == StructuredLineKind::Del {
212 i += 1;
213 }
214 let add_start = i;
215 while i < hunk.lines.len() && hunk.lines[i].kind == StructuredLineKind::Add {
216 i += 1;
217 }
218 let del_end = i.min(add_start);
219 let add_end = i;
220 if del_end > del_start && add_end > add_start {
221 let del_count = del_end - del_start;
222 let add_count = add_end - add_start;
223 let pairs = del_count.min(add_count);
224 for p in 0..pairs {
225 let del_idx = del_start + p;
226 let add_idx = add_start + p;
227 let (left, right) = hunk.lines.split_at_mut(add_idx);
228 let del_line = &mut left[del_idx];
229 let add_line = &mut right[0];
230 emphasize_replace_line_pair(del_line, add_line);
231 }
232 }
233 }
234 }
235
236 pin_canonical_line_text(hunks, &old.lines, &new.lines);
237}
238
239fn emphasize_replace_line_pair(del: &mut StructuredLine, add: &mut StructuredLine) {
240 let old_line = del.segments[0].text.clone();
241 let new_line = add.segments[0].text.clone();
242 let diff = TextDiff::from_words(&old_line, &new_line);
243 del.segments = word_segments_from_diff(&diff, &old_line, true);
244 add.segments = word_segments_from_diff(&diff, &new_line, false);
245}
246
247fn word_segments_from_diff(
248 diff: &TextDiff<'_, '_, str>,
249 full_line: &str,
250 old_side: bool,
251) -> Vec<StructuredSegment> {
252 let mut segments: Vec<StructuredSegment> = Vec::new();
253 for change in diff.iter_all_changes() {
254 let is_this_side = match change.tag() {
255 ChangeTag::Delete => old_side,
256 ChangeTag::Insert => !old_side,
257 ChangeTag::Equal => true,
258 };
259 if !is_this_side {
260 continue;
261 }
262 let emphasis = change.tag() != ChangeTag::Equal;
263 let text = change.value().to_owned();
264 if text.is_empty() {
265 continue;
266 }
267 if let Some(last) = segments.last_mut() {
268 if last.emphasis == emphasis {
269 last.text.push_str(&text);
270 continue;
271 }
272 }
273 segments.push(StructuredSegment { text, emphasis });
274 }
275 if segments.is_empty() && !full_line.is_empty() {
276 segments.push(StructuredSegment {
277 text: full_line.to_owned(),
278 emphasis: false,
279 });
280 }
281 reconcile_segments_with_line(&mut segments, full_line);
282 segments
283}
284
285fn pin_canonical_line_text(hunks: &mut [StructuredHunk], old_lines: &[&str], new_lines: &[&str]) {
287 for hunk in hunks {
288 for line in &mut hunk.lines {
289 let canonical = match line.kind {
290 StructuredLineKind::Del | StructuredLineKind::Context => line
291 .old
292 .and_then(|n| old_lines.get(n.saturating_sub(1)).copied()),
293 StructuredLineKind::Add => line
294 .new
295 .and_then(|n| new_lines.get(n.saturating_sub(1)).copied()),
296 };
297 let Some(canonical) = canonical else {
298 continue;
299 };
300 let collapse = line.kind == StructuredLineKind::Del && line.segments.len() != 1;
302 if collapse || !segments_render_as(&line.segments, canonical) {
303 let emphasis = line.segments.iter().any(|s| s.emphasis);
304 line.segments = vec![StructuredSegment {
305 text: canonical.to_owned(),
306 emphasis,
307 }];
308 }
309 }
310 }
311}
312
313fn segments_render_as(segments: &[StructuredSegment], text: &str) -> bool {
315 let mut rest = text;
316 for segment in segments {
317 match rest.strip_prefix(segment.text.as_str()) {
318 Some(tail) => rest = tail,
319 None => return false,
320 }
321 }
322 rest.is_empty()
323}
324
325#[must_use]
327pub fn structured_file_diff(
328 old_mode: FileMode,
329 new_mode: FileMode,
330 old: &SideBytes,
331 new: &SideBytes,
332 options: DiffOptions,
333) -> StructuredFileDiff {
334 let old_mode = old_mode.octal_if_present();
335 let new_mode = new_mode.octal_if_present();
336 let old_text = side_text_for_diff(old);
337 let new_text = side_text_for_diff(new);
338 let hunks = structured_text_diff_cow(old_text, new_text, options).hunks;
339 StructuredFileDiff {
340 old_mode,
341 new_mode,
342 old_encoding_lossy: old.encoding_lossy,
343 new_encoding_lossy: new.encoding_lossy,
344 hunks,
345 }
346}
347
348fn lines_with_trailing_newline(text: &str) -> (Vec<&str>, bool) {
350 if text.is_empty() {
351 return (Vec::new(), false);
352 }
353 let ends_nl = text.ends_with('\n');
354 let mut parts: Vec<&str> = text.split('\n').collect();
355 if ends_nl && parts.last() == Some(&"") {
356 parts.pop();
357 }
358 (parts, ends_nl)
359}
360
361fn strip_diff_newline_only(s: &str) -> &str {
362 s.strip_suffix('\n').unwrap_or(s)
363}
364
365pub(crate) fn old_line_bodies_for_context(text: &str) -> Vec<&str> {
367 TextLines::from_text(text).lines
368}
369
370pub(crate) fn enclosing_function_context(
372 lines: &[&str],
373 old_start_1based: usize,
374) -> Option<String> {
375 if old_start_1based == 0 {
376 return None;
377 }
378 function_context(lines, old_start_1based.saturating_sub(1))
379}
380
381fn function_context(lines: &[&str], start_0based: usize) -> Option<String> {
382 lines[..start_0based.min(lines.len())]
383 .iter()
384 .rev()
385 .find_map(|line| {
386 let first = line.chars().next()?;
387 (first.is_alphabetic() || first == '_').then(|| line.trim_end().to_owned())
388 })
389}
390
391fn reconcile_segments_with_line(segments: &mut Vec<StructuredSegment>, full_line: &str) {
392 if full_line.is_empty() {
393 return;
394 }
395 let rendered: String = segments.iter().map(|s| s.text.as_str()).collect();
396 if rendered != full_line {
397 let emphasis = segments.iter().any(|s| s.emphasis);
398 segments.clear();
399 segments.push(StructuredSegment {
400 text: full_line.to_owned(),
401 emphasis,
402 });
403 }
404}
405
406#[must_use]
408pub fn format_hunk_range(start: usize, count: usize) -> String {
409 if count == 0 {
410 "0,0".to_owned()
411 } else if count == 1 {
412 start.to_string()
413 } else {
414 format!("{start},{count}")
415 }
416}
417
418#[cfg(test)]
419mod tests {
420 use super::*;
421 use std::process::Command;
422
423 fn git_diff(old: &str, new: &str) -> String {
424 let tmp = tempfile::tempdir().expect("tempdir");
425 let path = tmp.path().join("f.txt");
426 std::fs::write(&path, old).expect("write old");
427 Command::new("git")
428 .args(["init", "-q", "-b", "main"])
429 .current_dir(tmp.path())
430 .status()
431 .expect("git init");
432 Command::new("git")
433 .args(["config", "user.email", "t@e.com"])
434 .current_dir(tmp.path())
435 .status()
436 .unwrap();
437 Command::new("git")
438 .args(["config", "user.name", "T"])
439 .current_dir(tmp.path())
440 .status()
441 .unwrap();
442 Command::new("git")
443 .args(["add", "f.txt"])
444 .current_dir(tmp.path())
445 .status()
446 .unwrap();
447 Command::new("git")
448 .args(["commit", "-qm", "init"])
449 .current_dir(tmp.path())
450 .status()
451 .unwrap();
452 std::fs::write(&path, new).expect("write new");
453 let out = Command::new("git")
454 .args(["diff", "f.txt"])
455 .current_dir(tmp.path())
456 .output()
457 .expect("git diff");
458 String::from_utf8(out.stdout).expect("utf8")
459 }
460
461 fn parse_hunk_header(patch: &str) -> (usize, usize, usize, usize) {
462 let line = patch.lines().find(|l| l.starts_with("@@")).expect("hunk");
463 let rest = line.strip_prefix("@@ ").expect("prefix");
464 let (old_part, new_part) = rest.split_once(" +").expect("plus");
465 let old_part = old_part.strip_prefix('-').expect("minus");
466 let (os, ol) = parse_range(old_part.split(' ').next().expect("old"));
467 let new_part = new_part.split(" @@").next().expect("close");
468 let (ns, nl) = parse_range(new_part);
469 (os, ol, ns, nl)
470 }
471
472 fn parse_range(s: &str) -> (usize, usize) {
473 if let Some((a, b)) = s.split_once(',') {
474 (a.parse().expect("start"), b.parse().expect("count"))
475 } else {
476 (s.parse().expect("start"), 1)
477 }
478 }
479
480 #[test]
481 fn lines_with_trailing_newline_splits_crlf() {
482 let (parts, ends) = lines_with_trailing_newline("a\r\nb\r\n");
483 assert!(ends);
484 assert_eq!(parts, ["a\r", "b\r"]);
485 }
486
487 #[test]
488 fn text_lines_from_text_preserves_cr() {
489 let t = TextLines::from_text("a\r\nb\r\n");
490 assert_eq!(t.lines[0], "a\r");
491 }
492
493 #[test]
494 fn crlf_to_lf_shows_carriage_return_on_removed_lines() {
495 let old = "a\r\nb\r\n";
496 let new = "a\nb\n";
497 let d = structured_text_diff(old, new, DiffOptions::default());
498 let del: Vec<_> = d.hunks[0]
499 .lines
500 .iter()
501 .filter(|l| l.kind == StructuredLineKind::Del)
502 .collect();
503 assert_eq!(del[0].segments[0].text, "a\r");
504 }
505
506 #[test]
507 fn trailing_newline_only_change_sets_no_newline_flag() {
508 let old = "line1\nline2";
509 let new = "line1\nline2\n";
510 let d = structured_text_diff(old, new, DiffOptions::default());
511 let del = d.hunks[0]
512 .lines
513 .iter()
514 .find(|l| l.kind == StructuredLineKind::Del)
515 .expect("deleted line2");
516 assert!(del.no_newline_at_eof);
517 }
518
519 #[test]
520 fn context_last_line_without_eof_newline_is_marked() {
521 let old = "old\nlast";
522 let new = "new\nlast";
523 let d = structured_text_diff(old, new, DiffOptions::default());
524 let ctx = d.hunks[0]
525 .lines
526 .iter()
527 .find(|l| l.kind == StructuredLineKind::Context && l.segments[0].text == "last")
528 .expect("context last");
529 assert!(ctx.no_newline_at_eof);
530 }
531
532 #[test]
533 fn segments_render_as_compares_concatenation() {
534 let seg = |text: &str| StructuredSegment {
535 text: text.into(),
536 emphasis: false,
537 };
538 assert!(segments_render_as(&[], ""));
539 assert!(!segments_render_as(&[], "a"));
540 assert!(segments_render_as(&[seg("ab"), seg("c")], "abc"));
541 assert!(!segments_render_as(&[seg("ab"), seg("c")], "abcd"));
542 assert!(!segments_render_as(&[seg("ab"), seg("x")], "abc"));
543 assert!(!segments_render_as(&[seg("abcd")], "abc"));
544 }
545
546 fn line_text(line: &StructuredLine) -> String {
547 line.segments.iter().map(|s| s.text.as_str()).collect()
548 }
549
550 #[test]
551 fn word_level_inline_keeps_canonical_line_text() {
552 let old = "keep\nfoo bar baz\n\nend\n";
553 let new = "keep\nfoo qux baz\nfilled\nend\n";
554 let plain = structured_text_diff(
555 old,
556 new,
557 DiffOptions::default().with_word_level_inline(false),
558 );
559 let inline = structured_text_diff(
560 old,
561 new,
562 DiffOptions::default().with_word_level_inline(true),
563 );
564 assert_eq!(plain.hunks.len(), inline.hunks.len());
565 for (p, i) in plain.hunks.iter().zip(&inline.hunks) {
566 assert_eq!(p.lines.len(), i.lines.len());
567 for (pl, il) in p.lines.iter().zip(&i.lines) {
568 assert_eq!((pl.kind, pl.old, pl.new), (il.kind, il.old, il.new));
569 assert_eq!(line_text(pl), line_text(il));
570 if il.kind == StructuredLineKind::Del {
571 assert_eq!(
572 il.segments.len(),
573 1,
574 "deleted lines collapse to one segment"
575 );
576 }
577 }
578 }
579 let dels: Vec<_> = inline.hunks[0]
580 .lines
581 .iter()
582 .filter(|l| l.kind == StructuredLineKind::Del)
583 .collect();
584 assert_eq!(line_text(dels[0]), "foo bar baz");
585 assert!(dels[0].segments[0].emphasis);
586 assert_eq!(line_text(dels[1]), "");
587 let add = inline.hunks[0]
588 .lines
589 .iter()
590 .find(|l| l.kind == StructuredLineKind::Add)
591 .expect("added line");
592 assert_eq!(line_text(add), "foo qux baz");
593 assert!(add.segments.len() > 1, "added line keeps word segments");
594 }
595
596 fn git_diff_u0(old: &str, new: &str) -> String {
597 let tmp = tempfile::tempdir().expect("tempdir");
598 let path = tmp.path().join("f.txt");
599 std::fs::write(&path, old).expect("write old");
600 Command::new("git")
601 .args(["init", "-q", "-b", "main"])
602 .current_dir(tmp.path())
603 .status()
604 .expect("git init");
605 for (k, v) in [("user.email", "t@e.com"), ("user.name", "T")] {
606 Command::new("git")
607 .args(["config", k, v])
608 .current_dir(tmp.path())
609 .status()
610 .unwrap();
611 }
612 Command::new("git")
613 .args(["add", "f.txt"])
614 .current_dir(tmp.path())
615 .status()
616 .unwrap();
617 Command::new("git")
618 .args(["commit", "-qm", "init"])
619 .current_dir(tmp.path())
620 .status()
621 .unwrap();
622 std::fs::write(&path, new).expect("write new");
623 let out = Command::new("git")
624 .args(["diff", "-U0", "f.txt"])
625 .current_dir(tmp.path())
626 .output()
627 .expect("git diff");
628 String::from_utf8(out.stdout).expect("utf8")
629 }
630
631 #[cfg_attr(
632 not(feature = "full-tests"),
633 ignore = "starts system git or is heavy; run with --features full-tests"
634 )]
635 #[test]
636 fn zero_context_insertion_anchor_matches_git() {
637 let old = "a\nb\nc\n";
638 let new = "a\nb\nX\nc\n";
639 let patch = git_diff_u0(old, new);
640 let (g_os, g_ol, g_ns, g_nl) = parse_hunk_header(&patch);
641 let d = structured_text_diff(
642 old,
643 new,
644 DiffOptions {
645 context_lines: 0,
646 ..DiffOptions::default()
647 },
648 );
649 let h = &d.hunks[0];
650 assert_eq!(
651 (h.old_start, h.old_lines, h.new_start, h.new_lines),
652 (g_os, g_ol, g_ns, g_nl)
653 );
654 assert_eq!((h.old_start, h.old_lines), (2, 0));
655 }
656
657 #[cfg_attr(
658 not(feature = "full-tests"),
659 ignore = "starts system git or is heavy; run with --features full-tests"
660 )]
661 #[test]
662 fn zero_context_deletion_anchor_matches_git() {
663 let old = "a\nb\nc\n";
664 let new = "a\nc\n";
665 let patch = git_diff_u0(old, new);
666 let (g_os, g_ol, g_ns, g_nl) = parse_hunk_header(&patch);
667 let d = structured_text_diff(
668 old,
669 new,
670 DiffOptions {
671 context_lines: 0,
672 ..DiffOptions::default()
673 },
674 );
675 let h = &d.hunks[0];
676 assert_eq!(
677 (h.old_start, h.old_lines, h.new_start, h.new_lines),
678 (g_os, g_ol, g_ns, g_nl)
679 );
680 assert_eq!((h.new_start, h.new_lines), (1, 0));
681 }
682
683 #[cfg_attr(
684 not(feature = "full-tests"),
685 ignore = "starts system git or is heavy; run with --features full-tests"
686 )]
687 #[test]
688 fn structured_hunk_retains_enclosing_function_context() {
689 let old = "fn foo() {\n let x = 1;\n}\n";
690 let new = "fn foo() {\n let x = 2;\n}\n";
691 let mut opts = DiffOptions::default();
692 opts.function_context = true;
693 let d = structured_text_diff(old, new, opts);
694 let h = &d.hunks[0];
695 assert_eq!(h.context.as_deref(), Some("fn foo() {"));
696 }
697
698 #[cfg_attr(
699 not(feature = "full-tests"),
700 ignore = "starts system git or is heavy; run with --features full-tests"
701 )]
702 #[test]
703 fn insert_into_empty_file_matches_git_hunk_header() {
704 let patch = git_diff("", "x\n");
705 let (g_os, g_ol, g_ns, g_nl) = parse_hunk_header(&patch);
706 let d = structured_text_diff("", "x\n", DiffOptions::default());
707 let h = &d.hunks[0];
708 assert_eq!(
709 (h.old_start, h.old_lines, h.new_start, h.new_lines),
710 (g_os, g_ol, g_ns, g_nl)
711 );
712 assert_eq!((h.old_start, h.old_lines), (0, 0));
713 }
714
715 #[cfg_attr(
716 not(feature = "full-tests"),
717 ignore = "starts system git or is heavy; run with --features full-tests"
718 )]
719 #[test]
720 fn delete_to_empty_matches_git_hunk_header() {
721 let patch = git_diff("x\n", "");
722 let (g_os, g_ol, g_ns, g_nl) = parse_hunk_header(&patch);
723 let d = structured_text_diff("x\n", "", DiffOptions::default());
724 let h = &d.hunks[0];
725 assert_eq!(
726 (h.old_start, h.old_lines, h.new_start, h.new_lines),
727 (g_os, g_ol, g_ns, g_nl)
728 );
729 assert_eq!((h.new_start, h.new_lines), (0, 0));
730 }
731
732 #[cfg_attr(
733 not(feature = "full-tests"),
734 ignore = "starts system git or is heavy; run with --features full-tests"
735 )]
736 #[test]
737 fn line_level_multiple_hunks_match_git() {
738 let old = "keep\nchange-a\nmid\nchange-b\nend\n";
739 let new = "keep\nCHANGE-A\nmid\nCHANGE-B\nend\n";
740 let patch = git_diff_u0(old, new);
741 let git_hunks: Vec<_> = patch.lines().filter(|l| l.starts_with("@@")).collect();
742 assert_eq!(git_hunks.len(), 2);
743 let d = structured_text_diff(
744 old,
745 new,
746 DiffOptions {
747 context_lines: 0,
748 word_level_inline: false,
749 ..DiffOptions::default()
750 },
751 );
752 assert_eq!(d.hunks.len(), 2);
753 for (h, header) in d.hunks.iter().zip(git_hunks) {
754 let (g_os, g_ol, g_ns, g_nl) = parse_hunk_header(&format!("{header}\n"));
755 assert_eq!(
756 (h.old_start, h.old_lines, h.new_start, h.new_lines),
757 (g_os, g_ol, g_ns, g_nl)
758 );
759 }
760 }
761
762 #[test]
763 fn line_level_blank_line_in_hunk() {
764 let old = "a\n\nb\n";
765 let new = "a\nX\n\nb\n";
766 let d = structured_text_diff(
767 old,
768 new,
769 DiffOptions {
770 context_lines: 1,
771 word_level_inline: false,
772 ..DiffOptions::default()
773 },
774 );
775 assert!(!d.hunks.is_empty());
776 assert!(
777 d.hunks[0]
778 .lines
779 .iter()
780 .any(|l| l.segments[0].text.is_empty() && l.kind == StructuredLineKind::Context)
781 || d.hunks[0]
782 .lines
783 .iter()
784 .any(|l| l.segments[0].text.is_empty())
785 );
786 }
787
788 #[test]
789 fn line_level_missing_eof_newline_flag() {
790 let old = "only";
791 let new = "only\n";
792 let d = structured_text_diff(
793 old,
794 new,
795 DiffOptions {
796 context_lines: 0,
797 word_level_inline: false,
798 ..DiffOptions::default()
799 },
800 );
801 let h = &d.hunks[0];
802 let add = h
803 .lines
804 .iter()
805 .find(|l| l.kind == StructuredLineKind::Add)
806 .expect("add line");
807 assert!(add.no_newline_at_eof || h.lines.iter().any(|l| l.no_newline_at_eof));
808 }
809
810 #[test]
811 fn hunk_header_counts_match_line_totals() {
812 let old = "x\n";
813 let new = "x\nmore\n";
814 let d = structured_text_diff(
815 old,
816 new,
817 DiffOptions {
818 context_lines: 3,
819 ..DiffOptions::default()
820 },
821 );
822 let h = &d.hunks[0];
823 assert_eq!(h.old_lines, 1);
824 assert_eq!(h.new_lines, 2);
825 }
826
827 #[test]
828 fn mode_only_change_has_empty_hunks() {
829 let old = SideBytes::from_bytes(b"x\n".to_vec());
830 let new = SideBytes::from_bytes(b"x\n".to_vec());
831 let f = structured_file_diff(
832 FileMode::REGULAR,
833 FileMode::EXECUTABLE,
834 &old,
835 &new,
836 DiffOptions::default(),
837 );
838 assert!(f.hunks.is_empty());
839 }
840}