hunkpick 0.7.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
use crate::model::*;
use crate::select::build_view;
use serde::Serialize;
use std::fmt::Write as _;

#[derive(Serialize)]
struct JsonChangedLine {
    /// 1-based index over the sub-hunk's changed (`+`/`-`) lines in body order. Pass a set of
    /// these to `select INDEX@L<set>` to stage an arbitrary subset of the sub-hunk's changes.
    i: usize,
    /// `"add"` for an inserted line, `"del"` for a removed one.
    kind: &'static str,
    /// The line text (without the leading marker), decoded lossily for display.
    text: String,
}

#[derive(Serialize)]
struct JsonHunk {
    index: usize,
    /// Stable content id; pass as `@<id>` to `select`. See [`crate::subhunk_id`].
    id: String,
    /// How many sub-hunks in the whole patch share this id. `1` means the id is unique
    /// (so `@<id>` addresses exactly this sub-hunk); `> 1` means `@<id>` would select all
    /// of them — use `path:N` to pick one.
    id_count: usize,
    old_start: u32,
    old_lines: u32,
    new_start: u32,
    new_lines: u32,
    added: u32,
    deleted: u32,
    /// True when the sub-hunk is all additions (a file-creation or pure-append block).
    addition_only: bool,
    /// The sub-hunk's changed (`+`/`-`) lines, in body order, each with its 1-based index for
    /// `select INDEX@L<set>`. Additions and deletions share one numbering. Empty for a binary
    /// or all-context sub-hunk.
    changed_lines: Vec<JsonChangedLine>,
    header: String,
    preview: String,
}

/// The sub-hunk's changed (`+`/`-`) lines as JSON entries, 1-based in body order.
fn changed_lines(h: &Hunk) -> Vec<JsonChangedLine> {
    h.changed_lines()
        .map(|(i, l)| JsonChangedLine {
            i,
            kind: match l.kind {
                LineKind::Add => "add",
                LineKind::Del => "del",
                LineKind::Context => unreachable!("context lines are filtered out"),
            },
            text: String::from_utf8_lossy(&l.text).into_owned(),
        })
        .collect()
}

#[derive(Serialize)]
struct JsonFile {
    path: String,
    binary: bool,
    hunks: Vec<JsonHunk>,
}

fn header_string(h: &Hunk) -> String {
    let old = crate::emit::fmt_range(h.old_start, h.old_lines);
    let new = crate::emit::fmt_range(h.new_start, h.new_lines);
    let mut s = format!("@@ -{old} +{new} @@");
    if !h.section.is_empty() {
        s.push(' ');
        s.push_str(&String::from_utf8_lossy(&h.section));
    }
    s
}

/// True when the sub-hunk consists solely of additions (no context, no deletions): a
/// file-creation or pure-append block. An empty body is not addition-only.
fn addition_only(h: &Hunk) -> bool {
    !h.lines.is_empty() && h.lines.iter().all(|l| matches!(l.kind, LineKind::Add))
}

fn preview(h: &Hunk) -> String {
    for l in &h.lines {
        match l.kind {
            LineKind::Add => return format!("+{}", String::from_utf8_lossy(&l.text)),
            LineKind::Del => return format!("-{}", String::from_utf8_lossy(&l.text)),
            LineKind::Context => {}
        }
    }
    String::new()
}

pub fn list_json(patch: &Patch) -> String {
    use crate::subhunk_id::subhunk_hash;
    let view = build_view(patch);
    // Hash each sub-hunk once, keeping the per-file hashes alongside the view so the second
    // pass reuses them instead of recomputing. `hashes[vi][si]` is the hash of the `si`-th
    // sub-hunk of the `vi`-th view entry.
    let hashes: Vec<Vec<u64>> = view
        .iter()
        .map(|(fi, subs)| {
            let f = &patch.files[*fi];
            subs.iter().map(|h| subhunk_hash(f, h)).collect()
        })
        .collect();
    // Histogram of content hashes across the whole patch, so each sub-hunk can report how
    // many sub-hunks share its id (`id_count`).
    let mut counts: std::collections::HashMap<u64, usize> = std::collections::HashMap::new();
    for file_hashes in &hashes {
        for hash in file_hashes {
            *counts.entry(*hash).or_insert(0) += 1;
        }
    }
    let mut files = Vec::new();
    for (vi, (fi, subs)) in view.iter().enumerate() {
        let f = &patch.files[*fi];
        let binary = matches!(f.content, FileContent::Binary(_));
        let hunks = subs
            .iter()
            .enumerate()
            .map(|(i, h)| {
                let (added, deleted) = h.change_counts();
                let hash = hashes[vi][i];
                JsonHunk {
                    index: i + 1,
                    id: format!("{hash:016x}"),
                    id_count: counts[&hash],
                    old_start: h.old_start,
                    old_lines: h.old_lines,
                    new_start: h.new_start,
                    new_lines: h.new_lines,
                    added,
                    deleted,
                    addition_only: addition_only(h),
                    changed_lines: changed_lines(h),
                    header: header_string(h),
                    preview: preview(h),
                }
            })
            .collect();
        files.push(JsonFile {
            path: f.display_path(),
            binary,
            hunks,
        });
    }
    // Infallible in practice: `JsonFile` serializes owned strings, integers and bools with
    // no map keys or custom `Serialize` that could error. `expect` documents that invariant.
    serde_json::to_string_pretty(&files).expect("serializing the JSON hunk list cannot fail")
}

// SGR (Select Graphic Rendition) parameter codes used for the human-readable listing.
const SGR_BOLD: &str = "1";
const SGR_RED: &str = "31";
const SGR_GREEN: &str = "32";

fn paint(s: &str, code: &str, color: bool) -> String {
    if color {
        format!("\x1b[{code}m{s}\x1b[0m")
    } else {
        s.to_string()
    }
}

pub fn list_human(patch: &Patch, color: bool) -> String {
    let view = build_view(patch);
    let mut out = String::new();
    for (fi, subs) in &view {
        let f = &patch.files[*fi];
        out.push_str(&f.display_path());
        if matches!(f.content, FileContent::Binary(_)) {
            out.push_str(" (binary)\n");
            continue;
        }
        out.push('\n');
        for (i, h) in subs.iter().enumerate() {
            let (added, deleted) = h.change_counts();
            let idx = paint(&format!("[{}]", i + 1), SGR_BOLD, color);
            let id = crate::subhunk_id::subhunk_id(f, h);
            let pv = preview(h);
            let pv = if pv.starts_with('+') {
                paint(&pv, SGR_GREEN, color)
            } else if pv.starts_with('-') {
                paint(&pv, SGR_RED, color)
            } else {
                pv
            };
            // Write directly into the output buffer rather than building a temporary
            // String per line (this runs once per sub-hunk).
            let marker = if addition_only(h) { " [+add]" } else { "" };
            let _ = writeln!(
                out,
                "  {idx} {id} {}  +{added} -{deleted}{marker}  {pv}",
                header_string(h)
            );
        }
    }
    out
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::parser::parse;

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

    // Two byte-identical changes (same context and edit) -> same content id.
    const DUP: &str = "\
diff --git a/f b/f
--- a/f
+++ b/f
@@ -1,3 +1,3 @@
 a
-x
+Y
 b
@@ -10,3 +10,3 @@
 a
-x
+Y
 b
";

    #[test]
    fn json_id_count_is_one_for_unique_ids() {
        let p = parse(MULTI.as_bytes()).unwrap();
        let v: serde_json::Value = serde_json::from_str(&list_json(&p)).unwrap();
        assert_eq!(v[0]["hunks"][0]["id_count"], 1);
        assert_eq!(v[0]["hunks"][1]["id_count"], 1);
    }

    #[test]
    fn json_id_count_marks_duplicates() {
        let p = parse(DUP.as_bytes()).unwrap();
        let v: serde_json::Value = serde_json::from_str(&list_json(&p)).unwrap();
        let hunks = &v[0]["hunks"];
        assert_eq!(
            hunks[0]["id"], hunks[1]["id"],
            "identical changes share an id"
        );
        assert_eq!(hunks[0]["id_count"], 2);
        assert_eq!(hunks[1]["id_count"], 2);
    }

    #[test]
    fn json_has_two_subhunks() {
        let p = parse(MULTI.as_bytes()).unwrap();
        let j = list_json(&p);
        let v: serde_json::Value = serde_json::from_str(&j).unwrap();
        assert_eq!(v[0]["path"], "f");
        assert_eq!(v[0]["hunks"].as_array().unwrap().len(), 2);
        assert_eq!(v[0]["hunks"][0]["index"], 1);
    }

    #[test]
    fn json_includes_subhunk_id() {
        let p = parse(MULTI.as_bytes()).unwrap();
        let j = list_json(&p);
        let v: serde_json::Value = serde_json::from_str(&j).unwrap();
        let id = v[0]["hunks"][0]["id"].as_str().expect("id field present");
        assert_eq!(id.len(), 16, "id must be 16 hex chars");
        let view = crate::select::build_view(&p);
        let expected = crate::subhunk_id::subhunk_id(&p.files[0], &view[0].1[0]);
        assert_eq!(id, expected, "json id must match the canonical sub-hunk id");
    }

    #[test]
    fn human_shows_subhunk_id() {
        let p = parse(MULTI.as_bytes()).unwrap();
        let out = list_human(&p, false);
        let view = crate::select::build_view(&p);
        let id = crate::subhunk_id::subhunk_id(&p.files[0], &view[0].1[0]);
        assert!(
            out.contains(&id),
            "human output must contain id {id}:\n{out}"
        );
    }

    #[test]
    fn human_lists_indices() {
        let p = parse(MULTI.as_bytes()).unwrap();
        let out = list_human(&p, false);
        assert!(out.contains("f"));
        assert!(out.contains("[1]"));
        assert!(out.contains("[2]"));
    }

    const NEW_FILE: &str = "\
diff --git a/f b/f
new file mode 100644
--- /dev/null
+++ b/f
@@ -0,0 +1,2 @@
+x
+y
";

    #[test]
    fn json_marks_addition_only() {
        let p = parse(NEW_FILE.as_bytes()).unwrap();
        let v: serde_json::Value = serde_json::from_str(&list_json(&p)).unwrap();
        assert_eq!(v[0]["hunks"][0]["addition_only"], true);
    }

    #[test]
    fn json_addition_only_false_for_mixed() {
        let p = parse(MULTI.as_bytes()).unwrap();
        let v: serde_json::Value = serde_json::from_str(&list_json(&p)).unwrap();
        assert_eq!(v[0]["hunks"][0]["addition_only"], false);
    }

    #[test]
    fn human_marks_addition_only() {
        let p = parse(NEW_FILE.as_bytes()).unwrap();
        let out = list_human(&p, false);
        assert!(
            out.contains("[+add]"),
            "addition-only marker missing:\n{out}"
        );
    }

    #[test]
    fn human_no_marker_for_mixed() {
        let p = parse(MULTI.as_bytes()).unwrap();
        let out = list_human(&p, false);
        assert!(
            !out.contains("[+add]"),
            "addition-only marker must not appear for a mixed sub-hunk:\n{out}"
        );
    }

    #[test]
    fn json_lists_changed_lines_with_indices() {
        // The first sub-hunk of MULTI is the b->B change: one deletion, one addition, numbered
        // 1 and 2 in body order (deletion first).
        let p = parse(MULTI.as_bytes()).unwrap();
        let v: serde_json::Value = serde_json::from_str(&list_json(&p)).unwrap();
        let cl = &v[0]["hunks"][0]["changed_lines"];
        assert_eq!(cl.as_array().unwrap().len(), 2);
        assert_eq!(cl[0]["i"], 1);
        assert_eq!(cl[0]["kind"], "del");
        assert_eq!(cl[0]["text"], "b");
        assert_eq!(cl[1]["i"], 2);
        assert_eq!(cl[1]["kind"], "add");
        assert_eq!(cl[1]["text"], "B");
    }

    #[test]
    fn json_changed_lines_number_across_dels_and_adds() {
        // A replacement `-a -b +A +B`: four changed lines numbered 1..4 (both deletions, then
        // both additions), matching the `select INDEX@L<set>` numbering.
        let p = parse(
            "\
diff --git a/f b/f
--- a/f
+++ b/f
@@ -1,2 +1,2 @@
-a
-b
+A
+B
"
            .as_bytes(),
        )
        .unwrap();
        let v: serde_json::Value = serde_json::from_str(&list_json(&p)).unwrap();
        let cl = v[0]["hunks"][0]["changed_lines"]
            .as_array()
            .unwrap()
            .clone();
        let kinds: Vec<&str> = cl.iter().map(|e| e["kind"].as_str().unwrap()).collect();
        assert_eq!(kinds, vec!["del", "del", "add", "add"]);
        let idx: Vec<u64> = cl.iter().map(|e| e["i"].as_u64().unwrap()).collect();
        assert_eq!(idx, vec![1, 2, 3, 4]);
    }

    #[test]
    fn deletion_only_is_not_flagged() {
        // A pure-deletion sub-hunk is not addition-only: deletions are not `LineKind::Add`.
        let p = parse(
            "\
diff --git a/f b/f
--- a/f
+++ b/f
@@ -1,2 +1,1 @@
 keep
-gone
"
            .as_bytes(),
        )
        .unwrap();
        let v: serde_json::Value = serde_json::from_str(&list_json(&p)).unwrap();
        assert_eq!(v[0]["hunks"][0]["addition_only"], false);
        assert!(!list_human(&p, false).contains("[+add]"));
    }
}