grit-lib 0.5.21

Core library for the grit Git implementation
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
//! Shared conflict classification and in-progress operation vocabulary.
//!
//! Merge, cherry-pick, revert (and later rebase) use the same [`Conflict`] shapes and
//! [`ConflictKind`] names. Status porcelain uses a separate, Git-compatible
//! [`ConflictKind`](crate::porcelain::status::ConflictKind) for `--porcelain=v2` XY codes.
//!
//! ```rust
//! use grit_lib::operation::{conflict_kind_from_stages, ConflictKind};
//!
//! assert_eq!(
//!     conflict_kind_from_stages(false, true, true),
//!     ConflictKind::AddAdd
//! );
//! ```

use std::collections::HashMap;

use crate::diff::merge_trees::TreeMergeOutput;
use crate::index::Index;

pub use crate::state::{
    operation_alternatives, operation_next_steps, operation_next_steps_empty, status_operation,
    InProgressOperation, NextStep, Operation,
};

/// How a tree-merge conflict should be presented (content, add/add, modify/delete, …).
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ConflictKind {
    /// Both sides edited the same tracked file (textual or binary).
    Content,
    /// Both sides added the same path with different content.
    AddAdd,
    /// One side deleted the path and the other modified it.
    ModifyDelete {
        /// When true, the deletion is on the current branch (HEAD); the incoming side modified the file.
        deleted_in_current: bool,
    },
    /// Both sides renamed the same base file, to different paths.
    ///
    /// Reported once for each of the three paths involved; [`Conflict::path`] says which one.
    RenameRename {
        /// Path of the file in the merge base (left at stage 1).
        base_path: String,
        /// Name the current branch gave it (stage 2).
        ours_path: String,
        /// Name the incoming side gave it (stage 3).
        theirs_path: String,
    },
}

impl ConflictKind {
    /// Stable snake_case name for JSON and scripting.
    #[must_use]
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::Content => "content",
            Self::AddAdd => "add_add",
            Self::ModifyDelete { .. } => "modify_delete",
            Self::RenameRename { .. } => "rename_rename",
        }
    }
}

/// One conflicted path from a tree merge or unmerged index stages 1–3.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Conflict {
    /// Repository-relative path.
    pub path: String,
    /// Conflict shape derived from unmerged index stages.
    pub kind: ConflictKind,
}

/// Derive [`ConflictKind`] from which unmerged index stages exist for a path.
///
/// Matches the classification used when recording merge conflicts from
/// [`TreeMergeOutput`].
#[must_use]
pub fn conflict_kind_from_stages(stage1: bool, stage2: bool, stage3: bool) -> ConflictKind {
    match (stage1, stage2, stage3) {
        (false, true, true) => ConflictKind::AddAdd,
        (true, true, true) => ConflictKind::Content,
        (true, false, true) => ConflictKind::ModifyDelete {
            deleted_in_current: true,
        },
        (true, true, false) => ConflictKind::ModifyDelete {
            deleted_in_current: false,
        },
        _ => ConflictKind::Content,
    }
}

/// Classify unmerged paths in `index` (sorted, deduplicated).
#[must_use]
pub fn conflicts_from_index(index: &Index) -> Vec<Conflict> {
    let paths = conflict_path_bytes_from_index(index);
    paths
        .into_iter()
        .map(|path_bytes| {
            let stage1 = index.get(&path_bytes, 1).is_some();
            let stage2 = index.get(&path_bytes, 2).is_some();
            let stage3 = index.get(&path_bytes, 3).is_some();
            Conflict {
                path: String::from_utf8_lossy(&path_bytes).into_owned(),
                kind: conflict_kind_from_stages(stage1, stage2, stage3),
            }
        })
        .collect()
}

/// Collect conflicted paths and kinds from a three-way tree merge result.
///
/// Paths of a [`TreeMergeOutput::rename_conflicts`] entry are reported as
/// [`ConflictKind::RenameRename`]; every other path is classified by its unmerged stages.
#[must_use]
pub fn conflicts_from_tree_merge(merged: &TreeMergeOutput) -> Vec<Conflict> {
    let mut rename_kinds: HashMap<&[u8], ConflictKind> = HashMap::new();
    for rr in &merged.rename_conflicts {
        let kind = ConflictKind::RenameRename {
            base_path: String::from_utf8_lossy(&rr.base_path).into_owned(),
            ours_path: String::from_utf8_lossy(&rr.ours_path).into_owned(),
            theirs_path: String::from_utf8_lossy(&rr.theirs_path).into_owned(),
        };
        for path in [&rr.base_path, &rr.ours_path, &rr.theirs_path] {
            rename_kinds.insert(path.as_slice(), kind.clone());
        }
    }
    let paths = tree_merge_conflict_path_strings(merged);
    paths
        .into_iter()
        .map(|path| {
            let path_bytes = path.as_bytes();
            if let Some(kind) = rename_kinds.get(path_bytes) {
                return Conflict {
                    kind: kind.clone(),
                    path,
                };
            }
            let stage1 = merged.index.get(path_bytes, 1).is_some();
            let stage2 = merged.index.get(path_bytes, 2).is_some();
            let stage3 = merged.index.get(path_bytes, 3).is_some();
            Conflict {
                path,
                kind: conflict_kind_from_stages(stage1, stage2, stage3),
            }
        })
        .collect()
}

/// Whether `merged` has textual conflict blobs or unmerged index stages.
#[must_use]
pub fn tree_merge_has_conflicts(merged: &TreeMergeOutput) -> bool {
    !merged.conflict_content.is_empty() || merged.index.entries().iter().any(|e| e.stage() != 0)
}

/// Render [`NextStep`] values as `grit` command lines (skips steps with no CLI yet).
#[must_use]
pub fn next_step_grit_commands(steps: &[NextStep]) -> Vec<String> {
    steps.iter().filter_map(NextStep::grit_command).collect()
}

/// Conflicted paths of a tree merge (marker blobs and unmerged stages), sorted and deduplicated.
pub(crate) fn tree_merge_conflict_path_strings(merged: &TreeMergeOutput) -> Vec<String> {
    let mut paths: Vec<String> = merged
        .conflict_content
        .keys()
        .map(|k| String::from_utf8_lossy(k).into_owned())
        .collect();
    paths.extend(
        merged
            .index
            .entries()
            .iter()
            .filter(|e| e.stage() != 0)
            .map(|e| String::from_utf8_lossy(&e.path).into_owned()),
    );
    paths.sort();
    paths.dedup();
    paths
}

fn conflict_path_bytes_from_index(index: &Index) -> Vec<Vec<u8>> {
    use std::collections::BTreeSet;
    let mut paths = BTreeSet::new();
    for entry in index.entries() {
        let stage = entry.stage();
        if (1..=3).contains(&stage) {
            paths.insert(entry.path.clone());
        }
    }
    paths.into_iter().collect()
}

#[cfg(test)]
mod tests {
    #![allow(clippy::unwrap_used)]

    use super::*;
    use crate::index::{Index, IndexEntry};
    use crate::merge_trees::TreeMergeOutput;
    use std::collections::{BTreeMap, HashSet};

    fn index_entry(path: &str, stage: u8) -> IndexEntry {
        let mut entry = IndexEntry {
            ctime_sec: 0,
            ctime_nsec: 0,
            mtime_sec: 0,
            mtime_nsec: 0,
            dev: 0,
            ino: 0,
            mode: crate::index::MODE_REGULAR,
            uid: 0,
            gid: 0,
            size: 0,
            oid: crate::diff::zero_oid(),
            flags: 0,
            flags_extended: None,
            path: path.as_bytes().to_vec(),
            base_index_pos: 0,
        };
        entry.set_stage(stage);
        entry
    }

    #[test]
    fn conflict_kind_from_stages_content() {
        assert_eq!(
            conflict_kind_from_stages(true, true, true),
            ConflictKind::Content
        );
    }

    #[test]
    fn conflict_kind_from_stages_add_add() {
        assert_eq!(
            conflict_kind_from_stages(false, true, true),
            ConflictKind::AddAdd
        );
    }

    #[test]
    fn conflict_kind_from_stages_modify_delete_deleted_in_current() {
        assert_eq!(
            conflict_kind_from_stages(true, false, true),
            ConflictKind::ModifyDelete {
                deleted_in_current: true
            }
        );
    }

    #[test]
    fn conflict_kind_from_stages_modify_delete_deleted_incoming() {
        assert_eq!(
            conflict_kind_from_stages(true, true, false),
            ConflictKind::ModifyDelete {
                deleted_in_current: false
            }
        );
    }

    #[test]
    fn conflict_kind_as_str_is_stable_snake_case() {
        assert_eq!(ConflictKind::Content.as_str(), "content");
        assert_eq!(ConflictKind::AddAdd.as_str(), "add_add");
        assert_eq!(
            ConflictKind::ModifyDelete {
                deleted_in_current: true
            }
            .as_str(),
            "modify_delete"
        );
        assert_eq!(
            ConflictKind::RenameRename {
                base_path: "a".into(),
                ours_path: "b".into(),
                theirs_path: "c".into(),
            }
            .as_str(),
            "rename_rename"
        );
    }

    #[test]
    fn conflicts_from_tree_merge_reports_rename_rename_on_all_three_paths() {
        let mut index = Index::new();
        index.add_or_replace(index_entry("a", 1));
        index.add_or_replace(index_entry("b", 2));
        index.add_or_replace(index_entry("c", 3));
        index.add_or_replace(index_entry("d", 1));
        index.add_or_replace(index_entry("d", 2));
        let merged = TreeMergeOutput {
            index,
            conflict_content: BTreeMap::new(),
            result_tree: crate::diff::zero_oid(),
            touched_paths: HashSet::new(),
            rename_conflicts: vec![crate::merge_trees::RenameRenameConflict {
                base_path: b"a".to_vec(),
                ours_path: b"b".to_vec(),
                theirs_path: b"c".to_vec(),
            }],
        };
        let kind = ConflictKind::RenameRename {
            base_path: "a".into(),
            ours_path: "b".into(),
            theirs_path: "c".into(),
        };
        let conflicts = conflicts_from_tree_merge(&merged);
        let got: Vec<(&str, &ConflictKind)> = conflicts
            .iter()
            .map(|c| (c.path.as_str(), &c.kind))
            .collect();
        assert_eq!(
            got,
            vec![
                ("a", &kind),
                ("b", &kind),
                ("c", &kind),
                (
                    "d",
                    &ConflictKind::ModifyDelete {
                        deleted_in_current: false
                    }
                ),
            ]
        );
    }

    #[test]
    fn conflicts_from_tree_merge_unions_markers_and_unmerged_index() {
        let mut index = Index::new();
        index.add_or_replace(index_entry("b.txt", 1));
        index.add_or_replace(index_entry("b.txt", 2));
        let mut conflict_content = BTreeMap::new();
        conflict_content.insert(b"a.txt".to_vec(), crate::diff::zero_oid());
        let merged = TreeMergeOutput {
            index,
            conflict_content,
            result_tree: crate::diff::zero_oid(),
            touched_paths: HashSet::new(),
            rename_conflicts: Vec::new(),
        };
        let conflicts = conflicts_from_tree_merge(&merged);
        assert_eq!(conflicts.len(), 2);
        assert_eq!(conflicts[0].path, "a.txt");
        assert_eq!(conflicts[0].kind, ConflictKind::Content);
        assert_eq!(conflicts[1].path, "b.txt");
        assert_eq!(
            conflicts[1].kind,
            ConflictKind::ModifyDelete {
                deleted_in_current: false
            }
        );
    }

    #[test]
    fn next_step_grit_command_for_each_operation() {
        use crate::state::InProgressOperation;

        let cases: &[(NextStep, &str)] = &[
            (
                NextStep::Abort(InProgressOperation::Merge),
                "grit merge --abort",
            ),
            (
                NextStep::Continue(InProgressOperation::Merge),
                "grit merge --continue",
            ),
            (
                NextStep::Abort(InProgressOperation::CherryPick),
                "grit pick --abort",
            ),
            (
                NextStep::Continue(InProgressOperation::CherryPick),
                "grit pick --continue",
            ),
            (
                NextStep::Skip(InProgressOperation::CherryPick),
                "grit pick --skip",
            ),
            (
                NextStep::Abort(InProgressOperation::Revert),
                "grit revert --abort",
            ),
            (
                NextStep::Continue(InProgressOperation::Revert),
                "grit revert --continue",
            ),
            (
                NextStep::Skip(InProgressOperation::Revert),
                "grit revert --skip",
            ),
        ];
        for (step, expected) in cases {
            assert_eq!(step.grit_command().as_deref(), Some(*expected), "{step:?}");
            assert_eq!(step.command().as_deref(), Some(*expected), "{step:?}");
            assert_eq!(step.git_command(), None, "{step:?}");
        }
    }

    #[test]
    fn continue_with_git_renders_only_a_git_command() {
        use crate::state::InProgressOperation;

        let cases: &[(InProgressOperation, Option<&str>)] = &[
            (InProgressOperation::Merge, Some("git merge --continue")),
            (InProgressOperation::Rebase, Some("git rebase --continue")),
            (
                InProgressOperation::RebaseInteractive,
                Some("git rebase --continue"),
            ),
            (
                InProgressOperation::CherryPick,
                Some("git cherry-pick --continue"),
            ),
            (InProgressOperation::Revert, Some("git revert --continue")),
            (InProgressOperation::Am, Some("git am --continue")),
            (InProgressOperation::Bisect, None),
        ];
        for (kind, expected) in cases {
            let step = NextStep::ContinueWithGit(*kind);
            assert_eq!(step.grit_command(), None, "{step:?}");
            assert_eq!(step.git_command().as_deref(), *expected, "{step:?}");
            assert_eq!(step.command().as_deref(), *expected, "{step:?}");
        }
        assert_eq!(
            NextStep::Abort(InProgressOperation::RebaseInteractive)
                .command()
                .as_deref(),
            Some("grit rebase --abort")
        );
    }
}