hunkpick 0.10.0

Non-interactive git add -p alternative — pick and split unified-diff hunks by index, range, or content id
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
use crate::model::*;
use std::collections::BTreeSet;
use std::fmt;

/// Why a hunk could not be split as asked. Every variant is a usage error (exit code 2).
#[derive(Debug, PartialEq, Eq)]
pub enum SplitError {
    /// A `--at` cut point names a new-file line that carries a change; only a context line can
    /// be cut at. Carries the offending line number.
    NotAContextLine(u32),
    /// A `--at` cut point names a new-file line outside the hunk. Carries it.
    OutOfRange(u32),
    /// An `INDEX@L<set>` selection references a changed line outside `1..=changed` of the
    /// sub-hunk. Carries the offending 1-based index and the sub-hunk's changed-line count.
    ChangedLineOutOfRange {
        /// The offending 1-based changed-line index.
        index: usize,
        /// How many changed lines the sub-hunk actually has.
        changed: usize,
    },
    /// An `INDEX@L<set>` selection resolved to no changed lines (an empty set). A defensive
    /// invariant: from the CLI an empty `@L` set is already rejected earlier by the selector
    /// parser (`empty index set`), so this is only reachable by a direct library caller.
    NoChangedLinesSelected,
    /// The addressed entry has no hunks to split: a binary patch, or a header-only entry such
    /// as a pure rename. Like [`SplitError::NoChangedLinesSelected`], only a direct library
    /// caller reaches it — the CLI resolves the address through `select::resolve_hunk`, which
    /// rejects both first.
    NotATextEntry,
    /// The address names a file or a hunk the patch does not have. Carries the 0-based index
    /// asked for and how many there are. Reachable only by a direct library caller, for the
    /// same reason as above.
    OutOfBounds {
        /// What was addressed.
        what: Addressed,
        /// The 0-based index the caller asked for.
        index: usize,
        /// How many exist.
        available: usize,
    },
}

impl fmt::Display for SplitError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            SplitError::NotAContextLine(n) => {
                write!(f, "new-file line {n} is a change line, not a context line")
            }
            SplitError::OutOfRange(n) => write!(f, "new-file line {n} is out of range"),
            SplitError::ChangedLineOutOfRange { index, changed } => write!(
                f,
                "changed-line index {index} is out of range \
                 (sub-hunk has {changed} changed line(s))"
            ),
            SplitError::NoChangedLinesSelected => {
                write!(f, "the selection references no changed lines")
            }
            SplitError::NotATextEntry => {
                write!(f, "the entry has no hunks to split")
            }
            SplitError::OutOfBounds {
                what,
                index,
                available,
            } => write!(f, "{what} index {index} is out of range (0..{available})"),
        }
    }
}

/// Lets callers treat it as a boxed [`std::error::Error`], as the Rust API guidelines ask
/// of a public error type.
impl std::error::Error for SplitError {}

/// What an out-of-range address named. Spelled out as a type rather than as the word that ends
/// up in the message: a caller matching on [`SplitError::OutOfBounds`] can tell the two apart
/// without comparing strings, and a misspelling stops compiling.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Addressed {
    /// A file entry of the patch.
    File,
    /// A hunk of one entry.
    Hunk,
}

impl fmt::Display for Addressed {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Addressed::File => write!(f, "file"),
            Addressed::Hunk => write!(f, "hunk"),
        }
    }
}

/// Auto-split a hunk into minimal sub-hunks at context gaps between change runs.
/// Returns the hunk unchanged (as a single element) if it has zero or one change run.
///
/// Each sub-hunk carries its surrounding context: the first sub-hunk gets all context
/// up to (and including) the inter-run boundary; subsequent sub-hunks start directly at
/// their change run (no leading shared boundary context). This produces non-overlapping
/// old-file ranges so the sub-hunks can be emitted together and applied with `git apply`.
pub fn auto_split_hunk(h: &Hunk) -> Vec<Hunk> {
    let runs = change_runs(h);
    if runs.len() <= 1 {
        return vec![h.clone()];
    }
    let n = h.lines.len();
    let mut result = Vec::with_capacity(runs.len());
    let mut pre = PrefixCounts::new();
    for ri in 0..runs.len() {
        // First sub-hunk starts at the beginning of the whole hunk.
        // Subsequent sub-hunks start directly at their change run (no shared boundary
        // context with the preceding sub-hunk) so that old-file ranges do not overlap.
        let lead_from = if ri == 0 { 0 } else { runs[ri].0 };
        // Trailing context: everything up to (but not including) the next change run,
        // or the end of the hunk for the last sub-hunk.
        let trail_to = if ri + 1 == runs.len() {
            n
        } else {
            runs[ri + 1].0
        };
        let slice = &h.lines[lead_from..trail_to];
        let counts = pre.upto(&h.lines, lead_from);
        result.push(rebuild_subhunk(h, slice, lead_from, counts));
    }
    result
}

/// Explicitly split a hunk at the given new-file line numbers (context lines only).
pub fn split_hunk_at(h: &Hunk, new_line_cuts: &[u32]) -> Result<Vec<Hunk>, SplitError> {
    let mut new_no = h.new_start;
    let mut cut_indices: Vec<usize> = Vec::new();
    let mut wanted: BTreeSet<u32> = new_line_cuts.iter().copied().collect();
    for (i, l) in h.lines.iter().enumerate() {
        let here = match l.kind {
            LineKind::Context | LineKind::Add => {
                let n = new_no;
                new_no += 1;
                n
            }
            LineKind::Del => continue,
        };
        if wanted.remove(&here) {
            if !matches!(l.kind, LineKind::Context) {
                return Err(SplitError::NotAContextLine(here));
            }
            cut_indices.push(i);
        }
    }
    if let Some(&missing) = wanted.iter().next() {
        return Err(SplitError::OutOfRange(missing));
    }
    if cut_indices.is_empty() {
        return Ok(vec![h.clone()]);
    }
    // Build slice boundaries: each piece ends just after its cut line (cut line becomes
    // trailing context of the piece), the next piece starts just after the cut line.
    // This produces non-overlapping old-file ranges while keeping trailing context in
    // each piece so that `git apply` can locate the patch position.
    let n = h.lines.len();
    let mut starts = vec![0usize];
    let mut ends: Vec<usize> = cut_indices.iter().map(|&ci| ci + 1).collect();
    ends.push(n);
    starts.extend(cut_indices.iter().map(|&ci| ci + 1));
    Ok(rebuild_pieces(h, &starts, &ends))
}

/// Replace hunk `hi` of `f` with the pieces `--at` asks for, keeping the lines recorded after a
/// hunk attached to the hunk they follow.
///
/// Splitting one hunk into `n` pieces moves every later hunk down by `n - 1`, and the lines
/// [`FileDiff::trailer`] holds must move with them: a line left at its old position is emitted
/// between the pieces, where `git apply` reads it as a patch fragment without a header — while
/// hunkpick, which checks hunk bodies and not the lines between them, still reports success.
/// Lines recorded right after the split hunk follow its last piece.
///
/// Returns how many pieces the hunk became. Errors as [`split_hunk_at`] does, plus
/// [`SplitError::NotATextEntry`] for a binary or header-only entry and
/// [`SplitError::OutOfBounds`] for a hunk index the file does not have. The CLI resolves the
/// address through `select::resolve_hunk` first, so from there neither is reachable; they are
/// for the direct library caller, who has no such step.
///
/// Prefer [`split_patch_hunk`] when the whole patch is at hand: this function cannot see
/// [`crate::model::Patch::no_trailing_newline`], and a cut that drops the tail of the last hunk
/// invalidates it.
pub fn split_file_hunk(
    f: &mut FileDiff,
    hi: usize,
    new_line_cuts: &[u32],
) -> Result<usize, SplitError> {
    let FileContent::Text(hunks) = &mut f.content else {
        return Err(SplitError::NotATextEntry);
    };
    if hi >= hunks.len() {
        return Err(SplitError::OutOfBounds {
            what: Addressed::Hunk,
            index: hi,
            available: hunks.len(),
        });
    }
    let pieces = split_hunk_at(&hunks[hi], new_line_cuts)?;
    let n = pieces.len();
    hunks.splice(hi..=hi, pieces);
    // A trailer entry counts the hunks before its line, so `at > hi` covers both the lines that
    // follow the split hunk itself (`at == hi + 1`) and those after any later hunk. Written as
    // `at + n - 1` rather than `at - 1 + n` so the sum is formed before the decrement: `n` is
    // zero when every piece was degenerate, and `at` is at least 1 here.
    for (at, _) in &mut f.trailer {
        if *at > hi {
            *at = *at + n - 1;
        }
    }
    Ok(n)
}

/// Split hunk `hi` of file `fi` and keep the patch's own trailing-newline flag honest.
///
/// [`split_file_hunk`] does the cut; what it cannot do is notice that the cut changed which line
/// the diff ends on. A piece with no changes is dropped, so cutting the last hunk of the last
/// file can leave the output ending before the input's last line — and
/// [`Patch::no_trailing_newline`] then removes the newline from a line that is not the one it
/// describes, truncating a line nobody asked to change. `git apply` reads the result as a
/// corrupt patch, while the internal check, which compares counts, order and anchors rather than
/// the bytes after the last hunk, reports success. This is the same rule
/// [`crate::select::select`] applies when it builds its result.
///
/// Returns how many pieces the hunk became; errors as [`split_file_hunk`] does, plus
/// [`SplitError::OutOfBounds`] for a file index the patch does not have.
pub fn split_patch_hunk(
    patch: &mut Patch,
    fi: usize,
    hi: usize,
    new_line_cuts: &[u32],
) -> Result<usize, SplitError> {
    if fi >= patch.files.len() {
        return Err(SplitError::OutOfBounds {
            what: Addressed::File,
            index: fi,
            available: patch.files.len(),
        });
    }
    // The flag is about one line of the input — its last — so only a cut of the last hunk of
    // the last file can invalidate it. Remember which line that is before the cut.
    let last_line_before = (fi + 1 == patch.files.len() && hi + 1 == patch.files[fi].hunk_count())
        .then(|| last_body_line(&patch.files[fi].content).cloned())
        .flatten();

    let pieces = split_file_hunk(&mut patch.files[fi], hi, new_line_cuts)?;

    if let Some(was) = last_line_before {
        let f = &patch.files[fi];
        // The entry ends on its tail when it has one, whichever way the hunks above were cut;
        // `select` reads the same rule off the same method where it builds its result.
        let still_there = f.ends_on_a_trailer_line() || last_body_line(&f.content) == Some(&was);
        patch.no_trailing_newline &= still_there;
    }
    Ok(pieces)
}

/// The last body line of an entry's last hunk — the line the entry's rendered form ends on,
/// unless a trailer follows it. `None` for a binary entry or one with no hunks.
fn last_body_line(content: &FileContent) -> Option<&Line> {
    match content {
        FileContent::Text(hunks) => hunks.last()?.lines.last(),
        FileContent::Binary(_) => None,
    }
}

/// Emit a piece of `h` that realises only the selected changed lines. `selected` holds 1-based
/// indices over `h`'s changed (Add/Del) lines in body order (`1..=changed`, where
/// `changed == added + deleted`). Each body line is rewritten:
///   - a context line is kept as context;
///   - a selected deletion stays a deletion; an unselected deletion becomes a context line (the
///     line is retained in this partial application, and it anchors the resulting hunk);
///   - a selected addition stays an addition; an unselected addition is omitted (not yet added).
///
/// Because unselected deletions are kept as context, every subset of changed lines is realisable
/// as one applicable hunk — there is no boundary restriction, and a deletion split by additions
/// (`+x -y +z`) can be addressed, keeping both leading and trailing context so the piece
/// anchors under `git apply`. The
/// old-side footprint (`old_start`, `old_lines`) is invariant: every original context and
/// deletion line is still present on the old side (a deletion either stays a deletion or becomes
/// context, both counting toward `old_lines`). Errors if `selected` is empty or references a
/// changed line outside `1..=changed`.
pub fn slice_changed_lines(h: &Hunk, selected: &BTreeSet<usize>) -> Result<Hunk, SplitError> {
    let changed = h.changed_lines().count();
    if selected.is_empty() {
        return Err(SplitError::NoChangedLinesSelected);
    }
    // `selected` is sorted (BTreeSet); parsing guarantees every index is >= 1, so only the upper
    // bound can be out of range.
    if let Some(&max) = selected.iter().next_back() {
        if max > changed {
            return Err(SplitError::ChangedLineOutOfRange {
                index: max,
                changed,
            });
        }
    }
    let mut lines: Vec<Line> = Vec::with_capacity(h.lines.len());
    let mut ci = 0usize; // 1-based changed-line counter
    for l in &h.lines {
        match l.kind {
            LineKind::Context => lines.push(l.clone()),
            LineKind::Del => {
                ci += 1;
                if selected.contains(&ci) {
                    lines.push(l.clone());
                } else {
                    // Retained line: emit as context so the hunk stays anchored.
                    lines.push(Line {
                        kind: LineKind::Context,
                        text: l.text.clone(),
                        no_newline: l.no_newline.clone(),
                    });
                }
            }
            LineKind::Add => {
                ci += 1;
                if selected.contains(&ci) {
                    lines.push(l.clone());
                }
                // Unselected addition: omit entirely.
            }
        }
    }
    fix_mid_hunk_no_newline(&mut lines);
    let (ctx, add, del) = count_kinds(&lines);
    Ok(Hunk {
        old_start: h.old_start,
        old_lines: ctx + del,
        new_start: h.new_start,
        new_lines: ctx + add,
        section: h.section.clone(),
        lines,
    })
}

/// Repair a `\ No newline at end of file` marker that is no longer at the end of the body.
///
/// A retained (unselected) deletion that sat at EOF became a context line still carrying the
/// no-newline marker. If it is no longer the last line — selected additions follow it — a plain
/// context line is both malformed (a mid-hunk no-newline marker) and wrong: appending after a
/// no-newline line requires that line to gain a trailing newline. Represent that the way git
/// does — delete the no-newline line and re-add it with a newline — so the piece applies. A
/// well-formed diff never carries a no-newline marker on a non-last context line, so this only
/// ever touches lines [`slice_changed_lines`] just converted from a deletion; deletions and
/// additions keep their own markers (a valid `-a\No newline +b` at EOF round-trips).
fn fix_mid_hunk_no_newline(lines: &mut Vec<Line>) {
    let n = lines.len();
    let needs_fix = |i: usize, l: &Line| {
        i + 1 < n && matches!(l.kind, LineKind::Context) && l.no_newline.is_some()
    };
    if !lines.iter().enumerate().any(|(i, l)| needs_fix(i, l)) {
        return;
    }
    let mut fixed: Vec<Line> = Vec::with_capacity(n + 1);
    for (i, l) in std::mem::take(lines).into_iter().enumerate() {
        if needs_fix(i, &l) {
            fixed.push(Line {
                kind: LineKind::Del,
                text: l.text.clone(),
                no_newline: l.no_newline.clone(),
            });
            fixed.push(Line {
                kind: LineKind::Add,
                text: l.text,
                no_newline: None,
            });
        } else {
            fixed.push(l);
        }
    }
    *lines = fixed;
}

/// Indices of maximal Add/Del runs as (start, end_exclusive).
fn change_runs(h: &Hunk) -> Vec<(usize, usize)> {
    let mut runs = Vec::new();
    let mut i = 0;
    while i < h.lines.len() {
        if matches!(h.lines[i].kind, LineKind::Add | LineKind::Del) {
            let start = i;
            while i < h.lines.len() && matches!(h.lines[i].kind, LineKind::Add | LineKind::Del) {
                i += 1;
            }
            runs.push((start, i));
        } else {
            i += 1;
        }
    }
    runs
}

/// Build non-overlapping sub-hunks from separate start/end index arrays.
///
/// Each piece `i` covers `h.lines[starts[i]..ends[i]]`. The cut (context) line becomes
/// the last line (trailing context) of the preceding piece; the next piece starts just
/// after it. This guarantees old-file ranges do not overlap while preserving at least one
/// context line in each piece so that `git apply` can locate the hunk without `--unidiff-zero`.
fn rebuild_pieces(h: &Hunk, starts: &[usize], ends: &[usize]) -> Vec<Hunk> {
    assert_eq!(starts.len(), ends.len());
    let mut result = Vec::new();
    let mut pre = PrefixCounts::new();
    for (start, end) in starts.iter().zip(ends.iter()) {
        // Skip empty pieces. A cut on the hunk's last line yields a trailing `start == end`
        // slice that would emit a degenerate `@@ -X,0 +Y,0 @@` stanza git rejects.
        if start >= end {
            continue;
        }
        let slice = &h.lines[*start..*end];
        // Skip context-only pieces. A cut on the hunk's first context line yields a
        // leading slice with no Add/Del lines, which produces a hunk with zero net
        // change that `git apply` rejects. Such a piece carries no change to stage.
        let (_, add, del) = count_kinds(slice);
        if add + del == 0 {
            continue;
        }
        let counts = pre.upto(&h.lines, *start);
        result.push(rebuild_subhunk(h, slice, *start, counts));
    }
    result
}

/// Running per-kind tally of the lines before a given index. Sub-hunks are built in
/// increasing start order, so the tally advances instead of being recounted from the hunk's
/// first line for every piece: recounting made auto-splitting quadratic in the number of
/// change runs (a 1.9 MB one-hunk diff with 64 000 runs took seconds).
struct PrefixCounts {
    scanned: usize,
    ctx: u32,
    add: u32,
    del: u32,
}

impl PrefixCounts {
    fn new() -> Self {
        Self {
            scanned: 0,
            ctx: 0,
            add: 0,
            del: 0,
        }
    }

    /// Counts of `lines[..upto]`. `upto` must not go backwards.
    fn upto(&mut self, lines: &[Line], upto: usize) -> (u32, u32, u32) {
        debug_assert!(
            upto >= self.scanned,
            "sub-hunk starts must be non-decreasing"
        );
        for l in &lines[self.scanned..upto] {
            match l.kind {
                LineKind::Context => self.ctx += 1,
                LineKind::Add => self.add += 1,
                LineKind::Del => self.del += 1,
            }
        }
        self.scanned = upto;
        (self.ctx, self.add, self.del)
    }
}

/// The start one side of a sub-hunk must carry: the parent's start advanced by `off`, the count
/// of that side's lines before the slice.
///
/// A side with no lines of its own reports the *preceding* line — git writes `@@ -3,0 +4 @@` for
/// a line appended after old line 3 — so the advanced position is one line too far. At `off == 0`
/// the parent header already carries the normalised value and is taken as is. Saturating, like
/// [`crate::renumber::anchor`]: the starts come from the input header, and a sum past `u32::MAX`
/// must clamp rather than wrap on a synthetic diff.
fn side_start(parent_start: u32, off: u32, lines: u32) -> u32 {
    let start = parent_start.saturating_add(off);
    if lines == 0 && off > 0 {
        start - 1
    } else {
        start
    }
}

/// Build a Hunk from a slice of `h.lines` starting at absolute index `abs_start`, whose
/// preceding lines tally `pre` (context, added, deleted), recomputing old/new start offsets
/// and line counts.
fn rebuild_subhunk(h: &Hunk, slice: &[Line], abs_start: usize, pre: (u32, u32, u32)) -> Hunk {
    // Old/new offsets of the slice are the line counts of everything before it; the slice's
    // own old/new lengths are its counts. Context lines advance both sides.
    let (pre_ctx, pre_add, pre_del) = pre;
    let old_off = pre_ctx + pre_del;
    let new_off = pre_ctx + pre_add;
    let (ctx, add, del) = count_kinds(slice);
    let old_lines = ctx + del;
    let new_lines = ctx + add;
    Hunk {
        old_start: side_start(h.old_start, old_off, old_lines),
        old_lines,
        new_start: side_start(h.new_start, new_off, new_lines),
        new_lines,
        section: if abs_start == 0 {
            h.section.clone()
        } else {
            Vec::new()
        },
        lines: slice.to_vec(),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::emit::emit;
    use crate::gittest::applies_to_file;
    use crate::model::{FileContent, FileDiff, Patch};
    use crate::parser::parse;

    fn hunk(src: &str) -> Hunk {
        let p = parse(src.as_bytes()).unwrap();
        let FileContent::Text(h) = &p.files[0].content else {
            panic!()
        };
        h[0].clone()
    }

    /// Reassemble a one-file patch from sub-hunks, as raw bytes, for `git apply --check`.
    /// Renders through [`emit`] so the pieces are spelled exactly as hunkpick spells them —
    /// a hand-rolled renderer here would let a rendering bug pass unnoticed.
    fn assemble(subs: &[Hunk]) -> Vec<u8> {
        emit(&Patch {
            preamble: Vec::new(),
            no_trailing_newline: false,
            files: vec![FileDiff {
                headers: vec![b"--- a/f".to_vec(), b"+++ b/f".to_vec()],
                trailer: Vec::new(),
                old_path: Some(b"f".to_vec()),
                new_path: Some(b"f".to_vec()),
                content: FileContent::Text(subs.to_vec()),
            }],
        })
    }

    const TWO_CHANGES: &str = "\
diff --git a/f b/f
--- a/f
+++ b/f
@@ -1,5 +1,5 @@
 a
-b
+B
 c
-d
+D
 e
";

    /// A side with no lines of its own reports the line *before* its empty range, the way git
    /// writes it (`@@ -3,0 +4 @@`). Adding the offset to the parent's start points one line
    /// past that, so the header describes a position the result does not have.
    #[test]
    fn a_side_with_no_lines_carries_the_preceding_line_number() {
        // a,b,c with b -> B and d appended: git renders the pair as one hunk, and `git diff -U0`
        // of the same change writes `@@ -3,0 +4 @@` for the appended line.
        let h = hunk(
            "\
diff --git a/f b/f
--- a/f
+++ b/f
@@ -1,3 +1,4 @@
 a
-b
+B
 c
+d
",
        );
        let subs = auto_split_hunk(&h);
        assert_eq!(subs.len(), 2);
        assert_eq!((subs[1].old_start, subs[1].old_lines), (3, 0));

        // The mirror case: a,b,c,d,e -> a,c leaves a pure deletion whose new side is empty.
        let h = hunk(
            "\
diff --git a/f b/f
--- a/f
+++ b/f
@@ -1,5 +1,2 @@
 a
-b
 c
-d
-e
",
        );
        let subs = auto_split_hunk(&h);
        assert_eq!(subs.len(), 2);
        assert_eq!((subs[1].new_start, subs[1].new_lines), (2, 0));
    }

    #[test]
    fn splits_two_changes_separated_by_context() {
        let h = hunk(TWO_CHANGES);
        let subs = auto_split_hunk(&h);
        assert_eq!(subs.len(), 2);
        assert_eq!(subs[0].old_start, 1);
        assert_eq!(
            subs[0]
                .lines
                .iter()
                .filter(|l| l.kind == LineKind::Add)
                .count(),
            1
        );
        // Each sub-hunk's header counts must match its body.
        for s in &subs {
            let ctx = s
                .lines
                .iter()
                .filter(|l| l.kind == LineKind::Context)
                .count() as u32;
            let del = s.lines.iter().filter(|l| l.kind == LineKind::Del).count() as u32;
            let add = s.lines.iter().filter(|l| l.kind == LineKind::Add).count() as u32;
            assert_eq!(s.old_lines, ctx + del);
            assert_eq!(s.new_lines, ctx + add);
        }
    }

    #[test]
    fn single_change_returns_one() {
        let h = hunk(
            "\
diff --git a/f b/f
--- a/f
+++ b/f
@@ -1,3 +1,3 @@
 a
-b
+B
 c
",
        );
        assert_eq!(auto_split_hunk(&h).len(), 1);
    }

    #[test]
    fn explicit_split_on_context_line() {
        let h = hunk(TWO_CHANGES);
        // New-file line numbers: a=1 B=2 c=3 D=4 e=5. Cut at context line 3 (c).
        let subs = split_hunk_at(&h, &[3]).unwrap();
        assert_eq!(subs.len(), 2);
        // The cut line c becomes trailing context of piece 0; piece 1 starts after it at
        // new-file line 4 (the -d/+D change). This keeps old-file ranges non-overlapping.
        assert_eq!(subs[1].new_start, 4);
        for s in &subs {
            let ctx = s
                .lines
                .iter()
                .filter(|l| l.kind == LineKind::Context)
                .count() as u32;
            let del = s.lines.iter().filter(|l| l.kind == LineKind::Del).count() as u32;
            let add = s.lines.iter().filter(|l| l.kind == LineKind::Add).count() as u32;
            assert_eq!(s.old_lines, ctx + del);
            assert_eq!(s.new_lines, ctx + add);
        }
    }

    #[test]
    fn explicit_split_on_first_context_line_drops_context_only_piece() {
        let h = hunk(TWO_CHANGES);
        // New-file line numbers: a=1 B=2 c=3 D=4 e=5. Cut at the first context line a=1.
        // The leading piece would be context-only (just `a`); it carries no change and
        // must be dropped rather than emitted as a degenerate zero-change hunk.
        let subs = split_hunk_at(&h, &[1]).unwrap();
        for s in &subs {
            let add = s.lines.iter().filter(|l| l.kind == LineKind::Add).count();
            let del = s.lines.iter().filter(|l| l.kind == LineKind::Del).count();
            assert!(add + del > 0, "no context-only sub-hunk emitted");
            assert!(s.old_lines > 0 && s.new_lines > 0);
        }
    }

    #[test]
    fn explicit_split_rejects_change_line() {
        let h = hunk(
            "\
diff --git a/f b/f
--- a/f
+++ b/f
@@ -1,3 +1,3 @@
 a
-b
+B
 c
",
        );
        // new-file line 2 is "B" (an Add) -> not a context line.
        assert_eq!(split_hunk_at(&h, &[2]), Err(SplitError::NotAContextLine(2)));
    }

    #[test]
    fn explicit_split_out_of_range() {
        let h = hunk(TWO_CHANGES);
        assert_eq!(split_hunk_at(&h, &[99]), Err(SplitError::OutOfRange(99)));
    }

    #[test]
    fn explicit_split_on_last_context_line_drops_empty_piece() {
        // Cutting at the hunk's final context line leaves nothing after the cut, so the
        // trailing piece would be an empty `@@ -X,0 +Y,0 @@` stanza that `git apply`
        // rejects as a corrupt patch. The split must drop such degenerate pieces.
        let h = hunk(
            "\
diff --git a/f b/f
--- a/f
+++ b/f
@@ -1,3 +1,3 @@
 a
-b
+B
 c
",
        );
        // New-file line numbers: a=1 B=2 c=3. Cut at context line 3 (c), the last line.
        let subs = split_hunk_at(&h, &[3]).unwrap();
        for s in &subs {
            assert!(!s.lines.is_empty(), "empty sub-hunk piece produced: {s:?}");
            assert!(
                s.old_lines > 0 || s.new_lines > 0,
                "degenerate zero-count sub-hunk produced: {s:?}"
            );
        }
        // The only meaningful piece is the change itself; the empty trailing piece is gone.
        assert_eq!(subs.len(), 1);
    }

    #[test]
    fn explicit_split_combined_applies_via_git() {
        let h = hunk(TWO_CHANGES);
        let pieces = split_hunk_at(&h, &[3]).unwrap();
        let diff = assemble(&pieces);
        assert!(
            applies_to_file(&diff, "a\nb\nc\nd\ne\n"),
            "git apply --check failed for combined explicit-split patch:\n{}",
            String::from_utf8_lossy(&diff)
        );
    }

    #[test]
    fn auto_split_subhunks_apply_via_git() {
        let h = hunk(TWO_CHANGES);
        let subs = auto_split_hunk(&h);
        // Reassemble a patch with all sub-hunks for file "f".
        let diff = assemble(&subs);
        assert!(
            applies_to_file(&diff, "a\nb\nc\nd\ne\n"),
            "git apply --check failed for split patch:\n{}",
            String::from_utf8_lossy(&diff)
        );
    }

    /// True if the assembled patch of `subs` applies cleanly to a file `f` seeded with
    /// `file_content` in a fresh git repo (`git apply --check`).
    fn git_apply_ok(subs: &[Hunk], file_content: &str) -> bool {
        applies_to_file(&assemble(subs), file_content)
    }

    /// Build a BTreeSet of the given 1-based changed-line indices.
    fn sel(indices: &[usize]) -> BTreeSet<usize> {
        indices.iter().copied().collect()
    }

    const REPLACEMENT: &str = "\
diff --git a/f b/f
--- a/f
+++ b/f
@@ -1,2 +1,2 @@
-a
-b
+A
+B
";

    #[test]
    fn slice_changed_separates_deletions() {
        // Select both deletions (changed lines 1,2): a pure deletion piece.
        let h = hunk(REPLACEMENT);
        let p = slice_changed_lines(&h, &sel(&[1, 2])).unwrap();
        assert_eq!(p.old_lines, 2);
        assert_eq!(p.new_lines, 0);
        assert!(p.lines.iter().all(|l| l.kind == LineKind::Del));
    }

    #[test]
    fn slice_changed_separates_additions() {
        // Select both additions (changed lines 3,4): the deletions become context so the piece
        // keeps an anchor; it is not a zero-context hunk.
        let h = hunk(REPLACEMENT);
        let p = slice_changed_lines(&h, &sel(&[3, 4])).unwrap();
        assert_eq!(p.old_lines, 2); // two context lines (the retained deletions)
        assert_eq!(p.new_lines, 4); // two context + two additions
        assert_eq!(
            p.lines.iter().filter(|l| l.kind == LineKind::Del).count(),
            0
        );
        assert_eq!(
            p.lines
                .iter()
                .filter(|l| l.kind == LineKind::Context)
                .count(),
            2
        );
        assert_eq!(
            p.lines.iter().filter(|l| l.kind == LineKind::Add).count(),
            2
        );
    }

    #[test]
    fn slice_changed_del_and_add_pieces_apply_independently_via_git() {
        // The key agent operation: stage a replacement's removals separately from its insertions.
        // Both pieces must apply to the original file on their own.
        let h = hunk(REPLACEMENT);
        let dels = slice_changed_lines(&h, &sel(&[1, 2])).unwrap();
        let adds = slice_changed_lines(&h, &sel(&[3, 4])).unwrap();
        assert!(git_apply_ok(&[dels], "a\nb\n"), "deletion piece must apply");
        assert!(git_apply_ok(&[adds], "a\nb\n"), "addition piece must apply");
    }

    const ADD_SPLIT_BY_DEL: &str = "\
diff --git a/f b/f
--- a/f
+++ b/f
@@ -1,1 +1,2 @@
+x
-y
+z
";

    #[test]
    fn slice_changed_addresses_deletion_split_by_additions() {
        // `+x -y +z`: the deletion (changed line 2) is surrounded by additions.
        // `slice_changed_lines` isolates it: select just the deletion.
        let h = hunk(ADD_SPLIT_BY_DEL);
        let p = slice_changed_lines(&h, &sel(&[2])).unwrap();
        assert_eq!(p.old_lines, 1);
        assert_eq!(p.new_lines, 0);
        assert_eq!(p.lines.len(), 1);
        assert_eq!(p.lines[0].kind, LineKind::Del);
        assert_eq!(p.lines[0].text, b"y");
        assert!(git_apply_ok(&[p], "y\n"), "isolated deletion must apply");
    }

    #[test]
    fn slice_changed_selecting_additions_around_deletion_keeps_it_as_context() {
        // Select the two additions of `+x -y +z`; the deletion becomes context and anchors it.
        let h = hunk(ADD_SPLIT_BY_DEL);
        let p = slice_changed_lines(&h, &sel(&[1, 3])).unwrap();
        assert_eq!(p.old_lines, 1); // the retained deletion, now context
        assert_eq!(p.new_lines, 3); // context + two additions
        assert!(git_apply_ok(&[p], "y\n"), "addition piece must apply");
    }

    #[test]
    fn slice_changed_roundtrip_full_selection_reproduces_body() {
        // Selecting every changed line reproduces the original sub-hunk body.
        let h = hunk(REPLACEMENT);
        let all = slice_changed_lines(&h, &sel(&[1, 2, 3, 4])).unwrap();
        assert_eq!(all.lines, h.lines);
    }

    #[test]
    fn slice_changed_readds_no_newline_line_when_additions_follow() {
        // Old file `a` has no trailing newline; it is replaced by `b\nc\n`. Selecting only the
        // additions retains `-a` (no_newline). Because content now follows it, `a` must gain a
        // trailing newline, so the piece deletes the no-newline `a` and re-adds it with a newline
        // (git's representation) rather than emitting a malformed mid-hunk no-newline context.
        let h = hunk(
            "\
diff --git a/f b/f
--- a/f
+++ b/f
@@ -1 +1,2 @@
-a
\\ No newline at end of file
+b
+c
",
        );
        // Changed lines: 1=`-a`(no_newline), 2=`+b`, 3=`+c`. Select the two additions.
        let p = slice_changed_lines(&h, &sel(&[2, 3])).unwrap();
        assert_eq!(p.lines[0].kind, LineKind::Del);
        assert_eq!(p.lines[0].text, b"a");
        assert!(
            p.lines[0].no_newline.is_some(),
            "the deleted `a` keeps its no-newline marker"
        );
        assert_eq!(p.lines[1].kind, LineKind::Add);
        assert_eq!(p.lines[1].text, b"a");
        assert!(
            p.lines[1].no_newline.is_none(),
            "the re-added `a` gains a trailing newline"
        );
        // old side: one deletion; new side: re-added a + b + c.
        assert_eq!(p.old_lines, 1);
        assert_eq!(p.new_lines, 3);
        assert!(
            git_apply_ok(&[p], "a"),
            "addition piece must apply to `a` (no trailing newline)"
        );
    }

    /// Splitting the first of two hunks moves the second one down, and every line recorded
    /// after a hunk has to move with it: a blank separator between the hunks belongs after the
    /// split hunk's last piece, and the file's signature stays after the final hunk.
    #[test]
    fn split_file_hunk_moves_trailing_lines_with_their_hunks() {
        let p = parse(
            concat!(
                "diff --git a/f b/f\n--- a/f\n+++ b/f\n",
                "@@ -1,5 +1,5 @@\n a\n-b\n+B\n c\n-d\n+D\n e\n",
                "\n",
                "@@ -20,3 +20,3 @@\n p\n-q\n+Q\n r\n",
                "-- \n2.53.0\n",
            )
            .as_bytes(),
        )
        .unwrap();
        let mut f = p.files[0].clone();
        assert_eq!(
            f.trailer,
            vec![
                (1, b"".to_vec()),
                (2, b"-- ".to_vec()),
                (2, b"2.53.0".to_vec())
            ],
            "positions before the split"
        );

        // New-file line numbers of the first hunk: a=1 B=2 c=3 D=4 e=5. Cut at context line 3.
        assert_eq!(split_file_hunk(&mut f, 0, &[3]).unwrap(), 2);
        assert_eq!(
            f.trailer,
            vec![
                (2, b"".to_vec()),
                (3, b"-- ".to_vec()),
                (3, b"2.53.0".to_vec())
            ],
            "each line follows the hunk it followed before the split"
        );
    }

    #[test]
    fn slice_changed_out_of_range_and_empty_error() {
        let h = hunk(REPLACEMENT); // 4 changed lines
        assert!(matches!(
            slice_changed_lines(&h, &sel(&[5])),
            Err(SplitError::ChangedLineOutOfRange {
                index: 5,
                changed: 4
            })
        ));
        assert_eq!(
            slice_changed_lines(&h, &sel(&[])),
            Err(SplitError::NoChangedLinesSelected)
        );
    }

    /// A library caller has no `resolve_hunk` step in front of it, so the addresses it passes
    /// have to be answered rather than trusted. These three used to be an `unreachable!` and two
    /// out-of-range indexings — a panic where the neighbouring `NoChangedLinesSelected` already
    /// established that the direct caller gets an error.
    #[test]
    fn an_address_the_patch_does_not_have_is_an_error_not_a_panic() {
        const BINARY: &str = "\
diff --git a/f b/f
GIT binary patch
literal 4
Lc$_iAxSk1
";
        let mut p = parse(BINARY.as_bytes()).unwrap();
        assert_eq!(
            split_file_hunk(&mut p.files[0], 0, &[1]),
            Err(SplitError::NotATextEntry)
        );

        let mut p = parse(TWO_CHANGES.as_bytes()).unwrap();
        assert_eq!(
            split_file_hunk(&mut p.files[0], 7, &[1]),
            Err(SplitError::OutOfBounds {
                what: Addressed::Hunk,
                index: 7,
                available: 1
            })
        );
        assert_eq!(
            split_patch_hunk(&mut p, 3, 0, &[1]),
            Err(SplitError::OutOfBounds {
                what: Addressed::File,
                index: 3,
                available: 1
            })
        );
    }

    /// The trailing-newline rule of [`split_patch_hunk`], at the level it is decided: cutting
    /// away the piece that held the input's last line means the result no longer ends there, so
    /// the flag has to go. The CLI test `split_that_drops_the_tail_keeps_the_final_newline`
    /// checks the same thing through the process; this one names the condition.
    #[test]
    fn a_cut_that_drops_the_tail_clears_the_trailing_newline_flag() {
        // ` e` is the input's last line and carries no change, so the piece holding it is
        // dropped: new-file lines are a=1 B=2 c=3 d=4 e=5, and the cut is at 3.
        const NO_FINAL_NEWLINE: &str = "\
diff --git a/f b/f
--- a/f
+++ b/f
@@ -1,5 +1,5 @@
 a
-b
+B
 c
 d
 e";
        let mut p = parse(NO_FINAL_NEWLINE.as_bytes()).unwrap();
        assert!(p.no_trailing_newline, "the input ends mid-line");
        split_patch_hunk(&mut p, 0, 0, &[3]).unwrap();
        assert!(
            !p.no_trailing_newline,
            "the result ends on ` c`, not on the input's last line"
        );

        // The same cut where both pieces carry a change keeps the tail, so the flag stays.
        const BOTH_PIECES_CHANGE: &str = "\
diff --git a/f b/f
--- a/f
+++ b/f
@@ -1,5 +1,5 @@
 a
-b
+B
 c
-d
+D
 e";
        let mut p = parse(BOTH_PIECES_CHANGE.as_bytes()).unwrap();
        split_patch_hunk(&mut p, 0, 0, &[3]).unwrap();
        assert!(p.no_trailing_newline, "the result still ends on ` e`");
    }
    /// A signature line is emitted after the last hunk, so the entry ends on it whichever way the
    /// hunks above were cut. Dropping the flag here removes the newline from a line the input did
    /// end with, and `git apply` reads the result as a corrupt patch.
    #[test]
    fn a_cut_under_a_signature_leaves_the_last_line_of_the_input_in_place() {
        const SIGNED: &str = "\
diff --git a/f b/f
--- a/f
+++ b/f
@@ -1,5 +1,5 @@
 a
-b
+B
 c
 d
 e
-- 
2.53.0";
        let mut p = parse(SIGNED.as_bytes()).unwrap();
        assert!(p.no_trailing_newline, "the input ends mid-line");
        split_patch_hunk(&mut p, 0, 0, &[3]).unwrap();
        assert!(
            p.no_trailing_newline,
            "the output still ends on `2.53.0`, the line the input ended on"
        );
        assert!(
            !emit(&p).ends_with(b"\n"),
            "a newline the input did not have must not appear"
        );
    }
}