1use std::ops::Range;
4
5use gpui::SharedString;
6
7use super::{
8 DiffFile, DiffFileStatus, DiffParseError,
9 document::{FileSide, LinePair},
10};
11
12#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
14#[non_exhaustive]
15pub enum DiffConflictResolution {
16 Current,
18 Incoming,
20 Both,
22}
23
24#[derive(Clone, Copy, Debug, PartialEq, Eq)]
26pub(crate) enum ConflictPart {
27 Current,
28 Base,
29 Incoming,
30}
31
32#[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 pub fn lines(&self) -> Range<usize> {
55 self.lines.clone()
56 }
57 pub fn current_lines(&self) -> Range<usize> {
59 self.current_lines.clone()
60 }
61 pub fn base_lines(&self) -> Option<Range<usize>> {
63 self.base_lines.clone()
64 }
65 pub fn incoming_lines(&self) -> Range<usize> {
67 self.incoming_lines.clone()
68 }
69 pub fn current_label(&self) -> &SharedString {
71 &self.current_label
72 }
73 pub fn base_label(&self) -> Option<&SharedString> {
75 self.base.as_ref().map(|_| &self.base_label)
76 }
77 pub fn incoming_label(&self) -> &SharedString {
79 &self.incoming_label
80 }
81 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 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 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
119fn 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 pub fn unchanged(path: impl Into<SharedString>, text: &str) -> Self {
135 Self::excerpts(path, [(1, text)])
136 }
137
138 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 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 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 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 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 assert!(DiffFile::parse_conflicts("a.md", "title\n=======\n").is_ok());
413 }
414}