Skip to main content

gitpoulpi_core/domain/
split.rs

1//! Split one commit into several (see the split-commit design).
2//!
3//! The types are shared by both backends, the daemon, the CLI/MCP and the
4//! TUI editor. [`validate_split`] is the one pure check all of them run, so a
5//! plan the editor accepts is a plan the backend accepts.
6
7use std::collections::HashSet;
8use std::path::PathBuf;
9
10use serde::{Deserialize, Serialize};
11
12use super::{normalize_reword_message, FileStatus, Hunk, HunkId, LineOrigin, Oid};
13
14/// Why a file can only be assigned to a part as a whole.
15#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
16#[serde(rename_all = "snake_case")]
17pub enum WholeReason {
18    Binary,
19    ModeOnly,
20    /// Added by the commit (a partial add breaks the `new file` header).
21    Added,
22    /// Deleted by the commit.
23    Deleted,
24    Submodule,
25    Lfs,
26}
27
28/// One file changed by the commit, numbered for splitting.
29#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
30pub struct SplitFile {
31    pub path: PathBuf,
32    pub status: FileStatus,
33    /// `Some` when the file can only be assigned whole; `hunks` is then empty.
34    pub whole_only: Option<WholeReason>,
35    pub hunks: Vec<Hunk>,
36}
37
38/// What `GitBackend::split_source` returns: the commit's changes, numbered
39/// with `--no-renames` so hunk ids do not depend on `diff.renames`.
40#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
41pub struct SplitSource {
42    pub commit: Oid,
43    /// `None` for a root commit.
44    pub parent: Option<Oid>,
45    pub message: String,
46    pub files: Vec<SplitFile>,
47    /// The effective `commit.gpgSign` (repository, global and system config
48    /// as git resolves it): what the editor's "Sign commits" starts as.
49    #[serde(default)]
50    pub sign_default: bool,
51}
52
53/// One unit assigned to a part. In JSON a piece is `path` plus an optional
54/// `hunk` plus optional `lines` (indices into `Hunk.lines`).
55#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
56#[serde(try_from = "RawPiece", into = "RawPiece")]
57pub enum SplitPiece {
58    /// A whole file: the only option for whole-only files; on a text file
59    /// it means every hunk of it.
60    File { path: PathBuf },
61    /// Every changed line of a hunk.
62    Hunk { path: PathBuf, hunk: HunkId },
63    /// Some changed lines of a hunk (indices into `Hunk.lines`).
64    Lines {
65        path: PathBuf,
66        hunk: HunkId,
67        lines: Vec<u32>,
68    },
69}
70
71#[derive(Serialize, Deserialize)]
72struct RawPiece {
73    path: PathBuf,
74    #[serde(default, skip_serializing_if = "Option::is_none")]
75    hunk: Option<HunkId>,
76    #[serde(default, skip_serializing_if = "Option::is_none")]
77    lines: Option<Vec<u32>>,
78}
79
80impl TryFrom<RawPiece> for SplitPiece {
81    type Error = String;
82    fn try_from(raw: RawPiece) -> Result<Self, String> {
83        match (raw.hunk, raw.lines) {
84            (None, None) => Ok(Self::File { path: raw.path }),
85            (Some(hunk), None) => Ok(Self::Hunk {
86                path: raw.path,
87                hunk,
88            }),
89            (Some(hunk), Some(lines)) => Ok(Self::Lines {
90                path: raw.path,
91                hunk,
92                lines,
93            }),
94            (None, Some(_)) => Err("a piece with `lines` needs a `hunk`".into()),
95        }
96    }
97}
98
99impl From<SplitPiece> for RawPiece {
100    fn from(piece: SplitPiece) -> Self {
101        match piece {
102            SplitPiece::File { path } => Self {
103                path,
104                hunk: None,
105                lines: None,
106            },
107            SplitPiece::Hunk { path, hunk } => Self {
108                path,
109                hunk: Some(hunk),
110                lines: None,
111            },
112            SplitPiece::Lines { path, hunk, lines } => Self {
113                path,
114                hunk: Some(hunk),
115                lines: Some(lines),
116            },
117        }
118    }
119}
120
121/// One resulting commit, oldest first in `SplitCommit::parts`.
122#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
123pub struct SplitPart {
124    pub message: String,
125    pub pieces: Vec<SplitPiece>,
126}
127
128/// The request of `GitBackend::split_commit`.
129#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
130pub struct SplitCommit {
131    pub commit: Oid,
132    pub parts: Vec<SplitPart>,
133    /// Sign the new commits (and the replayed descendants).
134    #[serde(default)]
135    pub sign: bool,
136}
137
138/// What `GitBackend::split_commit` did.
139#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
140pub struct SplitOutcome {
141    /// The new commits, oldest first (the last carries the original tree).
142    pub created: Vec<Oid>,
143    /// HEAD before the rewrite.
144    pub previous_head: Oid,
145    /// HEAD after it.
146    pub new_head: Oid,
147    /// How many descendants were re-created on top.
148    pub replayed: usize,
149}
150
151/// Why `GitBackend::split_commit` (or [`validate_split`]) refused, before
152/// changing anything.
153#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
154#[serde(rename_all = "snake_case")]
155pub enum SplitRefusal {
156    /// Not HEAD nor an ancestor of HEAD.
157    NotOnCurrentBranch,
158    MergeCommit,
159    EmptyCommit,
160    /// A merge, rebase, cherry-pick, revert or bisect is in progress.
161    OperationInProgress,
162    TooFewParts,
163    EmptyPart,
164    EmptyMessage,
165    /// A changed line or whole file is in no part.
166    Unassigned,
167    /// A changed line or whole file is in two parts (or twice in one).
168    AssignedTwice,
169    /// An unknown path, hunk or line, or a line that is not an add/delete.
170    UnknownPiece,
171    /// A hunk or line selection on a whole-only file.
172    WholeFileOnly,
173    SigningFailed,
174}
175
176/// One assignable unit: a whole file, or one changed line of a hunk.
177#[derive(Debug, Clone, PartialEq, Eq, Hash)]
178enum Unit {
179    File(PathBuf),
180    Line(PathBuf, HunkId, u32),
181}
182
183fn is_change(hunk: &Hunk, index: u32) -> bool {
184    hunk.lines
185        .get(index as usize)
186        .is_some_and(|l| l.origin != LineOrigin::Context)
187}
188
189/// The units a piece covers, or why it is invalid for `source`.
190fn units(source: &SplitSource, piece: &SplitPiece) -> Result<Vec<Unit>, SplitRefusal> {
191    let path = match piece {
192        SplitPiece::File { path }
193        | SplitPiece::Hunk { path, .. }
194        | SplitPiece::Lines { path, .. } => path,
195    };
196    let file = source
197        .files
198        .iter()
199        .find(|f| &f.path == path)
200        .ok_or(SplitRefusal::UnknownPiece)?;
201    if file.whole_only.is_some() {
202        return match piece {
203            SplitPiece::File { .. } => Ok(vec![Unit::File(path.clone())]),
204            _ => Err(SplitRefusal::WholeFileOnly),
205        };
206    }
207    let (hunk_id, selected) = match piece {
208        // A whole text file: every changed line of every hunk.
209        SplitPiece::File { .. } => {
210            return Ok(file
211                .hunks
212                .iter()
213                .flat_map(|h| {
214                    (0..h.lines.len() as u32)
215                        .filter(|i| is_change(h, *i))
216                        .map(|i| Unit::Line(path.clone(), h.id, i))
217                })
218                .collect());
219        }
220        SplitPiece::Hunk { hunk, .. } => (*hunk, None),
221        SplitPiece::Lines { hunk, lines, .. } => (*hunk, Some(lines)),
222    };
223    let hunk = file
224        .hunks
225        .iter()
226        .find(|h| h.id == hunk_id)
227        .ok_or(SplitRefusal::UnknownPiece)?;
228    let indices: Vec<u32> = match selected {
229        None => (0..hunk.lines.len() as u32)
230            .filter(|i| is_change(hunk, *i))
231            .collect(),
232        Some(lines) => {
233            if lines.is_empty() || lines.iter().any(|i| !is_change(hunk, *i)) {
234                return Err(SplitRefusal::UnknownPiece);
235            }
236            lines.clone()
237        }
238    };
239    Ok(indices
240        .into_iter()
241        .map(|i| Unit::Line(path.clone(), hunk_id, i))
242        .collect())
243}
244
245/// Checks `parts` against `source`, the one rule set behind the backend, the
246/// CLI and the TUI. The first refusal in this order wins: part count, empty
247/// parts, empty messages, each piece in part order (unknown, whole-only,
248/// assigned twice), then anything left unassigned.
249pub fn validate_split(source: &SplitSource, parts: &[SplitPart]) -> Result<(), SplitRefusal> {
250    if parts.len() < 2 {
251        return Err(SplitRefusal::TooFewParts);
252    }
253    if parts.iter().any(|p| p.pieces.is_empty()) {
254        return Err(SplitRefusal::EmptyPart);
255    }
256    if parts
257        .iter()
258        .any(|p| normalize_reword_message(&p.message).is_none())
259    {
260        return Err(SplitRefusal::EmptyMessage);
261    }
262    let mut seen: HashSet<Unit> = HashSet::new();
263    for piece in parts.iter().flat_map(|p| &p.pieces) {
264        for unit in units(source, piece)? {
265            if !seen.insert(unit) {
266                return Err(SplitRefusal::AssignedTwice);
267            }
268        }
269    }
270    if unassigned_in(source, &seen).is_empty() {
271        Ok(())
272    } else {
273        Err(SplitRefusal::Unassigned)
274    }
275}
276
277fn unassigned_in(source: &SplitSource, seen: &HashSet<Unit>) -> Vec<SplitPiece> {
278    let mut out = Vec::new();
279    for file in &source.files {
280        if file.whole_only.is_some() {
281            if !seen.contains(&Unit::File(file.path.clone())) {
282                out.push(SplitPiece::File {
283                    path: file.path.clone(),
284                });
285            }
286            continue;
287        }
288        for hunk in &file.hunks {
289            let changed: Vec<u32> = (0..hunk.lines.len() as u32)
290                .filter(|i| is_change(hunk, *i))
291                .collect();
292            let missing: Vec<u32> = changed
293                .iter()
294                .copied()
295                .filter(|i| !seen.contains(&Unit::Line(file.path.clone(), hunk.id, *i)))
296                .collect();
297            if missing.is_empty() {
298                continue;
299            }
300            if missing.len() == changed.len() {
301                out.push(SplitPiece::Hunk {
302                    path: file.path.clone(),
303                    hunk: hunk.id,
304                });
305            } else {
306                out.push(SplitPiece::Lines {
307                    path: file.path.clone(),
308                    hunk: hunk.id,
309                    lines: missing,
310                });
311            }
312        }
313    }
314    out
315}
316
317/// What `parts` leave unassigned, in file and hunk order: a whole file, a
318/// hunk nothing touches, or the remaining lines of a partly assigned hunk.
319/// Invalid pieces are ignored here ([`validate_split`] reports them). Used
320/// by the CLI's `--rest-message` and the TUI counter.
321pub fn unassigned(source: &SplitSource, parts: &[SplitPart]) -> Vec<SplitPiece> {
322    let seen: HashSet<Unit> = parts
323        .iter()
324        .flat_map(|p| &p.pieces)
325        .filter_map(|piece| units(source, piece).ok())
326        .flatten()
327        .collect();
328    unassigned_in(source, &seen)
329}
330
331#[cfg(test)]
332mod tests {
333    use super::*;
334    use crate::domain::DiffLine;
335
336    fn oid(n: u8) -> Oid {
337        Oid([n; 20])
338    }
339
340    fn line(origin: LineOrigin) -> DiffLine {
341        DiffLine {
342            origin,
343            content: "x\n".into(),
344            staged: false,
345        }
346    }
347
348    fn hunk(id: u32) -> Hunk {
349        use LineOrigin::{Add, Context, Delete};
350        Hunk {
351            id: HunkId(id),
352            old_start: 1,
353            old_lines: 3,
354            new_start: 1,
355            new_lines: 4,
356            // indices: 0 ctx, 1 add, 2 add, 3 delete, 4 ctx
357            lines: vec![
358                line(Context),
359                line(Add),
360                line(Add),
361                line(Delete),
362                line(Context),
363            ],
364        }
365    }
366
367    fn source() -> SplitSource {
368        SplitSource {
369            commit: oid(1),
370            parent: Some(oid(2)),
371            message: "feat: both".into(),
372            sign_default: false,
373            files: vec![
374                SplitFile {
375                    path: "src/a.rs".into(),
376                    status: FileStatus::Modified,
377                    whole_only: None,
378                    hunks: vec![hunk(0), hunk(1)],
379                },
380                SplitFile {
381                    path: "logo.png".into(),
382                    status: FileStatus::Added,
383                    whole_only: Some(WholeReason::Binary),
384                    hunks: vec![],
385                },
386            ],
387        }
388    }
389
390    fn file(p: &str) -> SplitPiece {
391        SplitPiece::File { path: p.into() }
392    }
393    fn hk(p: &str, h: u32) -> SplitPiece {
394        SplitPiece::Hunk {
395            path: p.into(),
396            hunk: HunkId(h),
397        }
398    }
399    fn lines(p: &str, h: u32, l: &[u32]) -> SplitPiece {
400        SplitPiece::Lines {
401            path: p.into(),
402            hunk: HunkId(h),
403            lines: l.to_vec(),
404        }
405    }
406    fn part(msg: &str, pieces: Vec<SplitPiece>) -> SplitPart {
407        SplitPart {
408            message: msg.into(),
409            pieces,
410        }
411    }
412
413    #[test]
414    fn hunks_and_whole_files_validate() {
415        let parts = [
416            part("one", vec![hk("src/a.rs", 0), file("logo.png")]),
417            part("two", vec![hk("src/a.rs", 1)]),
418        ];
419        assert_eq!(validate_split(&source(), &parts), Ok(()));
420        assert!(unassigned(&source(), &parts).is_empty());
421    }
422
423    #[test]
424    fn a_whole_text_file_piece_means_every_hunk() {
425        let parts = [
426            part("one", vec![file("src/a.rs")]),
427            part("two", vec![file("logo.png")]),
428        ];
429        assert_eq!(validate_split(&source(), &parts), Ok(()));
430        assert!(unassigned(&source(), &parts).is_empty());
431        // Mixed with a hunk of the same file, in any part: twice.
432        let twice = [
433            part("one", vec![file("src/a.rs"), file("logo.png")]),
434            part("two", vec![hk("src/a.rs", 1)]),
435        ];
436        assert_eq!(
437            validate_split(&source(), &twice),
438            Err(SplitRefusal::AssignedTwice)
439        );
440        // Untouched text files are still reported per hunk.
441        let only_logo = [part("one", vec![file("logo.png")])];
442        assert_eq!(
443            unassigned(&source(), &only_logo),
444            vec![hk("src/a.rs", 0), hk("src/a.rs", 1)]
445        );
446    }
447
448    #[test]
449    fn a_hunk_split_by_lines_across_three_parts_validates() {
450        let parts = [
451            part("one", vec![lines("src/a.rs", 0, &[1]), file("logo.png")]),
452            part("two", vec![lines("src/a.rs", 0, &[2, 3])]),
453            part("three", vec![hk("src/a.rs", 1)]),
454        ];
455        assert_eq!(validate_split(&source(), &parts), Ok(()));
456    }
457
458    #[test]
459    fn refusals_in_order() {
460        let s = source();
461        let ok_a = part("a", vec![hk("src/a.rs", 0), file("logo.png")]);
462        let ok_b = part("b", vec![hk("src/a.rs", 1)]);
463        let with_a = |second: SplitPart| validate_split(&s, &[ok_a.clone(), second]);
464
465        assert_eq!(
466            validate_split(&s, std::slice::from_ref(&ok_a)),
467            Err(SplitRefusal::TooFewParts)
468        );
469        assert_eq!(validate_split(&s, &[]), Err(SplitRefusal::TooFewParts));
470        assert_eq!(with_a(part("b", vec![])), Err(SplitRefusal::EmptyPart));
471        assert_eq!(
472            with_a(part("  \n ", vec![hk("src/a.rs", 1)])),
473            Err(SplitRefusal::EmptyMessage)
474        );
475        assert_eq!(
476            with_a(part("b", vec![hk("src/a.rs", 1), hk("src/a.rs", 0)])),
477            Err(SplitRefusal::AssignedTwice)
478        );
479        assert_eq!(
480            with_a(part(
481                "b",
482                vec![hk("src/a.rs", 1), lines("src/a.rs", 0, &[2])]
483            )),
484            Err(SplitRefusal::AssignedTwice)
485        );
486        assert_eq!(
487            with_a(part("b", vec![lines("src/a.rs", 1, &[1, 1])])),
488            Err(SplitRefusal::AssignedTwice)
489        );
490        assert_eq!(
491            with_a(part("b", vec![hk("src/other.rs", 0)])),
492            Err(SplitRefusal::UnknownPiece)
493        );
494        assert_eq!(
495            with_a(part("b", vec![hk("src/a.rs", 9)])),
496            Err(SplitRefusal::UnknownPiece)
497        );
498        // out of range, a context line, and an empty selection
499        for bad in [&[7][..], &[0], &[]] {
500            assert_eq!(
501                with_a(part("b", vec![lines("src/a.rs", 1, bad)])),
502                Err(SplitRefusal::UnknownPiece)
503            );
504        }
505        // a whole-file piece on a text file overlaps any hunk of it
506        assert_eq!(
507            with_a(part("b", vec![file("src/a.rs")])),
508            Err(SplitRefusal::AssignedTwice)
509        );
510        // selection on a whole-only file
511        assert_eq!(
512            validate_split(&s, &[part("a", vec![hk("logo.png", 0)]), ok_b.clone()]),
513            Err(SplitRefusal::WholeFileOnly)
514        );
515        assert_eq!(
516            with_a(part("b", vec![lines("logo.png", 0, &[1])])),
517            Err(SplitRefusal::WholeFileOnly)
518        );
519        // unassigned: part of hunk 1 left out, or the whole file
520        assert_eq!(
521            with_a(part("b", vec![lines("src/a.rs", 1, &[1])])),
522            Err(SplitRefusal::Unassigned)
523        );
524        assert_eq!(
525            validate_split(
526                &s,
527                &[
528                    part("a", vec![hk("src/a.rs", 0)]),
529                    part("b", vec![hk("src/a.rs", 1)])
530                ]
531            ),
532            Err(SplitRefusal::Unassigned)
533        );
534        assert_eq!(validate_split(&s, &[ok_a, ok_b]), Ok(()));
535    }
536
537    #[test]
538    fn unassigned_lists_files_hunks_and_remaining_lines_in_order() {
539        let parts = [
540            part("a", vec![lines("src/a.rs", 0, &[1])]),
541            part("b", vec![lines("src/a.rs", 1, &[2])]),
542        ];
543        assert_eq!(
544            unassigned(&source(), &parts),
545            vec![
546                lines("src/a.rs", 0, &[2, 3]),
547                lines("src/a.rs", 1, &[1, 3]),
548                file("logo.png"),
549            ]
550        );
551        assert_eq!(
552            unassigned(&source(), &[]),
553            vec![hk("src/a.rs", 0), hk("src/a.rs", 1), file("logo.png")]
554        );
555    }
556
557    #[test]
558    fn unassigned_ignores_invalid_pieces() {
559        let parts = [part("a", vec![hk("nope", 0), hk("src/a.rs", 0)])];
560        assert_eq!(
561            unassigned(&source(), &parts),
562            vec![hk("src/a.rs", 1), file("logo.png")]
563        );
564    }
565
566    #[test]
567    fn pieces_round_trip_as_path_hunk_lines_json() {
568        let json = r#"[{"path":"a"},{"path":"b","hunk":1},{"path":"c","hunk":2,"lines":[3,4]}]"#;
569        let pieces: Vec<SplitPiece> = serde_json::from_str(json).unwrap();
570        assert_eq!(pieces, vec![file("a"), hk("b", 1), lines("c", 2, &[3, 4])]);
571        assert_eq!(serde_json::to_string(&pieces).unwrap(), json);
572        assert!(serde_json::from_str::<SplitPiece>(r#"{"path":"a","lines":[1]}"#).is_err());
573    }
574
575    #[test]
576    fn a_request_defaults_to_unsigned() {
577        let req: SplitCommit = serde_json::from_value(serde_json::json!({
578            "commit": serde_json::to_value(oid(3)).unwrap(),
579            "parts": [],
580        }))
581        .unwrap();
582        assert!(!req.sign);
583    }
584}