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::{RepoPath, repo_path},
268 status::{UnmergedStatus, UnmergedStatusCode},
269 };
270 use gpui::{BackgroundExecutor, TestAppContext};
271 use serde_json::json;
272 use text::{Buffer, BufferId, Point, ReplicaId, ToOffset as _};
273 use unindent::Unindent as _;
274 use util::{path, rel_path::rel_path};
275
276 #[test]
277 fn test_parse_conflicts_in_buffer() {
278 // Create a buffer with conflict markers
279 let test_content = r#"
280 This is some text before the conflict.
281 <<<<<<< HEAD
282 This is our version
283 =======
284 This is their version
285 >>>>>>> branch-name
286
287 Another conflict:
288 <<<<<<< HEAD
289 Our second change
290 ||||||| merged common ancestors
291 Original content
292 =======
293 Their second change
294 >>>>>>> branch-name
295 "#
296 .unindent();
297
298 let buffer_id = BufferId::new(1).unwrap();
299 let buffer = Buffer::new(ReplicaId::LOCAL, buffer_id, test_content);
300 let snapshot = buffer.snapshot();
301
302 let conflict_snapshot = ConflictSet::parse(&snapshot);
303 assert_eq!(conflict_snapshot.conflicts.len(), 2);
304
305 let first = &conflict_snapshot.conflicts[0];
306 assert!(first.base.is_none());
307 let our_text = snapshot
308 .text_for_range(first.ours.clone())
309 .collect::<String>();
310 let their_text = snapshot
311 .text_for_range(first.theirs.clone())
312 .collect::<String>();
313 assert_eq!(our_text, "This is our version\n");
314 assert_eq!(their_text, "This is their version\n");
315
316 let second = &conflict_snapshot.conflicts[1];
317 assert!(second.base.is_some());
318 let our_text = snapshot
319 .text_for_range(second.ours.clone())
320 .collect::<String>();
321 let their_text = snapshot
322 .text_for_range(second.theirs.clone())
323 .collect::<String>();
324 let base_text = snapshot
325 .text_for_range(second.base.as_ref().unwrap().clone())
326 .collect::<String>();
327 assert_eq!(our_text, "Our second change\n");
328 assert_eq!(their_text, "Their second change\n");
329 assert_eq!(base_text, "Original content\n");
330
331 // Test conflicts_in_range
332 let range = snapshot.anchor_before(0)..snapshot.anchor_before(snapshot.len());
333 let conflicts_in_range = conflict_snapshot.conflicts_in_range(range, &snapshot);
334 assert_eq!(conflicts_in_range.len(), 2);
335
336 // Test with a range that includes only the first conflict
337 let first_conflict_end = conflict_snapshot.conflicts[0].range.end;
338 let range = snapshot.anchor_before(0)..first_conflict_end;
339 let conflicts_in_range = conflict_snapshot.conflicts_in_range(range, &snapshot);
340 assert_eq!(conflicts_in_range.len(), 1);
341
342 // Test with a range that includes only the second conflict
343 let second_conflict_start = conflict_snapshot.conflicts[1].range.start;
344 let range = second_conflict_start..snapshot.anchor_before(snapshot.len());
345 let conflicts_in_range = conflict_snapshot.conflicts_in_range(range, &snapshot);
346 assert_eq!(conflicts_in_range.len(), 1);
347
348 // Test with a range that doesn't include any conflicts
349 let range = buffer.anchor_after(first_conflict_end.to_next_offset(&buffer))
350 ..buffer.anchor_before(second_conflict_start.to_previous_offset(&buffer));
351 let conflicts_in_range = conflict_snapshot.conflicts_in_range(range, &snapshot);
352 assert_eq!(conflicts_in_range.len(), 0);
353 }
354
355 #[test]
356 fn test_nested_conflict_markers() {
357 // Create a buffer with nested conflict markers
358 let test_content = r#"
359 This is some text before the conflict.
360 <<<<<<< HEAD
361 This is our version
362 <<<<<<< HEAD
363 This is a nested conflict marker
364 =======
365 This is their version in a nested conflict
366 >>>>>>> branch-nested
367 =======
368 This is their version
369 >>>>>>> branch-name
370 "#
371 .unindent();
372
373 let buffer_id = BufferId::new(1).unwrap();
374 let buffer = Buffer::new(ReplicaId::LOCAL, buffer_id, test_content);
375 let snapshot = buffer.snapshot();
376
377 let conflict_snapshot = ConflictSet::parse(&snapshot);
378
379 assert_eq!(conflict_snapshot.conflicts.len(), 1);
380
381 // The conflict should have our version, their version, but no base
382 let conflict = &conflict_snapshot.conflicts[0];
383 assert!(conflict.base.is_none());
384
385 // Check that the nested conflict was detected correctly
386 let our_text = snapshot
387 .text_for_range(conflict.ours.clone())
388 .collect::<String>();
389 assert_eq!(our_text, "This is a nested conflict marker\n");
390 let their_text = snapshot
391 .text_for_range(conflict.theirs.clone())
392 .collect::<String>();
393 assert_eq!(their_text, "This is their version in a nested conflict\n");
394 }
395
396 #[test]
397 fn test_conflict_markers_at_eof() {
398 let test_content = r#"
399 <<<<<<< ours
400 =======
401 This is their version
402 >>>>>>> "#
403 .unindent();
404 let buffer_id = BufferId::new(1).unwrap();
405 let buffer = Buffer::new(ReplicaId::LOCAL, buffer_id, test_content);
406 let snapshot = buffer.snapshot();
407
408 let conflict_snapshot = ConflictSet::parse(&snapshot);
409 assert_eq!(conflict_snapshot.conflicts.len(), 1);
410 }
411
412 #[test]
413 fn test_conflicts_in_range() {
414 // Create a buffer with conflict markers
415 let test_content = r#"
416 one
417 <<<<<<< HEAD1
418 two
419 =======
420 three
421 >>>>>>> branch1
422 four
423 five
424 <<<<<<< HEAD2
425 six
426 =======
427 seven
428 >>>>>>> branch2
429 eight
430 nine
431 <<<<<<< HEAD3
432 ten
433 =======
434 eleven
435 >>>>>>> branch3
436 twelve
437 <<<<<<< HEAD4
438 thirteen
439 =======
440 fourteen
441 >>>>>>> branch4
442 fifteen
443 "#
444 .unindent();
445
446 let buffer_id = BufferId::new(1).unwrap();
447 let buffer = Buffer::new(ReplicaId::LOCAL, buffer_id, test_content.clone());
448 let snapshot = buffer.snapshot();
449
450 let conflict_snapshot = ConflictSet::parse(&snapshot);
451 assert_eq!(conflict_snapshot.conflicts.len(), 4);
452
453 let range = test_content.find("seven").unwrap()..test_content.find("eleven").unwrap();
454 let range = buffer.anchor_before(range.start)..buffer.anchor_after(range.end);
455 assert_eq!(
456 conflict_snapshot.conflicts_in_range(range, &snapshot),
457 &conflict_snapshot.conflicts[1..=2]
458 );
459
460 let range = test_content.find("one").unwrap()..test_content.find("<<<<<<< HEAD2").unwrap();
461 let range = buffer.anchor_before(range.start)..buffer.anchor_after(range.end);
462 assert_eq!(
463 conflict_snapshot.conflicts_in_range(range, &snapshot),
464 &conflict_snapshot.conflicts[0..=1]
465 );
466
467 let range =
468 test_content.find("eight").unwrap() - 1..test_content.find(">>>>>>> branch3").unwrap();
469 let range = buffer.anchor_before(range.start)..buffer.anchor_after(range.end);
470 assert_eq!(
471 conflict_snapshot.conflicts_in_range(range, &snapshot),
472 &conflict_snapshot.conflicts[1..=2]
473 );
474
475 let range = test_content.find("thirteen").unwrap() - 1..test_content.len();
476 let range = buffer.anchor_before(range.start)..buffer.anchor_after(range.end);
477 assert_eq!(
478 conflict_snapshot.conflicts_in_range(range, &snapshot),
479 &conflict_snapshot.conflicts[3..=3]
480 );
481 }
482
483 #[gpui::test]
484 async fn test_conflict_updates(executor: BackgroundExecutor, cx: &mut TestAppContext) {
485 zlog::init_test();
486 cx.update(|cx| {
487 settings::init(cx);
488 });
489 let initial_text = "
490 one
491 two
492 three
493 four
494 five
495 "
496 .unindent();
497 let fs = FakeFs::new(executor);
498 fs.insert_tree(
499 path!("/project"),
500 json!({
501 ".git": {},
502 "a.txt": initial_text,
503 }),
504 )
505 .await;
506 let project = Project::test(fs.clone(), [path!("/project").as_ref()], cx).await;
507 let (git_store, buffer) = project.update(cx, |project, cx| {
508 (
509 project.git_store().clone(),
510 project.open_local_buffer(path!("/project/a.txt"), cx),
511 )
512 });
513 let buffer = buffer.await.unwrap();
514 let conflict_set = git_store.update(cx, |git_store, cx| {
515 git_store.open_conflict_set(buffer.clone(), cx)
516 });
517 let (events_tx, events_rx) = mpsc::channel::<ConflictSetUpdate>();
518 let _conflict_set_subscription = cx.update(|cx| {
519 cx.subscribe(&conflict_set, move |_, event, _| {
520 events_tx.send(event.clone()).ok();
521 })
522 });
523 let conflicts_snapshot =
524 conflict_set.read_with(cx, |conflict_set, _| conflict_set.snapshot());
525 assert!(conflicts_snapshot.conflicts.is_empty());
526
527 buffer.update(cx, |buffer, cx| {
528 buffer.edit(
529 [
530 (4..4, "<<<<<<< HEAD\n"),
531 (14..14, "=======\nTWO\n>>>>>>> branch\n"),
532 ],
533 None,
534 cx,
535 );
536 });
537
538 cx.run_until_parked();
539 events_rx.try_recv().expect_err(
540 "no conflicts should be registered as long as the file's status is unchanged",
541 );
542
543 fs.with_git_state(path!("/project/.git").as_ref(), true, |state| {
544 state.unmerged_paths.insert(
545 repo_path("a.txt"),
546 UnmergedStatus {
547 first_head: UnmergedStatusCode::Updated,
548 second_head: UnmergedStatusCode::Updated,
549 },
550 );
551 // Cause the repository to emit MergeHeadsChanged.
552 state.refs.insert("MERGE_HEAD".into(), "123".into())
553 })
554 .unwrap();
555
556 cx.run_until_parked();
557 let update = events_rx
558 .try_recv()
559 .expect("status change should trigger conflict parsing");
560 assert_eq!(update.old_range, 0..0);
561 assert_eq!(update.new_range, 0..1);
562
563 let conflict = conflict_set.read_with(cx, |conflict_set, _| {
564 conflict_set.snapshot().conflicts[0].clone()
565 });
566 cx.update(|cx| {
567 conflict.resolve(buffer.clone(), std::slice::from_ref(&conflict.theirs), cx);
568 });
569
570 cx.run_until_parked();
571 let update = events_rx
572 .try_recv()
573 .expect("conflicts should be removed after resolution");
574 assert_eq!(update.old_range, 0..1);
575 assert_eq!(update.new_range, 0..0);
576 }
577
578 #[gpui::test]
579 async fn test_conflict_updates_without_merge_head(
580 executor: BackgroundExecutor,
581 cx: &mut TestAppContext,
582 ) {
583 zlog::init_test();
584 cx.update(|cx| {
585 settings::init(cx);
586 });
587
588 let initial_text = "
589 zero
590 <<<<<<< HEAD
591 one
592 =======
593 two
594 >>>>>>> Stashed Changes
595 three
596 "
597 .unindent();
598
599 let fs = FakeFs::new(executor);
600 fs.insert_tree(
601 path!("/project"),
602 json!({
603 ".git": {},
604 "a.txt": initial_text,
605 }),
606 )
607 .await;
608
609 let project = Project::test(fs.clone(), [path!("/project").as_ref()], cx).await;
610 let (git_store, buffer) = project.update(cx, |project, cx| {
611 (
612 project.git_store().clone(),
613 project.open_local_buffer(path!("/project/a.txt"), cx),
614 )
615 });
616
617 cx.run_until_parked();
618 fs.with_git_state(path!("/project/.git").as_ref(), true, |state| {
619 state.unmerged_paths.insert(
620 RepoPath::from_rel_path(rel_path("a.txt")),
621 UnmergedStatus {
622 first_head: UnmergedStatusCode::Updated,
623 second_head: UnmergedStatusCode::Updated,
624 },
625 )
626 })
627 .unwrap();
628
629 let buffer = buffer.await.unwrap();
630
631 // Open the conflict set for a file that currently has conflicts.
632 let conflict_set = git_store.update(cx, |git_store, cx| {
633 git_store.open_conflict_set(buffer.clone(), cx)
634 });
635
636 cx.run_until_parked();
637 conflict_set.update(cx, |conflict_set, cx| {
638 let conflict_range = conflict_set.snapshot().conflicts[0]
639 .range
640 .to_point(buffer.read(cx));
641 assert_eq!(conflict_range, Point::new(1, 0)..Point::new(6, 0));
642 });
643
644 // Simulate the conflict being removed by e.g. staging the file.
645 fs.with_git_state(path!("/project/.git").as_ref(), true, |state| {
646 state.unmerged_paths.remove(&repo_path("a.txt"))
647 })
648 .unwrap();
649
650 cx.run_until_parked();
651 conflict_set.update(cx, |conflict_set, _| {
652 assert!(!conflict_set.has_conflict);
653 assert_eq!(conflict_set.snapshot.conflicts.len(), 0);
654 });
655
656 // Simulate the conflict being re-added.
657 fs.with_git_state(path!("/project/.git").as_ref(), true, |state| {
658 state.unmerged_paths.insert(
659 repo_path("a.txt"),
660 UnmergedStatus {
661 first_head: UnmergedStatusCode::Updated,
662 second_head: UnmergedStatusCode::Updated,
663 },
664 )
665 })
666 .unwrap();
667
668 cx.run_until_parked();
669 conflict_set.update(cx, |conflict_set, cx| {
670 let conflict_range = conflict_set.snapshot().conflicts[0]
671 .range
672 .to_point(buffer.read(cx));
673 assert_eq!(conflict_range, Point::new(1, 0)..Point::new(6, 0));
674 });
675 }
676}