1use gpui::{App, Context, Entity, EventEmitter};
2use std::{cmp::Ordering, ops::Range, sync::Arc};
3use text::{Anchor, BufferId, OffsetRangeExt as _};
4
5pub struct ConflictSet {
6 pub has_conflict: bool,
7 pub snapshot: ConflictSetSnapshot,
8}
9
10#[derive(Clone, Debug, PartialEq, Eq)]
11pub struct ConflictSetUpdate {
12 pub buffer_range: Option<Range<Anchor>>,
13 pub old_range: Range<usize>,
14 pub new_range: Range<usize>,
15}
16
17#[derive(Debug, Clone)]
18pub struct ConflictSetSnapshot {
19 pub buffer_id: BufferId,
20 pub conflicts: Arc<[ConflictRegion]>,
21}
22
23impl ConflictSetSnapshot {
24 pub fn conflicts_in_range(
25 &self,
26 range: Range<Anchor>,
27 buffer: &text::BufferSnapshot,
28 ) -> &[ConflictRegion] {
29 let start_ix = self
30 .conflicts
31 .binary_search_by(|conflict| {
32 conflict
33 .range
34 .end
35 .cmp(&range.start, buffer)
36 .then(Ordering::Greater)
37 })
38 .unwrap_err();
39 let end_ix = start_ix
40 + self.conflicts[start_ix..]
41 .binary_search_by(|conflict| {
42 conflict
43 .range
44 .start
45 .cmp(&range.end, buffer)
46 .then(Ordering::Less)
47 })
48 .unwrap_err();
49 &self.conflicts[start_ix..end_ix]
50 }
51
52 pub fn compare(&self, other: &Self, buffer: &text::BufferSnapshot) -> ConflictSetUpdate {
53 let common_prefix_len = self
54 .conflicts
55 .iter()
56 .zip(other.conflicts.iter())
57 .take_while(|(old, new)| old == new)
58 .count();
59 let common_suffix_len = self.conflicts[common_prefix_len..]
60 .iter()
61 .rev()
62 .zip(other.conflicts[common_prefix_len..].iter().rev())
63 .take_while(|(old, new)| old == new)
64 .count();
65 let old_conflicts =
66 &self.conflicts[common_prefix_len..(self.conflicts.len() - common_suffix_len)];
67 let new_conflicts =
68 &other.conflicts[common_prefix_len..(other.conflicts.len() - common_suffix_len)];
69 let old_range = common_prefix_len..(common_prefix_len + old_conflicts.len());
70 let new_range = common_prefix_len..(common_prefix_len + new_conflicts.len());
71 let start = match (old_conflicts.first(), new_conflicts.first()) {
72 (None, None) => None,
73 (None, Some(conflict)) => Some(conflict.range.start),
74 (Some(conflict), None) => Some(conflict.range.start),
75 (Some(first), Some(second)) => Some(first.range.start.min(&second.range.start, buffer)),
76 };
77 let end = match (old_conflicts.last(), new_conflicts.last()) {
78 (None, None) => None,
79 (None, Some(conflict)) => Some(conflict.range.end),
80 (Some(first), None) => Some(first.range.end),
81 (Some(first), Some(second)) => Some(first.range.end.max(&second.range.end, buffer)),
82 };
83 ConflictSetUpdate {
84 buffer_range: start.zip(end).map(|(start, end)| start..end),
85 old_range,
86 new_range,
87 }
88 }
89}
90
91#[derive(Debug, Clone, PartialEq, Eq)]
92pub struct ConflictRegion {
93 pub range: Range<Anchor>,
94 pub ours: Range<Anchor>,
95 pub theirs: Range<Anchor>,
96 pub base: Option<Range<Anchor>>,
97}
98
99impl ConflictRegion {
100 pub fn resolve(
101 &self,
102 buffer: Entity<language::Buffer>,
103 ranges: &[Range<Anchor>],
104 cx: &mut App,
105 ) {
106 let buffer_snapshot = buffer.read(cx).snapshot();
107 let mut deletions = Vec::new();
108 let empty = "";
109 let outer_range = self.range.to_offset(&buffer_snapshot);
110 let mut offset = outer_range.start;
111 for kept_range in ranges {
112 let kept_range = kept_range.to_offset(&buffer_snapshot);
113 if kept_range.start > offset {
114 deletions.push((offset..kept_range.start, empty));
115 }
116 offset = kept_range.end;
117 }
118 if outer_range.end > offset {
119 deletions.push((offset..outer_range.end, empty));
120 }
121
122 buffer.update(cx, |buffer, cx| {
123 buffer.edit(deletions, None, cx);
124 });
125 }
126}
127
128impl ConflictSet {
129 pub fn new(buffer_id: BufferId, has_conflict: bool, _: &mut Context<Self>) -> Self {
130 Self {
131 has_conflict,
132 snapshot: ConflictSetSnapshot {
133 buffer_id,
134 conflicts: Default::default(),
135 },
136 }
137 }
138
139 pub fn set_has_conflict(&mut self, has_conflict: bool, cx: &mut Context<Self>) -> bool {
140 if has_conflict != self.has_conflict {
141 self.has_conflict = has_conflict;
142 if !self.has_conflict {
143 cx.emit(ConflictSetUpdate {
144 buffer_range: None,
145 old_range: 0..self.snapshot.conflicts.len(),
146 new_range: 0..0,
147 });
148 self.snapshot.conflicts = Default::default();
149 }
150 true
151 } else {
152 false
153 }
154 }
155
156 pub fn snapshot(&self) -> ConflictSetSnapshot {
157 self.snapshot.clone()
158 }
159
160 pub fn set_snapshot(
161 &mut self,
162 snapshot: ConflictSetSnapshot,
163 update: ConflictSetUpdate,
164 cx: &mut Context<Self>,
165 ) {
166 self.snapshot = snapshot;
167 cx.emit(update);
168 }
169
170 pub fn parse(buffer: &text::BufferSnapshot) -> ConflictSetSnapshot {
171 let mut conflicts = Vec::new();
172
173 let mut line_pos = 0;
174 let buffer_len = buffer.len();
175 let mut lines = buffer.text_for_range(0..buffer_len).lines();
176
177 let mut conflict_start: Option<usize> = None;
178 let mut ours_start: Option<usize> = None;
179 let mut ours_end: Option<usize> = None;
180 let mut base_start: Option<usize> = None;
181 let mut base_end: Option<usize> = None;
182 let mut theirs_start: Option<usize> = None;
183
184 while let Some(line) = lines.next() {
185 let line_end = line_pos + line.len();
186
187 if line.starts_with("<<<<<<< ") {
188 // If we see a new conflict marker while already parsing one,
189 // abandon the previous one and start a new one
190 conflict_start = Some(line_pos);
191 ours_start = Some(line_end + 1);
192 } else if line.starts_with("||||||| ")
193 && conflict_start.is_some()
194 && ours_start.is_some()
195 {
196 ours_end = Some(line_pos);
197 base_start = Some(line_end + 1);
198 } else if line.starts_with("=======")
199 && conflict_start.is_some()
200 && ours_start.is_some()
201 {
202 // Set ours_end if not already set (would be set if we have base markers)
203 if ours_end.is_none() {
204 ours_end = Some(line_pos);
205 } else if base_start.is_some() {
206 base_end = Some(line_pos);
207 }
208 theirs_start = Some(line_end + 1);
209 } else if line.starts_with(">>>>>>> ")
210 && conflict_start.is_some()
211 && ours_start.is_some()
212 && ours_end.is_some()
213 && theirs_start.is_some()
214 {
215 let theirs_end = line_pos;
216 let conflict_end = (line_end + 1).min(buffer_len);
217
218 let range = buffer.anchor_after(conflict_start.unwrap())
219 ..buffer.anchor_before(conflict_end);
220 let ours = buffer.anchor_after(ours_start.unwrap())
221 ..buffer.anchor_before(ours_end.unwrap());
222 let theirs =
223 buffer.anchor_after(theirs_start.unwrap())..buffer.anchor_before(theirs_end);
224
225 let base = base_start
226 .zip(base_end)
227 .map(|(start, end)| buffer.anchor_after(start)..buffer.anchor_before(end));
228
229 conflicts.push(ConflictRegion {
230 range,
231 ours,
232 theirs,
233 base,
234 });
235
236 conflict_start = None;
237 ours_start = None;
238 ours_end = None;
239 base_start = None;
240 base_end = None;
241 theirs_start = None;
242 }
243
244 line_pos = line_end + 1;
245 }
246
247 ConflictSetSnapshot {
248 conflicts: conflicts.into(),
249 buffer_id: buffer.remote_id(),
250 }
251 }
252}
253
254impl EventEmitter<ConflictSetUpdate> for ConflictSet {}
255
256#[cfg(test)]
257mod tests {
258 use std::{path::Path, sync::mpsc};
259
260 use crate::{Project, project_settings::ProjectSettings};
261
262 use super::*;
263 use fs::FakeFs;
264 use git::status::{UnmergedStatus, UnmergedStatusCode};
265 use gpui::{BackgroundExecutor, TestAppContext};
266 use language::language_settings::AllLanguageSettings;
267 use serde_json::json;
268 use settings::Settings as _;
269 use text::{Buffer, BufferId, Point, ToOffset as _};
270 use unindent::Unindent as _;
271 use util::path;
272 use worktree::WorktreeSettings;
273
274 #[test]
275 fn test_parse_conflicts_in_buffer() {
276 // Create a buffer with conflict markers
277 let test_content = r#"
278 This is some text before the conflict.
279 <<<<<<< HEAD
280 This is our version
281 =======
282 This is their version
283 >>>>>>> branch-name
284
285 Another conflict:
286 <<<<<<< HEAD
287 Our second change
288 ||||||| merged common ancestors
289 Original content
290 =======
291 Their second change
292 >>>>>>> branch-name
293 "#
294 .unindent();
295
296 let buffer_id = BufferId::new(1).unwrap();
297 let buffer = Buffer::new(0, buffer_id, test_content);
298 let snapshot = buffer.snapshot();
299
300 let conflict_snapshot = ConflictSet::parse(&snapshot);
301 assert_eq!(conflict_snapshot.conflicts.len(), 2);
302
303 let first = &conflict_snapshot.conflicts[0];
304 assert!(first.base.is_none());
305 let our_text = snapshot
306 .text_for_range(first.ours.clone())
307 .collect::<String>();
308 let their_text = snapshot
309 .text_for_range(first.theirs.clone())
310 .collect::<String>();
311 assert_eq!(our_text, "This is our version\n");
312 assert_eq!(their_text, "This is their version\n");
313
314 let second = &conflict_snapshot.conflicts[1];
315 assert!(second.base.is_some());
316 let our_text = snapshot
317 .text_for_range(second.ours.clone())
318 .collect::<String>();
319 let their_text = snapshot
320 .text_for_range(second.theirs.clone())
321 .collect::<String>();
322 let base_text = snapshot
323 .text_for_range(second.base.as_ref().unwrap().clone())
324 .collect::<String>();
325 assert_eq!(our_text, "Our second change\n");
326 assert_eq!(their_text, "Their second change\n");
327 assert_eq!(base_text, "Original content\n");
328
329 // Test conflicts_in_range
330 let range = snapshot.anchor_before(0)..snapshot.anchor_before(snapshot.len());
331 let conflicts_in_range = conflict_snapshot.conflicts_in_range(range, &snapshot);
332 assert_eq!(conflicts_in_range.len(), 2);
333
334 // Test with a range that includes only the first conflict
335 let first_conflict_end = conflict_snapshot.conflicts[0].range.end;
336 let range = snapshot.anchor_before(0)..first_conflict_end;
337 let conflicts_in_range = conflict_snapshot.conflicts_in_range(range, &snapshot);
338 assert_eq!(conflicts_in_range.len(), 1);
339
340 // Test with a range that includes only the second conflict
341 let second_conflict_start = conflict_snapshot.conflicts[1].range.start;
342 let range = second_conflict_start..snapshot.anchor_before(snapshot.len());
343 let conflicts_in_range = conflict_snapshot.conflicts_in_range(range, &snapshot);
344 assert_eq!(conflicts_in_range.len(), 1);
345
346 // Test with a range that doesn't include any conflicts
347 let range = buffer.anchor_after(first_conflict_end.to_offset(&buffer) + 1)
348 ..buffer.anchor_before(second_conflict_start.to_offset(&buffer) - 1);
349 let conflicts_in_range = conflict_snapshot.conflicts_in_range(range, &snapshot);
350 assert_eq!(conflicts_in_range.len(), 0);
351 }
352
353 #[test]
354 fn test_nested_conflict_markers() {
355 // Create a buffer with nested conflict markers
356 let test_content = r#"
357 This is some text before the conflict.
358 <<<<<<< HEAD
359 This is our version
360 <<<<<<< HEAD
361 This is a nested conflict marker
362 =======
363 This is their version in a nested conflict
364 >>>>>>> branch-nested
365 =======
366 This is their version
367 >>>>>>> branch-name
368 "#
369 .unindent();
370
371 let buffer_id = BufferId::new(1).unwrap();
372 let buffer = Buffer::new(0, buffer_id, test_content);
373 let snapshot = buffer.snapshot();
374
375 let conflict_snapshot = ConflictSet::parse(&snapshot);
376
377 assert_eq!(conflict_snapshot.conflicts.len(), 1);
378
379 // The conflict should have our version, their version, but no base
380 let conflict = &conflict_snapshot.conflicts[0];
381 assert!(conflict.base.is_none());
382
383 // Check that the nested conflict was detected correctly
384 let our_text = snapshot
385 .text_for_range(conflict.ours.clone())
386 .collect::<String>();
387 assert_eq!(our_text, "This is a nested conflict marker\n");
388 let their_text = snapshot
389 .text_for_range(conflict.theirs.clone())
390 .collect::<String>();
391 assert_eq!(their_text, "This is their version in a nested conflict\n");
392 }
393
394 #[test]
395 fn test_conflict_markers_at_eof() {
396 let test_content = r#"
397 <<<<<<< ours
398 =======
399 This is their version
400 >>>>>>> "#
401 .unindent();
402 let buffer_id = BufferId::new(1).unwrap();
403 let buffer = Buffer::new(0, buffer_id, test_content);
404 let snapshot = buffer.snapshot();
405
406 let conflict_snapshot = ConflictSet::parse(&snapshot);
407 assert_eq!(conflict_snapshot.conflicts.len(), 1);
408 }
409
410 #[test]
411 fn test_conflicts_in_range() {
412 // Create a buffer with conflict markers
413 let test_content = r#"
414 one
415 <<<<<<< HEAD1
416 two
417 =======
418 three
419 >>>>>>> branch1
420 four
421 five
422 <<<<<<< HEAD2
423 six
424 =======
425 seven
426 >>>>>>> branch2
427 eight
428 nine
429 <<<<<<< HEAD3
430 ten
431 =======
432 eleven
433 >>>>>>> branch3
434 twelve
435 <<<<<<< HEAD4
436 thirteen
437 =======
438 fourteen
439 >>>>>>> branch4
440 fifteen
441 "#
442 .unindent();
443
444 let buffer_id = BufferId::new(1).unwrap();
445 let buffer = Buffer::new(0, buffer_id, test_content.clone());
446 let snapshot = buffer.snapshot();
447
448 let conflict_snapshot = ConflictSet::parse(&snapshot);
449 assert_eq!(conflict_snapshot.conflicts.len(), 4);
450
451 let range = test_content.find("seven").unwrap()..test_content.find("eleven").unwrap();
452 let range = buffer.anchor_before(range.start)..buffer.anchor_after(range.end);
453 assert_eq!(
454 conflict_snapshot.conflicts_in_range(range, &snapshot),
455 &conflict_snapshot.conflicts[1..=2]
456 );
457
458 let range = test_content.find("one").unwrap()..test_content.find("<<<<<<< HEAD2").unwrap();
459 let range = buffer.anchor_before(range.start)..buffer.anchor_after(range.end);
460 assert_eq!(
461 conflict_snapshot.conflicts_in_range(range, &snapshot),
462 &conflict_snapshot.conflicts[0..=1]
463 );
464
465 let range =
466 test_content.find("eight").unwrap() - 1..test_content.find(">>>>>>> branch3").unwrap();
467 let range = buffer.anchor_before(range.start)..buffer.anchor_after(range.end);
468 assert_eq!(
469 conflict_snapshot.conflicts_in_range(range, &snapshot),
470 &conflict_snapshot.conflicts[1..=2]
471 );
472
473 let range = test_content.find("thirteen").unwrap() - 1..test_content.len();
474 let range = buffer.anchor_before(range.start)..buffer.anchor_after(range.end);
475 assert_eq!(
476 conflict_snapshot.conflicts_in_range(range, &snapshot),
477 &conflict_snapshot.conflicts[3..=3]
478 );
479 }
480
481 #[gpui::test]
482 async fn test_conflict_updates(executor: BackgroundExecutor, cx: &mut TestAppContext) {
483 zlog::init_test();
484 cx.update(|cx| {
485 settings::init(cx);
486 WorktreeSettings::register(cx);
487 ProjectSettings::register(cx);
488 AllLanguageSettings::register(cx);
489 });
490 let initial_text = "
491 one
492 two
493 three
494 four
495 five
496 "
497 .unindent();
498 let fs = FakeFs::new(executor);
499 fs.insert_tree(
500 path!("/project"),
501 json!({
502 ".git": {},
503 "a.txt": initial_text,
504 }),
505 )
506 .await;
507 let project = Project::test(fs.clone(), [path!("/project").as_ref()], cx).await;
508 let (git_store, buffer) = project.update(cx, |project, cx| {
509 (
510 project.git_store().clone(),
511 project.open_local_buffer(path!("/project/a.txt"), cx),
512 )
513 });
514 let buffer = buffer.await.unwrap();
515 let conflict_set = git_store.update(cx, |git_store, cx| {
516 git_store.open_conflict_set(buffer.clone(), cx)
517 });
518 let (events_tx, events_rx) = mpsc::channel::<ConflictSetUpdate>();
519 let _conflict_set_subscription = cx.update(|cx| {
520 cx.subscribe(&conflict_set, move |_, event, _| {
521 events_tx.send(event.clone()).ok();
522 })
523 });
524 let conflicts_snapshot =
525 conflict_set.read_with(cx, |conflict_set, _| conflict_set.snapshot());
526 assert!(conflicts_snapshot.conflicts.is_empty());
527
528 buffer.update(cx, |buffer, cx| {
529 buffer.edit(
530 [
531 (4..4, "<<<<<<< HEAD\n"),
532 (14..14, "=======\nTWO\n>>>>>>> branch\n"),
533 ],
534 None,
535 cx,
536 );
537 });
538
539 cx.run_until_parked();
540 events_rx.try_recv().expect_err(
541 "no conflicts should be registered as long as the file's status is unchanged",
542 );
543
544 fs.with_git_state(path!("/project/.git").as_ref(), true, |state| {
545 state.unmerged_paths.insert(
546 "a.txt".into(),
547 UnmergedStatus {
548 first_head: UnmergedStatusCode::Updated,
549 second_head: UnmergedStatusCode::Updated,
550 },
551 );
552 // Cause the repository to emit MergeHeadsChanged.
553 state.refs.insert("MERGE_HEAD".into(), "123".into())
554 })
555 .unwrap();
556
557 cx.run_until_parked();
558 let update = events_rx
559 .try_recv()
560 .expect("status change should trigger conflict parsing");
561 assert_eq!(update.old_range, 0..0);
562 assert_eq!(update.new_range, 0..1);
563
564 let conflict = conflict_set.read_with(cx, |conflict_set, _| {
565 conflict_set.snapshot().conflicts[0].clone()
566 });
567 cx.update(|cx| {
568 conflict.resolve(buffer.clone(), std::slice::from_ref(&conflict.theirs), cx);
569 });
570
571 cx.run_until_parked();
572 let update = events_rx
573 .try_recv()
574 .expect("conflicts should be removed after resolution");
575 assert_eq!(update.old_range, 0..1);
576 assert_eq!(update.new_range, 0..0);
577 }
578
579 #[gpui::test]
580 async fn test_conflict_updates_without_merge_head(
581 executor: BackgroundExecutor,
582 cx: &mut TestAppContext,
583 ) {
584 zlog::init_test();
585 cx.update(|cx| {
586 settings::init(cx);
587 WorktreeSettings::register(cx);
588 ProjectSettings::register(cx);
589 AllLanguageSettings::register(cx);
590 });
591
592 let initial_text = "
593 zero
594 <<<<<<< HEAD
595 one
596 =======
597 two
598 >>>>>>> Stashed Changes
599 three
600 "
601 .unindent();
602
603 let fs = FakeFs::new(executor);
604 fs.insert_tree(
605 path!("/project"),
606 json!({
607 ".git": {},
608 "a.txt": initial_text,
609 }),
610 )
611 .await;
612
613 let project = Project::test(fs.clone(), [path!("/project").as_ref()], cx).await;
614 let (git_store, buffer) = project.update(cx, |project, cx| {
615 (
616 project.git_store().clone(),
617 project.open_local_buffer(path!("/project/a.txt"), cx),
618 )
619 });
620
621 cx.run_until_parked();
622 fs.with_git_state(path!("/project/.git").as_ref(), true, |state| {
623 state.unmerged_paths.insert(
624 "a.txt".into(),
625 UnmergedStatus {
626 first_head: UnmergedStatusCode::Updated,
627 second_head: UnmergedStatusCode::Updated,
628 },
629 )
630 })
631 .unwrap();
632
633 let buffer = buffer.await.unwrap();
634
635 // Open the conflict set for a file that currently has conflicts.
636 let conflict_set = git_store.update(cx, |git_store, cx| {
637 git_store.open_conflict_set(buffer.clone(), cx)
638 });
639
640 cx.run_until_parked();
641 conflict_set.update(cx, |conflict_set, cx| {
642 let conflict_range = conflict_set.snapshot().conflicts[0]
643 .range
644 .to_point(buffer.read(cx));
645 assert_eq!(conflict_range, Point::new(1, 0)..Point::new(6, 0));
646 });
647
648 // Simulate the conflict being removed by e.g. staging the file.
649 fs.with_git_state(path!("/project/.git").as_ref(), true, |state| {
650 state.unmerged_paths.remove(Path::new("a.txt"))
651 })
652 .unwrap();
653
654 cx.run_until_parked();
655 conflict_set.update(cx, |conflict_set, _| {
656 assert!(!conflict_set.has_conflict);
657 assert_eq!(conflict_set.snapshot.conflicts.len(), 0);
658 });
659
660 // Simulate the conflict being re-added.
661 fs.with_git_state(path!("/project/.git").as_ref(), true, |state| {
662 state.unmerged_paths.insert(
663 "a.txt".into(),
664 UnmergedStatus {
665 first_head: UnmergedStatusCode::Updated,
666 second_head: UnmergedStatusCode::Updated,
667 },
668 )
669 })
670 .unwrap();
671
672 cx.run_until_parked();
673 conflict_set.update(cx, |conflict_set, cx| {
674 let conflict_range = conflict_set.snapshot().conflicts[0]
675 .range
676 .to_point(buffer.read(cx));
677 assert_eq!(conflict_range, Point::new(1, 0)..Point::new(6, 0));
678 });
679 }
680}