File: builtin_driver.rs

package info (click to toggle)
rust-gix-merge 0.2.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 4,644 kB
  • sloc: sh: 2,069; makefile: 2
file content (392 lines) | stat: -rw-r--r-- 16,463 bytes parent folder | download
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
use gix_merge::blob::builtin_driver::binary::{Pick, ResolveWith};
use gix_merge::blob::{builtin_driver, Resolution};

#[test]
fn binary() {
    assert_eq!(
        builtin_driver::binary(None),
        (Pick::Ours, Resolution::Conflict),
        "by default it picks ours and marks it as conflict"
    );
    assert_eq!(
        builtin_driver::binary(Some(ResolveWith::Ancestor)),
        (Pick::Ancestor, Resolution::CompleteWithAutoResolvedConflict),
        "Otherwise we can pick anything and it will mark it as complete"
    );
    assert_eq!(
        builtin_driver::binary(Some(ResolveWith::Ours)),
        (Pick::Ours, Resolution::CompleteWithAutoResolvedConflict)
    );
    assert_eq!(
        builtin_driver::binary(Some(ResolveWith::Theirs)),
        (Pick::Theirs, Resolution::CompleteWithAutoResolvedConflict)
    );
}

mod text {
    use bstr::ByteSlice;
    use gix_merge::blob::builtin_driver::text::{Conflict, ConflictStyle};
    use gix_merge::blob::{builtin_driver, Resolution};
    use pretty_assertions::assert_str_eq;

    const DIVERGING: &[&str] = &[
        // Somehow, on in zdiff mode, it's different, and I wasn't able to figure out the rule properly.
        // Now we prefer ancestor/before newlines and somewhat ignore our hunks. It's probably a minor issue in practice.
        // gix: "1\r\n2\n<<<<<<< complex/marker-newline-handling-lf2/ours.blob\n4\r\n||||||| complex/marker-newline-handling-lf2/base.blob\r\n2\r\n3\n=======\n5\n>>>>>>> complex/marker-newline-handling-lf2/theirs.blob\n"
        // git: "1\r\n2\n<<<<<<< complex/marker-newline-handling-lf2/ours.blob\n4  \n||||||| complex/marker-newline-handling-lf2/base.blob  \n2\r\n3\n=======\n5\n>>>>>>> complex/marker-newline-handling-lf2/theirs.blob\n"
        "complex/marker-newline-handling-lf2/zdiff3.merged",
        "complex/marker-newline-handling-lf2/zdiff3-histogram.merged",
        // This is related to Git seemingly extending a hunk to increase overlap (see diff3)
        "zdiff3-interesting/merge.merged",
        "zdiff3-interesting/merge-ours.merged",
        "zdiff3-interesting/diff3.merged",
        "zdiff3-interesting/diff3-histogram.merged",
        "zdiff3-interesting/zdiff3.merged",
        "zdiff3-interesting/zdiff3-histogram.merged",
        "zdiff3-interesting/merge-union.merged",
        // Git can extend hunks, similar to above, but the effect is not as noticeable.
        // Implementing this would be interesting, to figure out when the hunk processing should apply.
        "zdiff3-evil/merge.merged",
        "zdiff3-evil/merge-union.merged",
        // Git seems to merge to hunks if they are close together to get a less noisy diff.
        "zdiff3-middlecommon/merge.merged",
        "zdiff3-middlecommon/merge-union.merged",
        // Git has special character handling, which does magic to prevent conflicts
        "complex/auto-simplification/merge.merged",
        "complex/auto-simplification/merge-union.merged",
        // Git has special newline handling when diffing,
        // which auto-inserts a newline when it was removed, kind of.
        "complex/missing-LF-at-EOF/merge.merged",
        "complex/missing-LF-at-EOF/diff3.merged",
        "complex/missing-LF-at-EOF/diff3-histogram.merged",
        "complex/missing-LF-at-EOF/zdiff3.merged",
        "complex/missing-LF-at-EOF/zdiff3-histogram.merged",
        "complex/missing-LF-at-EOF/merge-ours.merged",
        "complex/missing-LF-at-EOF/merge-theirs.merged",
        "complex/missing-LF-at-EOF/merge-union.merged",
        // Git has different diff-slider-heuristics so diffs can be different.
        // See https://github.com/mhagger/diff-slider-tools.
        "complex/spurious-c-conflicts/merge.merged",
        "complex/spurious-c-conflicts/merge-union.merged",
        "complex/spurious-c-conflicts/diff3-histogram.merged",
        "complex/spurious-c-conflicts/zdiff3-histogram.merged",
    ];

    /// Should be a copy of `DIVERGING` once the reverse operation truly works like before
    const DIVERGING_REVERSED: &[&str] = &[
        // expected cases
        "zdiff3-middlecommon/merge.merged-reversed",
        "zdiff3-middlecommon/merge-union.merged-reversed",
        "zdiff3-interesting/merge.merged-reversed",
        "zdiff3-interesting/merge-theirs.merged-reversed",
        "zdiff3-interesting/diff3.merged-reversed",
        "zdiff3-interesting/diff3-histogram.merged-reversed",
        "zdiff3-interesting/zdiff3.merged-reversed",
        "zdiff3-interesting/zdiff3-histogram.merged-reversed",
        "zdiff3-interesting/merge-union.merged-reversed",
        "zdiff3-evil/merge.merged-reversed",
        "zdiff3-evil/merge-union.merged-reversed",
        "complex/missing-LF-at-EOF/merge.merged-reversed",
        "complex/missing-LF-at-EOF/diff3.merged-reversed",
        "complex/missing-LF-at-EOF/diff3-histogram.merged-reversed",
        "complex/missing-LF-at-EOF/zdiff3.merged-reversed",
        "complex/missing-LF-at-EOF/zdiff3-histogram.merged-reversed",
        "complex/missing-LF-at-EOF/merge-ours.merged-reversed",
        "complex/missing-LF-at-EOF/merge-theirs.merged-reversed",
        "complex/missing-LF-at-EOF/merge-union.merged-reversed",
        "complex/auto-simplification/merge.merged-reversed",
        "complex/auto-simplification/merge-union.merged-reversed",
        "complex/marker-newline-handling-lf2/zdiff3.merged-reversed",
        "complex/marker-newline-handling-lf2/zdiff3-histogram.merged-reversed",
        "complex/spurious-c-conflicts/merge.merged-reversed",
        "complex/spurious-c-conflicts/merge-union.merged-reversed",
        "complex/spurious-c-conflicts/diff3-histogram.merged-reversed",
        "complex/spurious-c-conflicts/zdiff3-histogram.merged-reversed",
    ];

    // TODO: fix all of these eventually
    fn is_case_diverging(case: &baseline::Expectation, diverging: &[&str]) -> bool {
        diverging.iter().any(|name| case.name == *name)
    }

    #[test]
    fn fuzzed() {
        for (ours, base, theirs, opts) in [
            (
                &[255, 10, 10, 255][..],
                &[0, 10, 10, 13, 10, 193, 0, 51, 8, 33][..],
                &[10, 255, 10, 10, 10, 0, 10][..],
                builtin_driver::text::Options {
                    conflict: Conflict::ResolveWithUnion,
                    diff_algorithm: imara_diff::Algorithm::Myers,
                },
            ),
            (
                &[],
                &[10, 255, 255, 255],
                &[255, 10, 255, 10, 10, 255, 40],
                builtin_driver::text::Options::default(),
            ),
        ] {
            let mut out = Vec::new();
            let mut input = imara_diff::intern::InternedInput::default();
            gix_merge::blob::builtin_driver::text(&mut out, &mut input, Default::default(), ours, base, theirs, opts);
        }
    }

    #[test]
    fn run_baseline() -> crate::Result {
        let root = gix_testtools::scripted_fixture_read_only("text-baseline.sh")?;
        for (baseline, diverging, expected_percentage) in [
            ("baseline-reversed.cases", DIVERGING_REVERSED, 11),
            ("baseline.cases", DIVERGING, 11),
        ] {
            let cases = std::fs::read_to_string(root.join(baseline))?;
            let mut out = Vec::new();
            let mut num_diverging = 0;
            let mut num_cases = 0;
            for case in baseline::Expectations::new(&root, &cases) {
                num_cases += 1;
                let mut input = imara_diff::intern::InternedInput::default();
                let actual = gix_merge::blob::builtin_driver::text(
                    &mut out,
                    &mut input,
                    case.labels(),
                    &case.ours,
                    &case.base,
                    &case.theirs,
                    case.options,
                );
                if is_case_diverging(&case, diverging) {
                    num_diverging += 1;
                } else {
                    if case.expected.contains_str("<<<<<<<") {
                        assert_eq!(actual, Resolution::Conflict, "{}: resolution mismatch", case.name,);
                    } else {
                        assert!(
                            matches!(
                                actual,
                                Resolution::Complete | Resolution::CompleteWithAutoResolvedConflict
                            ),
                            "{}: resolution mismatch",
                            case.name
                        );
                    };
                    assert_str_eq!(
                        out.as_bstr().to_str_lossy(),
                        case.expected.to_str_lossy(),
                        "{}: output mismatch\n{}",
                        case.name,
                        out.as_bstr()
                    );
                    assert_eq!(out.as_bstr(), case.expected);
                }
            }

            assert_eq!(
                num_diverging,
                diverging.len(),
                "Number of expected diverging cases must match the actual one - probably the implementation improved"
            );
            assert_eq!(
                ((num_diverging as f32 / num_cases as f32) * 100.0) as usize,
                expected_percentage,
                "Just to show the percentage of skipped tests - this should get better"
            );
        }
        Ok(())
    }

    #[test]
    fn both_sides_same_changes_are_conflict_free() {
        for conflict in [
            builtin_driver::text::Conflict::Keep {
                style: ConflictStyle::Merge,
                marker_size: 7.try_into().unwrap(),
            },
            builtin_driver::text::Conflict::Keep {
                style: ConflictStyle::Diff3,
                marker_size: 7.try_into().unwrap(),
            },
            builtin_driver::text::Conflict::Keep {
                style: ConflictStyle::ZealousDiff3,
                marker_size: 7.try_into().unwrap(),
            },
            builtin_driver::text::Conflict::ResolveWithOurs,
            builtin_driver::text::Conflict::ResolveWithTheirs,
            builtin_driver::text::Conflict::ResolveWithUnion,
        ] {
            let options = builtin_driver::text::Options {
                conflict,
                ..Default::default()
            };
            let mut input = imara_diff::intern::InternedInput::default();
            let mut out = Vec::new();
            let actual = builtin_driver::text(
                &mut out,
                &mut input,
                Default::default(),
                b"1\n3\nother",
                b"1\n2\n3",
                b"1\n3\nother",
                options,
            );
            assert_eq!(actual, Resolution::Complete, "{conflict:?}");
        }
    }

    #[test]
    fn both_differ_partially_resolution_is_conflicting() {
        for (conflict, expected) in [
            (
                builtin_driver::text::Conflict::Keep {
                    style: ConflictStyle::Merge,
                    marker_size: 7.try_into().unwrap(),
                },
                Resolution::Conflict,
            ),
            (
                builtin_driver::text::Conflict::Keep {
                    style: ConflictStyle::Diff3,
                    marker_size: 7.try_into().unwrap(),
                },
                Resolution::Conflict,
            ),
            (
                builtin_driver::text::Conflict::Keep {
                    style: ConflictStyle::ZealousDiff3,
                    marker_size: 7.try_into().unwrap(),
                },
                Resolution::Conflict,
            ),
            (
                builtin_driver::text::Conflict::ResolveWithOurs,
                Resolution::CompleteWithAutoResolvedConflict,
            ),
            (
                builtin_driver::text::Conflict::ResolveWithTheirs,
                Resolution::CompleteWithAutoResolvedConflict,
            ),
            (
                builtin_driver::text::Conflict::ResolveWithUnion,
                Resolution::CompleteWithAutoResolvedConflict,
            ),
        ] {
            let options = builtin_driver::text::Options {
                conflict,
                ..Default::default()
            };
            let mut input = imara_diff::intern::InternedInput::default();
            let mut out = Vec::new();
            let actual = builtin_driver::text(
                &mut out,
                &mut input,
                Default::default(),
                b"1\n3\nours",
                b"1\n2\n3",
                b"1\n3\ntheirs",
                options,
            );
            assert_eq!(actual, expected, "{conflict:?}");
        }
    }

    mod baseline {
        use bstr::BString;
        use gix_merge::blob::builtin_driver::text::{Conflict, ConflictStyle};
        use std::path::Path;

        #[derive(Debug)]
        pub struct Expectation {
            pub ours: BString,
            pub ours_marker: String,
            pub theirs: BString,
            pub theirs_marker: String,
            pub base: BString,
            pub base_marker: String,
            pub name: BString,
            pub expected: BString,
            pub options: gix_merge::blob::builtin_driver::text::Options,
        }

        impl Expectation {
            pub fn labels(&self) -> gix_merge::blob::builtin_driver::text::Labels<'_> {
                gix_merge::blob::builtin_driver::text::Labels {
                    ancestor: Some(self.base_marker.as_str().as_ref()),
                    current: Some(self.ours_marker.as_str().as_ref()),
                    other: Some(self.theirs_marker.as_str().as_ref()),
                }
            }
        }

        pub struct Expectations<'a> {
            root: &'a Path,
            lines: std::str::Lines<'a>,
        }

        impl<'a> Expectations<'a> {
            pub fn new(root: &'a Path, cases: &'a str) -> Self {
                Expectations {
                    root,
                    lines: cases.lines(),
                }
            }
        }

        impl Iterator for Expectations<'_> {
            type Item = Expectation;

            fn next(&mut self) -> Option<Self::Item> {
                let line = self.lines.next()?;
                let mut words = line.split(' ');
                let (Some(ours), Some(base), Some(theirs), Some(output)) =
                    (words.next(), words.next(), words.next(), words.next())
                else {
                    panic!("need at least the input and output")
                };

                let read = |rela_path: &str| read_blob(self.root, rela_path);

                let mut options = gix_merge::blob::builtin_driver::text::Options::default();
                let marker_size = 7.try_into().unwrap();
                for arg in words {
                    options.conflict = match arg {
                        "--diff3" => Conflict::Keep {
                            style: ConflictStyle::Diff3,
                            marker_size,
                        },
                        "--zdiff3" => Conflict::Keep {
                            style: ConflictStyle::ZealousDiff3,
                            marker_size,
                        },
                        "--ours" => Conflict::ResolveWithOurs,
                        "--theirs" => Conflict::ResolveWithTheirs,
                        "--union" => Conflict::ResolveWithUnion,
                        _ => panic!("Unknown argument to parse into options: '{arg}'"),
                    }
                }
                if output.contains("histogram") {
                    options.diff_algorithm = imara_diff::Algorithm::Histogram;
                }

                Some(Expectation {
                    ours: read(ours),
                    ours_marker: ours.into(),
                    theirs: read(theirs),
                    theirs_marker: theirs.into(),
                    base: read(base),
                    base_marker: base.into(),
                    expected: read(output),
                    name: output.into(),
                    options,
                })
            }
        }

        fn read_blob(root: &Path, rela_path: &str) -> BString {
            std::fs::read(root.join(rela_path))
                .unwrap_or_else(|_| panic!("Failed to read '{rela_path}' in '{}'", root.display()))
                .into()
        }
    }
}