Skip to main content

gpui_component/diff/
conflict.rs

1//! Files outside a patch: a whole source shown for reference, and a working
2//! file containing Git conflict markers.
3use std::ops::Range;
4
5use gpui::SharedString;
6
7use super::{
8    DiffFile, DiffFileStatus, DiffParseError,
9    document::{FileSide, LinePair},
10};
11
12/// How the user resolved a conflict.
13#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
14#[non_exhaustive]
15pub enum DiffConflictResolution {
16    /// Keep the current change, between `<<<<<<<` and `=======`.
17    Current,
18    /// Keep the incoming change, between `=======` and `>>>>>>>`.
19    Incoming,
20    /// Keep the current change followed by the incoming one.
21    Both,
22}
23
24/// Which part of a conflict a row introduces.
25#[derive(Clone, Copy, Debug, PartialEq, Eq)]
26pub(crate) enum ConflictPart {
27    Current,
28    Base,
29    Incoming,
30}
31
32/// A parsed merge conflict in a working file.
33///
34/// Source coordinates are one-based, half-open ranges, allowing empty parts.
35/// Returned by [`DiffFile::conflicts`] in source order; its slice index is the
36/// index accepted by [`super::DiffState::resolve_conflict`]. Fields are private
37/// and only the parser constructs these snapshots.
38#[derive(Clone, Debug)]
39pub struct DiffConflict {
40    lines: Range<usize>,
41    current_lines: Range<usize>,
42    base_lines: Option<Range<usize>>,
43    incoming_lines: Range<usize>,
44    current: Range<usize>,
45    base: Option<Range<usize>>,
46    incoming: Range<usize>,
47    current_label: SharedString,
48    base_label: SharedString,
49    incoming_label: SharedString,
50}
51
52impl DiffConflict {
53    /// One-based working-file lines, including markers, with an exclusive end.
54    pub fn lines(&self) -> Range<usize> {
55        self.lines.clone()
56    }
57    /// Current-side source lines, with an exclusive end; may be empty.
58    pub fn current_lines(&self) -> Range<usize> {
59        self.current_lines.clone()
60    }
61    /// Base source lines for diff3, with an exclusive end; may be empty.
62    pub fn base_lines(&self) -> Option<Range<usize>> {
63        self.base_lines.clone()
64    }
65    /// Incoming-side source lines, with an exclusive end; may be empty.
66    pub fn incoming_lines(&self) -> Range<usize> {
67        self.incoming_lines.clone()
68    }
69    /// The label from the opening marker.
70    pub fn current_label(&self) -> &SharedString {
71        &self.current_label
72    }
73    /// The base marker label, or None for a two-way conflict.
74    pub fn base_label(&self) -> Option<&SharedString> {
75        self.base.as_ref().map(|_| &self.base_label)
76    }
77    /// The label from the closing marker.
78    pub fn incoming_label(&self) -> &SharedString {
79        &self.incoming_label
80    }
81    /// Every line of the region, in file order.
82    pub(crate) fn source_lines(&self) -> Range<usize> {
83        self.current.start..self.incoming.end
84    }
85    pub(crate) fn part(&self, part: ConflictPart) -> Option<Range<usize>> {
86        match part {
87            ConflictPart::Current => Some(self.current.clone()),
88            ConflictPart::Base => self.base.clone(),
89            ConflictPart::Incoming => Some(self.incoming.clone()),
90        }
91    }
92    pub(crate) fn label(&self, part: ConflictPart) -> &SharedString {
93        match part {
94            ConflictPart::Current => &self.current_label,
95            ConflictPart::Base => &self.base_label,
96            ConflictPart::Incoming => &self.incoming_label,
97        }
98    }
99    /// The part a line of the region belongs to.
100    pub(crate) fn part_of(&self, ix: usize) -> Option<ConflictPart> {
101        [
102            ConflictPart::Current,
103            ConflictPart::Base,
104            ConflictPart::Incoming,
105        ]
106        .into_iter()
107        .find(|part| self.part(*part).is_some_and(|range| range.contains(&ix)))
108    }
109    /// The lines a resolution keeps.
110    pub(crate) fn kept(&self, resolution: DiffConflictResolution) -> Vec<Range<usize>> {
111        match resolution {
112            DiffConflictResolution::Current => vec![self.current.clone()],
113            DiffConflictResolution::Incoming => vec![self.incoming.clone()],
114            DiffConflictResolution::Both => vec![self.current.clone(), self.incoming.clone()],
115        }
116    }
117}
118
119/// Splits `text` into lines and their byte ranges, keeping line endings.
120fn line_ranges(text: &str) -> Vec<Range<usize>> {
121    let mut offset = 0;
122    text.split_inclusive('\n')
123        .map(|line| {
124            let range = offset..offset + line.len();
125            offset = range.end;
126            range
127        })
128        .collect()
129}
130
131impl DiffFile {
132    /// A file shown in full, for reference, without changes. It appears as a
133    /// single column in every display mode.
134    pub fn unchanged(path: impl Into<SharedString>, text: &str) -> Self {
135        Self::excerpts(path, [(1, text)])
136    }
137
138    /// Parts of a file shown for reference, without changes, each keeping
139    /// its own line numbers: `(first line, text)` per part, in file order
140    /// without overlap. A first line below 1 is clamped to 1. Like
141    /// [`Self::unchanged`] it is a single column in every display mode;
142    /// the lines between the parts are simply not there.
143    pub fn excerpts<'a>(
144        path: impl Into<SharedString>,
145        parts: impl IntoIterator<Item = (usize, &'a str)>,
146    ) -> Self {
147        let path = path.into();
148        let mut source = String::new();
149        let mut lines = Vec::new();
150        for (first, text) in parts {
151            // A part cut off mid-line must not run into the next one.
152            if !source.is_empty() && !source.ends_with('\n') {
153                source.push('\n');
154            }
155            debug_assert!(
156                lines.last().is_none_or(|(line, _)| first.max(1) > *line),
157                "excerpt parts must come in file order without overlap"
158            );
159            let offset = source.len();
160            lines.extend(
161                line_ranges(text)
162                    .into_iter()
163                    .enumerate()
164                    .map(|(ix, range)| {
165                        (first.max(1) + ix, offset + range.start..offset + range.end)
166                    }),
167            );
168            source.push_str(text);
169        }
170        let pairs = (0..lines.len())
171            .map(|ix| LinePair::new(None, Some(ix), false))
172            .collect();
173        DiffFile::new(
174            DiffFileStatus::Unchanged,
175            FileSide::new(Some(path.clone()), String::new(), []),
176            FileSide::new(Some(path), source, lines),
177            pairs,
178            Vec::new(),
179            Vec::new(),
180            false,
181        )
182    }
183
184    /// Parses a working file containing Git conflict markers, including the
185    /// `|||||||` base section of `diff3` style. Lines keep their numbers in
186    /// the working file; marker lines are shown as conflict headings instead.
187    pub fn parse_conflicts(
188        path: impl Into<SharedString>,
189        text: &str,
190    ) -> Result<Self, DiffParseError> {
191        let path = path.into();
192        let mut source = String::new();
193        let mut lines = Vec::new();
194        let mut pairs = Vec::new();
195        let mut conflicts = Vec::new();
196        // The marker-delimited part being read, with the open region's ranges.
197        let mut open: Option<(ConflictPart, DiffConflict)> = None;
198        for (ix, range) in line_ranges(text).into_iter().enumerate() {
199            let line = &text[range];
200            let content = line.trim_end_matches(['\n', '\r']);
201            let marker = |prefix: &str| {
202                content
203                    .strip_prefix(prefix)
204                    .filter(|rest| rest.is_empty() || rest.starts_with(' '))
205                    .map(|rest| SharedString::from(rest.trim().to_owned()))
206            };
207            let next = lines.len();
208            let (opening, base, separator, closing) = (
209                marker("<<<<<<<"),
210                marker("|||||||"),
211                marker("======="),
212                marker(">>>>>>>"),
213            );
214            match open.as_mut() {
215                None => {
216                    if let Some(label) = opening {
217                        open = Some((
218                            ConflictPart::Current,
219                            DiffConflict {
220                                lines: ix + 1..ix + 1,
221                                current_lines: ix + 2..ix + 2,
222                                base_lines: None,
223                                incoming_lines: ix + 2..ix + 2,
224                                current: next..next,
225                                base: None,
226                                incoming: next..next,
227                                current_label: label,
228                                base_label: SharedString::default(),
229                                incoming_label: SharedString::default(),
230                            },
231                        ));
232                        continue;
233                    }
234                    if base.is_some() || closing.is_some() {
235                        return Err(DiffParseError::new(
236                            ix + 1,
237                            "conflict marker outside a conflict",
238                        ));
239                    }
240                }
241                Some((part, conflict)) => {
242                    if opening.is_some() {
243                        return Err(DiffParseError::new(ix + 1, "nested conflict marker"));
244                    }
245                    match (*part, base, separator, closing) {
246                        (ConflictPart::Current, Some(label), _, _) => {
247                            conflict.current.end = next;
248                            conflict.current_lines.end = ix + 1;
249                            conflict.base_lines = Some(ix + 2..ix + 2);
250                            conflict.base = Some(next..next);
251                            conflict.base_label = label;
252                            *part = ConflictPart::Base;
253                            continue;
254                        }
255                        (ConflictPart::Current | ConflictPart::Base, _, Some(_), _) => {
256                            if *part == ConflictPart::Current {
257                                conflict.current.end = next;
258                                conflict.current_lines.end = ix + 1;
259                            } else if let Some(base) = &mut conflict.base {
260                                base.end = next;
261                                conflict.base_lines.as_mut().unwrap().end = ix + 1;
262                            }
263                            conflict.incoming = next..next;
264                            conflict.incoming_lines = ix + 2..ix + 2;
265                            *part = ConflictPart::Incoming;
266                            continue;
267                        }
268                        (ConflictPart::Incoming, _, _, Some(label)) => {
269                            conflict.incoming.end = next;
270                            conflict.incoming_lines.end = ix + 1;
271                            conflict.lines.end = ix + 2;
272                            conflict.incoming_label = label;
273                            if let Some((_, conflict)) = open.take() {
274                                conflicts.push(conflict);
275                            }
276                            continue;
277                        }
278                        _ => {}
279                    }
280                }
281            }
282            let start = source.len();
283            source.push_str(line);
284            lines.push((ix + 1, start..source.len()));
285            pairs.push(LinePair::new(None, Some(next), open.is_some()));
286        }
287        if open.is_some() {
288            return Err(DiffParseError::new(
289                text.lines().count(),
290                "unterminated conflict",
291            ));
292        }
293        Ok(DiffFile::new(
294            DiffFileStatus::Conflicted,
295            FileSide::new(Some(path.clone()), String::new(), []),
296            FileSide::new(Some(path), source, lines),
297            pairs,
298            Vec::new(),
299            Vec::new(),
300            false,
301        )
302        .with_conflicts(conflicts))
303    }
304}
305
306#[cfg(test)]
307mod tests {
308    use super::*;
309    use crate::diff::DiffSide;
310
311    const MERGE: &str = "fn retry() {\n<<<<<<< HEAD\n    3\n=======\n    5\n>>>>>>> feature\n}\n";
312
313    #[test]
314    fn unchanged_files_show_every_line_once() {
315        let file = DiffFile::unchanged("src/lib.rs", "one\r\ntwo\nlast");
316        assert_eq!(file.status(), DiffFileStatus::Unchanged);
317        assert!(!file.has_changes());
318        assert_eq!(file.lines_count(DiffSide::Modified), 3);
319        assert_eq!(file.lines_count(DiffSide::Original), 0);
320        assert_eq!(
321            file.text_for_lines(DiffSide::Modified, 1, 3),
322            "one\r\ntwo\nlast"
323        );
324        assert!(DiffFile::unchanged("empty", "").pairs().is_empty());
325    }
326
327    #[test]
328    fn excerpts_keep_each_parts_line_numbers() {
329        let file = DiffFile::excerpts(
330            "src/lib.rs",
331            [
332                (40, "fn a() {\n}\n"),
333                (90, "fn b() {}"),
334                (120, "fn c() {}\n"),
335            ],
336        );
337        assert_eq!(file.status(), DiffFileStatus::Unchanged);
338        let numbers: Vec<usize> = (0..file.lines_count(DiffSide::Modified))
339            .map(|ix| file.line_number(DiffSide::Modified, ix))
340            .collect();
341        assert_eq!(numbers, [40, 41, 90, 120]);
342        assert_eq!(file.line_index(DiffSide::Modified, 90), Some(2));
343        assert_eq!(file.line_index(DiffSide::Modified, 60), None);
344        // A part without a final newline does not swallow the next one.
345        assert_eq!(
346            file.text_for_lines(DiffSide::Modified, 90, 120),
347            "fn b() {}\nfn c() {}\n"
348        );
349    }
350
351    #[test]
352    fn conflicts_keep_working_file_line_numbers() {
353        let file = DiffFile::parse_conflicts("src/retry.rs", MERGE).unwrap();
354        assert_eq!(file.status(), DiffFileStatus::Conflicted);
355        let numbers = file
356            .lines(DiffSide::Modified)
357            .iter()
358            .map(|line| line.line_number())
359            .collect::<Vec<_>>();
360        assert_eq!(numbers, [1, 3, 5, 7]);
361        let conflict = &file.conflicts()[0];
362        assert_eq!(conflict.lines(), 2..7);
363        assert_eq!(conflict.current_lines(), 3..4);
364        assert_eq!(conflict.incoming_lines(), 5..6);
365        assert_eq!(conflict.base_lines(), None);
366        assert_eq!(conflict.base_label(), None);
367        assert_eq!(conflict.current_label().as_str(), "HEAD");
368        assert_eq!(conflict.incoming_label().as_str(), "feature");
369        assert_eq!(conflict.part(ConflictPart::Current), Some(1..2));
370        assert_eq!(conflict.part(ConflictPart::Incoming), Some(2..3));
371        assert_eq!(conflict.label(ConflictPart::Current).as_str(), "HEAD");
372        assert_eq!(conflict.label(ConflictPart::Incoming).as_str(), "feature");
373        assert_eq!(conflict.part_of(2), Some(ConflictPart::Incoming));
374        assert!(file.pairs()[1].is_changed() && !file.pairs()[0].is_changed());
375    }
376
377    #[test]
378    fn diff3_bases_and_malformed_markers() {
379        let file = DiffFile::parse_conflicts(
380            "a.txt",
381            "<<<<<<< ours\na\n||||||| base\nb\n=======\nc\n>>>>>>> theirs\n",
382        )
383        .unwrap();
384        let conflict = &file.conflicts()[0];
385        assert_eq!(conflict.lines(), 1..8);
386        assert_eq!(conflict.current_lines(), 2..3);
387        assert_eq!(conflict.base_lines(), Some(4..5));
388        assert_eq!(conflict.incoming_lines(), 6..7);
389        assert_eq!(conflict.base_label().unwrap().as_str(), "base");
390        assert_eq!(conflict.part(ConflictPart::Base), Some(1..2));
391        assert_eq!(conflict.label(ConflictPart::Base).as_str(), "base");
392        assert_eq!(conflict.kept(DiffConflictResolution::Both), [0..1, 2..3]);
393        for text in [
394            "<<<<<<< a\nx\n",
395            "<<<<<<< a\n<<<<<<< b\n",
396            ">>>>>>> stray\n",
397        ] {
398            let error = DiffFile::parse_conflicts("a.txt", text).err().unwrap();
399            assert!(error.line() > 0);
400        }
401        let empty = DiffFile::parse_conflicts(
402            "empty.txt",
403            "<<<<<<< ours\n||||||| base\n=======\n>>>>>>> theirs\n",
404        )
405        .unwrap();
406        let conflict = &empty.conflicts()[0];
407        assert_eq!(conflict.lines(), 1..5);
408        assert_eq!(conflict.current_lines(), 2..2);
409        assert_eq!(conflict.base_lines(), Some(3..3));
410        assert_eq!(conflict.incoming_lines(), 4..4);
411        // A separator outside a conflict is ordinary text.
412        assert!(DiffFile::parse_conflicts("a.md", "title\n=======\n").is_ok());
413    }
414}