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