Skip to main content

vcs_git/
conflict.rs

1//! Typed model of git conflict markers — parse a conflicted file's *content*
2//! into structured regions and write a chosen resolution back. Pure functions
3//! (no subprocess), so everything here is hermetic.
4//!
5//! Handles git's three `merge.conflictStyle`s with one grammar: `merge`
6//! (2-way: ours/theirs), `diff3` (3-way: ours/base/theirs), and `zdiff3`
7//! (same markers as diff3 — the common affixes are already outside the
8//! region). Marker length is variable (`merge.conflictMarkerSize`, default 7)
9//! and is detected per region. Lines are kept verbatim (including `\r\n` and
10//! a missing trailing newline), so [`render`] is a byte-exact roundtrip.
11//!
12//! jj note: files materialized with jj's `ui.conflict-marker-style = "git"`
13//! use this exact grammar (with jj's own labels) and parse here; jj's native
14//! `diff`/`snapshot` styles live in `vcs_jj::conflict`.
15
16use processkit::{Error, Result};
17
18use crate::BINARY;
19
20/// Which side of a conflict a resolution keeps.
21///
22/// Intentionally **exhaustive** (no `#[non_exhaustive]`): a git conflict has
23/// exactly these three sides — the domain is closed, so `#[non_exhaustive]` would
24/// buy no future variant while forcing a wildcard arm on any caller that matches
25/// this (callers usually *construct* it to pass to [`resolve`]) and wrongly
26/// signalling a fourth side could appear.
27#[derive(Debug, Clone, Copy, PartialEq, Eq)]
28pub enum ResolutionSide {
29    /// The `<<<<<<<` side (typically `HEAD`).
30    Ours,
31    /// The `|||||||` base (diff3/zdiff3 only).
32    Base,
33    /// The `>>>>>>>` side (the merged-in branch).
34    Theirs,
35}
36
37/// One conflicted region: the lines of each side plus the verbatim marker
38/// lines (kept so rendering is byte-exact).
39///
40/// All line vectors store lines **with** their original endings; the last
41/// line of a file may have none.
42#[derive(Debug, Clone, PartialEq, Eq)]
43#[non_exhaustive]
44pub struct ConflictRegion {
45    /// Label after the `<<<<<<<` marker (e.g. `HEAD`); empty when absent.
46    pub ours_label: String,
47    /// Label after the `|||||||` marker; `None` for 2-way conflicts.
48    pub base_label: Option<String>,
49    /// Label after the `>>>>>>>` marker (e.g. the branch name).
50    pub theirs_label: String,
51    /// The `<<<<<<<`-side lines.
52    pub ours: Vec<String>,
53    /// The base lines (`diff3`/`zdiff3`); `None` for 2-way conflicts.
54    pub base: Option<Vec<String>>,
55    /// The `>>>>>>>`-side lines.
56    pub theirs: Vec<String>,
57    /// The marker run length (7 unless `merge.conflictMarkerSize` raised it).
58    pub marker_len: usize,
59    // Verbatim marker lines, for byte-exact rendering.
60    marker_ours: String,
61    marker_base: Option<String>,
62    marker_sep: String,
63    marker_end: String,
64}
65
66/// A conflicted file as a sequence of plain-text runs and conflict regions —
67/// the shape that keeps [`render`] a byte-exact roundtrip.
68///
69/// Intentionally **exhaustive**: a file is text-or-conflict, and consumers match
70/// every segment in the resolve/render loop this crate exists to serve, so the
71/// closed enum stays ergonomic. Field-level evolution rides [`ConflictRegion`],
72/// which *is* `#[non_exhaustive]`.
73#[derive(Debug, Clone, PartialEq, Eq)]
74pub enum ConflictSegment {
75    /// Lines outside any conflict (verbatim, endings included).
76    Text(Vec<String>),
77    /// One conflicted region (boxed — much larger than a text run).
78    Conflict(Box<ConflictRegion>),
79}
80
81/// Does `content` contain a line that looks like a conflict-start marker?
82/// Cheap pre-check before a full [`parse_conflicts`].
83pub fn has_conflict_markers(content: &str) -> bool {
84    content
85        .split_inclusive('\n')
86        .any(|line| marker_run(line, '<').is_some_and(|n| n >= 7))
87}
88
89/// The length of the leading `ch` run when `line` is a marker line for it:
90/// the run must be followed by a space + label, or end the line.
91fn marker_run(line: &str, ch: char) -> Option<usize> {
92    let trimmed = line.trim_end_matches(['\r', '\n']);
93    let n = trimmed.chars().take_while(|&c| c == ch).count();
94    if n == 0 {
95        return None;
96    }
97    let rest = &trimmed[n..];
98    (rest.is_empty() || rest.starts_with(' ')).then_some(n)
99}
100
101/// The label after an `n`-char marker run (empty when none).
102fn marker_label(line: &str, n: usize) -> String {
103    line.trim_end_matches(['\r', '\n'])[n..]
104        .trim_start()
105        .to_string()
106}
107
108fn parse_error(message: String) -> Error {
109    Error::parse(BINARY, message)
110}
111
112/// Parse a conflicted file's content into text/conflict segments.
113///
114/// Errors with [`Error::Parse`] only on a genuinely malformed *region*: a
115/// `<<<<<<<`-opened region missing its `=======` separator or `>>>>>>>`
116/// terminator. A `=======`/`>>>>>>>` run **outside** any region is treated as
117/// ordinary content (a Markdown/RST underline, a divider, a quoted email), so a
118/// file with no real conflict — or a real conflict alongside marker-like content
119/// — parses cleanly.
120pub fn parse_conflicts(content: &str) -> Result<Vec<ConflictSegment>> {
121    let mut segments = Vec::new();
122    let mut text: Vec<String> = Vec::new();
123    let mut lines = content.split_inclusive('\n').peekable();
124
125    while let Some(line) = lines.next() {
126        // A region starts at a `<<<<<<<`-run of length ≥ 7. A `=======` / `>>>>>>>`
127        // run *outside* a region is ordinary content — a Markdown/RST setext
128        // underline (`=========`), a `=======` divider banner, a deep `>>>>>>>`
129        // email quote — NOT a malformed conflict, so it is kept verbatim as text
130        // (a real conflict is delimited by a `<<<<<<<` opener; the region loops
131        // below consume the `=`/`>` markers that belong to it). A genuinely broken
132        // region (an opener with no separator/terminator) is still caught inside
133        // those loops.
134        let Some(n) = marker_run(line, '<').filter(|&n| n >= 7) else {
135            text.push(line.to_string());
136            continue;
137        };
138        if !text.is_empty() {
139            segments.push(ConflictSegment::Text(std::mem::take(&mut text)));
140        }
141
142        let marker_ours = line.to_string();
143        let ours_label = marker_label(line, n);
144        let mut ours = Vec::new();
145        let mut base: Option<Vec<String>> = None;
146        let mut marker_base = None;
147        let mut base_label = None;
148
149        // Ours, until the base marker (diff3) or the separator.
150        let marker_sep = loop {
151            let Some(line) = lines.next() else {
152                return Err(parse_error(format!(
153                    "unterminated conflict (no ======= after {:?})",
154                    marker_ours.trim_end()
155                )));
156            };
157            // Only the FIRST `|`-run is the diff3 base marker; a later matching
158            // line is base *content* (a region has exactly one base marker — a
159            // repeated one used to overwrite it and lose a line on render).
160            if base.is_none() && marker_run(line, '|') == Some(n) {
161                base_label = Some(marker_label(line, n));
162                marker_base = Some(line.to_string());
163                base = Some(Vec::new());
164                continue;
165            }
166            if marker_run(line, '=') == Some(n) {
167                break line.to_string();
168            }
169            match &mut base {
170                Some(base_lines) => base_lines.push(line.to_string()),
171                None => ours.push(line.to_string()),
172            }
173        };
174
175        // Theirs, until the end marker.
176        let mut theirs = Vec::new();
177        let marker_end = loop {
178            let Some(line) = lines.next() else {
179                return Err(parse_error(format!(
180                    "unterminated conflict (no >>>>>>> after {:?})",
181                    marker_ours.trim_end()
182                )));
183            };
184            if marker_run(line, '>') == Some(n) {
185                break line.to_string();
186            }
187            theirs.push(line.to_string());
188        };
189        let theirs_label = marker_label(&marker_end, n);
190
191        segments.push(ConflictSegment::Conflict(Box::new(ConflictRegion {
192            ours_label,
193            base_label,
194            theirs_label,
195            ours,
196            base,
197            theirs,
198            marker_len: n,
199            marker_ours,
200            marker_base,
201            marker_sep,
202            marker_end,
203        })));
204    }
205    if !text.is_empty() {
206        segments.push(ConflictSegment::Text(text));
207    }
208    Ok(segments)
209}
210
211/// Re-render segments verbatim — the byte-exact inverse of
212/// [`parse_conflicts`].
213pub fn render(segments: &[ConflictSegment]) -> String {
214    let mut out = String::new();
215    for segment in segments {
216        match segment {
217            ConflictSegment::Text(lines) => lines.iter().for_each(|l| out.push_str(l)),
218            ConflictSegment::Conflict(region) => {
219                out.push_str(&region.marker_ours);
220                region.ours.iter().for_each(|l| out.push_str(l));
221                if let Some(marker) = &region.marker_base {
222                    out.push_str(marker);
223                    if let Some(base) = &region.base {
224                        base.iter().for_each(|l| out.push_str(l));
225                    }
226                }
227                out.push_str(&region.marker_sep);
228                region.theirs.iter().for_each(|l| out.push_str(l));
229                out.push_str(&region.marker_end);
230            }
231        }
232    }
233    out
234}
235
236/// Produce the file content with every conflict resolved to `side`.
237///
238/// Errors with a clear message when `side` is [`ResolutionSide::Base`] and a
239/// region has no base (2-way `merge` style records none).
240pub fn resolve(segments: &[ConflictSegment], side: ResolutionSide) -> Result<String> {
241    let mut out = String::new();
242    for segment in segments {
243        match segment {
244            ConflictSegment::Text(lines) => lines.iter().for_each(|l| out.push_str(l)),
245            ConflictSegment::Conflict(region) => {
246                let chosen = match side {
247                    ResolutionSide::Ours => &region.ours,
248                    ResolutionSide::Theirs => &region.theirs,
249                    ResolutionSide::Base => region.base.as_ref().ok_or_else(|| {
250                        Error::spawn(
251                            BINARY,
252                            std::io::Error::new(
253                                std::io::ErrorKind::InvalidInput,
254                                "cannot resolve to Base: this conflict records no base \
255                                 (2-way `merge` style; use diff3/zdiff3)",
256                            ),
257                        )
258                    })?,
259                };
260                chosen.iter().for_each(|l| out.push_str(l));
261            }
262        }
263    }
264    Ok(out)
265}
266
267#[cfg(test)]
268mod tests {
269    use super::*;
270
271    const MERGE_2WAY: &str =
272        "line 1\n<<<<<<< HEAD\nmain line 2\n=======\nfeature line 2\n>>>>>>> feature\nline 3\n";
273    const DIFF3: &str = "line 1\n<<<<<<< HEAD\nmain line 2\n||||||| 0b025ce\nline 2\n=======\nfeature line 2\n>>>>>>> feature\nline 3\n";
274
275    #[test]
276    fn parses_two_way_merge_style() {
277        let segments = parse_conflicts(MERGE_2WAY).expect("parse");
278        assert_eq!(segments.len(), 3);
279        let ConflictSegment::Conflict(region) = &segments[1] else {
280            panic!("expected a conflict, got {segments:?}");
281        };
282        assert_eq!(region.ours_label, "HEAD");
283        assert_eq!(region.theirs_label, "feature");
284        assert_eq!(region.ours, ["main line 2\n"]);
285        assert_eq!(region.theirs, ["feature line 2\n"]);
286        assert!(region.base.is_none());
287        assert_eq!(region.marker_len, 7);
288    }
289
290    #[test]
291    fn parses_diff3_with_base() {
292        let segments = parse_conflicts(DIFF3).expect("parse");
293        let ConflictSegment::Conflict(region) = &segments[1] else {
294            panic!("expected a conflict");
295        };
296        assert_eq!(region.base_label.as_deref(), Some("0b025ce"));
297        assert_eq!(region.base.as_deref(), Some(&["line 2\n".to_string()][..]));
298    }
299
300    // Proptest-found regression (seed committed in proptest-regressions/): a
301    // SECOND `|`-run line inside a diff3 region is base *content*, not a
302    // replacement base marker — the overwrite used to drop a line on render,
303    // breaking the byte-exact roundtrip.
304    #[test]
305    fn repeated_base_marker_line_is_base_content() {
306        let s = "<<<<<<<< HEAD\n|||||||| base\n|||||||| base\n========\n>>>>>>>> branché\n";
307        let segments = parse_conflicts(s).expect("parse");
308        let ConflictSegment::Conflict(region) = &segments[0] else {
309            panic!("expected a conflict, got {segments:?}");
310        };
311        assert_eq!(
312            region.base.as_deref(),
313            Some(&["|||||||| base\n".to_string()][..]),
314            "the second |-run line is content of the base section"
315        );
316        assert_eq!(render(&segments), s, "roundtrip must be byte-exact");
317    }
318
319    // Roundtrip must be byte-exact — including CRLF, custom marker sizes,
320    // and a conflict at EOF with no trailing newline.
321    #[test]
322    fn render_roundtrips_exactly() {
323        let crlf = "a\r\n<<<<<<< HEAD\r\nours\r\n=======\r\ntheirs\r\n>>>>>>> b\r\nz\r\n";
324        let wide = "<<<<<<<<<<<<<<< HEAD\nours\n===============\ntheirs\n>>>>>>>>>>>>>>> b\n";
325        let eof = "x\n<<<<<<< HEAD\nours\n=======\ntheirs\n>>>>>>> b";
326        for sample in [MERGE_2WAY, DIFF3, crlf, wide, eof] {
327            let segments = parse_conflicts(sample).expect("parse");
328            assert_eq!(render(&segments), sample, "roundtrip");
329        }
330        // The wide sample detected the larger marker run.
331        let segments = parse_conflicts(wide).unwrap();
332        let ConflictSegment::Conflict(region) = &segments[0] else {
333            panic!()
334        };
335        assert_eq!(region.marker_len, 15);
336    }
337
338    #[test]
339    fn resolve_takes_one_side_everywhere() {
340        let two = format!("{MERGE_2WAY}between\n{MERGE_2WAY}");
341        let segments = parse_conflicts(&two).expect("parse");
342        assert_eq!(
343            resolve(&segments, ResolutionSide::Ours).unwrap(),
344            "line 1\nmain line 2\nline 3\nbetween\nline 1\nmain line 2\nline 3\n"
345        );
346        assert_eq!(
347            resolve(&segments, ResolutionSide::Theirs).unwrap(),
348            "line 1\nfeature line 2\nline 3\nbetween\nline 1\nfeature line 2\nline 3\n"
349        );
350        // No base recorded in merge style → Base resolution is refused.
351        assert!(resolve(&segments, ResolutionSide::Base).is_err());
352
353        let diff3 = parse_conflicts(DIFF3).expect("parse");
354        assert_eq!(
355            resolve(&diff3, ResolutionSide::Base).unwrap(),
356            "line 1\nline 2\nline 3\n"
357        );
358    }
359
360    #[test]
361    fn empty_sides_and_clean_files_parse() {
362        // One side deleted everything.
363        let deletion = "<<<<<<< HEAD\n=======\nkept\n>>>>>>> b\n";
364        let segments = parse_conflicts(deletion).expect("parse");
365        assert_eq!(resolve(&segments, ResolutionSide::Ours).unwrap(), "");
366        // A file without conflicts is one text segment.
367        let clean = parse_conflicts("just\ntext\n").expect("parse");
368        assert_eq!(clean.len(), 1);
369        assert!(!has_conflict_markers("just\ntext\n"));
370        assert!(has_conflict_markers(MERGE_2WAY));
371    }
372
373    #[test]
374    fn malformed_files_are_parse_errors() {
375        // Only a genuinely broken *region* (an opener with no separator/terminator)
376        // is an error.
377        for bad in [
378            "<<<<<<< HEAD\nours\n",                  // no separator
379            "<<<<<<< HEAD\nours\n=======\ntheirs\n", // no terminator
380        ] {
381            assert!(
382                matches!(parse_conflicts(bad), Err(Error::Parse { .. })),
383                "{bad:?} must fail"
384            );
385        }
386    }
387
388    // A `=======`/`>>>>>>>` run outside any region is ordinary content (Markdown
389    // underline, divider, quoted email), not a malformed conflict — parsed as text,
390    // never an error, and round-trips byte-exact. (H6)
391    #[test]
392    fn marker_like_content_outside_a_region_is_text() {
393        for content in [
394            "Heading\n=======\nbody\n",          // RST/Markdown setext underline
395            "a\n=======================\nb\n",   // divider banner
396            ">>>>>>> deep email quote\nreply\n", // quoted email
397            "code: a <<<<<<< b\n",               // marker run not at line start
398        ] {
399            let segments = parse_conflicts(content).expect("parses as text, no error");
400            assert!(
401                segments
402                    .iter()
403                    .all(|s| matches!(s, ConflictSegment::Text(_))),
404                "{content:?} must be all text, got {segments:?}"
405            );
406            assert_eq!(render(&segments), content, "round-trips byte-exact");
407        }
408    }
409}
410
411// Property-based fuzzing. The marker grammar slices on marker-run lengths and
412// must never panic on a hostile file (a real conflicted file from a git we
413// don't control), and `render(parse(x)?) == x` must hold byte-for-byte — the
414// regression net for the marker-detection / byte-offset logic.
415#[cfg(test)]
416mod proptests {
417    use super::*;
418    use proptest::prelude::*;
419
420    /// A line drawn from the conflict-marker vocabulary plus multibyte text,
421    /// with variable marker-run lengths (7..16) and CRLF, so a joined document
422    /// reaches the marker-slicing branches with adversarial content.
423    fn conflict_line() -> impl Strategy<Value = String> {
424        prop_oneof![
425            (7usize..16).prop_map(|n| format!("{} HEAD\n", "<".repeat(n))),
426            (7usize..16).prop_map(|n| format!("{}\n", "=".repeat(n))),
427            (7usize..16).prop_map(|n| format!("{} branché\n", ">".repeat(n))),
428            (7usize..16).prop_map(|n| format!("{} base\n", "|".repeat(n))),
429            "[a-zé<>=|]{0,14}\r?\n", // text incl. marker-ish chars + multibyte + CRLF
430            Just("\n".to_string()),
431        ]
432    }
433
434    fn conflict_doc() -> impl Strategy<Value = String> {
435        prop::collection::vec(conflict_line(), 0..30).prop_map(|lines| lines.concat())
436    }
437
438    proptest! {
439        #[test]
440        fn parse_never_panics_on_arbitrary_text(s in any::<String>()) {
441            let _ = has_conflict_markers(&s);
442            // Whatever arbitrary text happens to parse must also round-trip
443            // byte-exact — the load-bearing invariant, asserted on this generator
444            // too (not just the structured one below).
445            if let Ok(segments) = parse_conflicts(&s) {
446                prop_assert_eq!(render(&segments), s);
447            }
448        }
449
450        #[test]
451        fn parse_never_panics_on_structured_text(s in conflict_doc()) {
452            let _ = parse_conflicts(&s);
453        }
454
455        // The load-bearing invariant: whenever the file parses, re-rendering is
456        // byte-exact.
457        #[test]
458        fn render_roundtrips_whatever_parses(s in conflict_doc()) {
459            if let Ok(segments) = parse_conflicts(&s) {
460                prop_assert_eq!(render(&segments), s);
461            }
462        }
463
464        // A marker-free file is one Text segment that renders back unchanged.
465        #[test]
466        fn marker_free_files_are_a_single_text_segment(s in "[a-zé \t\r\n]{0,80}") {
467            prop_assume!(!has_conflict_markers(&s));
468            let segments = parse_conflicts(&s).expect("no markers → Ok");
469            prop_assert_eq!(render(&segments), s);
470        }
471    }
472}