git_graph.rs

   1use collections::{BTreeMap, HashMap};
   2use git::{
   3    BuildCommitPermalinkParams, GitHostingProviderRegistry, GitRemote, Oid, ParsedGitRemote,
   4    parse_git_remote_url,
   5    repository::{CommitDiff, InitialGraphCommitData, LogOrder, LogSource},
   6};
   7use git_ui::commit_tooltip::CommitAvatar;
   8use gpui::{
   9    AnyElement, App, Bounds, ClipboardItem, Context, Corner, DefiniteLength, ElementId, Entity,
  10    EventEmitter, FocusHandle, Focusable, FontWeight, Hsla, InteractiveElement, ParentElement,
  11    PathBuilder, Pixels, Point, Render, ScrollWheelEvent, SharedString, Styled, Subscription, Task,
  12    WeakEntity, Window, actions, anchored, deferred, point, px,
  13};
  14use project::{
  15    Project,
  16    git_store::{CommitDataState, GitStoreEvent, Repository, RepositoryEvent},
  17};
  18use settings::Settings;
  19use smallvec::{SmallVec, smallvec};
  20use std::{ops::Range, rc::Rc, sync::Arc, sync::OnceLock};
  21use theme::{AccentColors, ThemeSettings};
  22use time::{OffsetDateTime, UtcOffset, format_description::BorrowedFormatItem};
  23use ui::{
  24    CommonAnimationExt as _, ContextMenu, ScrollableHandle, Table, TableInteractionState, Tooltip,
  25    prelude::*,
  26};
  27use workspace::{
  28    Workspace,
  29    item::{Item, ItemEvent, SerializableItem},
  30};
  31
  32const COMMIT_CIRCLE_RADIUS: Pixels = px(4.5);
  33const COMMIT_CIRCLE_STROKE_WIDTH: Pixels = px(1.5);
  34const LANE_WIDTH: Pixels = px(16.0);
  35const LEFT_PADDING: Pixels = px(12.0);
  36const LINE_WIDTH: Pixels = px(1.5);
  37
  38actions!(
  39    git_graph,
  40    [
  41        /// Opens the Git Graph panel.
  42        Open,
  43        /// Opens the commit view for the selected commit.
  44        OpenCommitView,
  45    ]
  46);
  47
  48fn timestamp_format() -> &'static [BorrowedFormatItem<'static>] {
  49    static FORMAT: OnceLock<Vec<BorrowedFormatItem<'static>>> = OnceLock::new();
  50    FORMAT.get_or_init(|| {
  51        time::format_description::parse("[day] [month repr:short] [year] [hour]:[minute]")
  52            .unwrap_or_default()
  53    })
  54}
  55
  56fn format_timestamp(timestamp: i64) -> String {
  57    let Ok(datetime) = OffsetDateTime::from_unix_timestamp(timestamp) else {
  58        return "Unknown".to_string();
  59    };
  60
  61    let local_offset = UtcOffset::current_local_offset().unwrap_or(UtcOffset::UTC);
  62    let local_datetime = datetime.to_offset(local_offset);
  63
  64    local_datetime
  65        .format(timestamp_format())
  66        .unwrap_or_default()
  67}
  68
  69fn accent_colors_count(accents: &AccentColors) -> usize {
  70    accents.0.len()
  71}
  72
  73#[derive(Copy, Clone, Debug)]
  74struct BranchColor(u8);
  75
  76#[derive(Debug)]
  77enum LaneState {
  78    Empty,
  79    Active {
  80        child: Oid,
  81        parent: Oid,
  82        color: Option<BranchColor>,
  83        starting_row: usize,
  84        starting_col: usize,
  85        destination_column: Option<usize>,
  86        segments: SmallVec<[CommitLineSegment; 1]>,
  87    },
  88}
  89
  90impl LaneState {
  91    fn to_commit_lines(
  92        &mut self,
  93        ending_row: usize,
  94        lane_column: usize,
  95        parent_column: usize,
  96        parent_color: BranchColor,
  97    ) -> Option<CommitLine> {
  98        let state = std::mem::replace(self, LaneState::Empty);
  99
 100        match state {
 101            LaneState::Active {
 102                #[cfg_attr(not(test), allow(unused_variables))]
 103                parent,
 104                #[cfg_attr(not(test), allow(unused_variables))]
 105                child,
 106                color,
 107                starting_row,
 108                starting_col,
 109                destination_column,
 110                mut segments,
 111            } => {
 112                let final_destination = destination_column.unwrap_or(parent_column);
 113                let final_color = color.unwrap_or(parent_color);
 114
 115                Some(CommitLine {
 116                    #[cfg(test)]
 117                    child,
 118                    #[cfg(test)]
 119                    parent,
 120                    child_column: starting_col,
 121                    full_interval: starting_row..ending_row,
 122                    color_idx: final_color.0 as usize,
 123                    segments: {
 124                        match segments.last_mut() {
 125                            Some(CommitLineSegment::Straight { to_row })
 126                                if *to_row == usize::MAX =>
 127                            {
 128                                if final_destination != lane_column {
 129                                    *to_row = ending_row - 1;
 130
 131                                    let curved_line = CommitLineSegment::Curve {
 132                                        to_column: final_destination,
 133                                        on_row: ending_row,
 134                                        curve_kind: CurveKind::Checkout,
 135                                    };
 136
 137                                    if *to_row == starting_row {
 138                                        let last_index = segments.len() - 1;
 139                                        segments[last_index] = curved_line;
 140                                    } else {
 141                                        segments.push(curved_line);
 142                                    }
 143                                } else {
 144                                    *to_row = ending_row;
 145                                }
 146                            }
 147                            Some(CommitLineSegment::Curve {
 148                                on_row,
 149                                to_column,
 150                                curve_kind,
 151                            }) if *on_row == usize::MAX => {
 152                                if *to_column == usize::MAX {
 153                                    *to_column = final_destination;
 154                                }
 155                                if matches!(curve_kind, CurveKind::Merge) {
 156                                    *on_row = starting_row + 1;
 157                                    if *on_row < ending_row {
 158                                        if *to_column != final_destination {
 159                                            segments.push(CommitLineSegment::Straight {
 160                                                to_row: ending_row - 1,
 161                                            });
 162                                            segments.push(CommitLineSegment::Curve {
 163                                                to_column: final_destination,
 164                                                on_row: ending_row,
 165                                                curve_kind: CurveKind::Checkout,
 166                                            });
 167                                        } else {
 168                                            segments.push(CommitLineSegment::Straight {
 169                                                to_row: ending_row,
 170                                            });
 171                                        }
 172                                    } else if *to_column != final_destination {
 173                                        segments.push(CommitLineSegment::Curve {
 174                                            to_column: final_destination,
 175                                            on_row: ending_row,
 176                                            curve_kind: CurveKind::Checkout,
 177                                        });
 178                                    }
 179                                } else {
 180                                    *on_row = ending_row;
 181                                    if *to_column != final_destination {
 182                                        segments.push(CommitLineSegment::Straight {
 183                                            to_row: ending_row,
 184                                        });
 185                                        segments.push(CommitLineSegment::Curve {
 186                                            to_column: final_destination,
 187                                            on_row: ending_row,
 188                                            curve_kind: CurveKind::Checkout,
 189                                        });
 190                                    }
 191                                }
 192                            }
 193                            Some(CommitLineSegment::Curve {
 194                                on_row, to_column, ..
 195                            }) => {
 196                                if *on_row < ending_row {
 197                                    if *to_column != final_destination {
 198                                        segments.push(CommitLineSegment::Straight {
 199                                            to_row: ending_row - 1,
 200                                        });
 201                                        segments.push(CommitLineSegment::Curve {
 202                                            to_column: final_destination,
 203                                            on_row: ending_row,
 204                                            curve_kind: CurveKind::Checkout,
 205                                        });
 206                                    } else {
 207                                        segments.push(CommitLineSegment::Straight {
 208                                            to_row: ending_row,
 209                                        });
 210                                    }
 211                                } else if *to_column != final_destination {
 212                                    segments.push(CommitLineSegment::Curve {
 213                                        to_column: final_destination,
 214                                        on_row: ending_row,
 215                                        curve_kind: CurveKind::Checkout,
 216                                    });
 217                                }
 218                            }
 219                            _ => {}
 220                        }
 221
 222                        segments
 223                    },
 224                })
 225            }
 226            LaneState::Empty => None,
 227        }
 228    }
 229
 230    fn is_empty(&self) -> bool {
 231        match self {
 232            LaneState::Empty => true,
 233            LaneState::Active { .. } => false,
 234        }
 235    }
 236}
 237
 238struct CommitEntry {
 239    data: Arc<InitialGraphCommitData>,
 240    lane: usize,
 241    color_idx: usize,
 242}
 243
 244type ActiveLaneIdx = usize;
 245
 246enum AllCommitCount {
 247    NotLoaded,
 248    Loaded(usize),
 249}
 250
 251#[derive(Debug)]
 252enum CurveKind {
 253    Merge,
 254    Checkout,
 255}
 256
 257#[derive(Debug)]
 258enum CommitLineSegment {
 259    Straight {
 260        to_row: usize,
 261    },
 262    Curve {
 263        to_column: usize,
 264        on_row: usize,
 265        curve_kind: CurveKind,
 266    },
 267}
 268
 269#[derive(Debug)]
 270struct CommitLine {
 271    #[cfg(test)]
 272    child: Oid,
 273    #[cfg(test)]
 274    parent: Oid,
 275    child_column: usize,
 276    full_interval: Range<usize>,
 277    color_idx: usize,
 278    segments: SmallVec<[CommitLineSegment; 1]>,
 279}
 280
 281impl CommitLine {
 282    fn get_first_visible_segment_idx(&self, first_visible_row: usize) -> Option<(usize, usize)> {
 283        if first_visible_row > self.full_interval.end {
 284            return None;
 285        } else if first_visible_row <= self.full_interval.start {
 286            return Some((0, self.child_column));
 287        }
 288
 289        let mut current_column = self.child_column;
 290
 291        for (idx, segment) in self.segments.iter().enumerate() {
 292            match segment {
 293                CommitLineSegment::Straight { to_row } => {
 294                    if *to_row >= first_visible_row {
 295                        return Some((idx, current_column));
 296                    }
 297                }
 298                CommitLineSegment::Curve {
 299                    to_column, on_row, ..
 300                } => {
 301                    if *on_row >= first_visible_row {
 302                        return Some((idx, current_column));
 303                    }
 304                    current_column = *to_column;
 305                }
 306            }
 307        }
 308
 309        None
 310    }
 311}
 312
 313#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
 314struct CommitLineKey {
 315    child: Oid,
 316    parent: Oid,
 317}
 318
 319struct GraphData {
 320    lane_states: SmallVec<[LaneState; 8]>,
 321    lane_colors: HashMap<ActiveLaneIdx, BranchColor>,
 322    parent_to_lanes: HashMap<Oid, SmallVec<[usize; 1]>>,
 323    next_color: BranchColor,
 324    accent_colors_count: usize,
 325    commits: Vec<Rc<CommitEntry>>,
 326    max_commit_count: AllCommitCount,
 327    max_lanes: usize,
 328    lines: Vec<Rc<CommitLine>>,
 329    active_commit_lines: HashMap<CommitLineKey, usize>,
 330    active_commit_lines_by_parent: HashMap<Oid, SmallVec<[usize; 1]>>,
 331}
 332
 333impl GraphData {
 334    fn new(accent_colors_count: usize) -> Self {
 335        GraphData {
 336            lane_states: SmallVec::default(),
 337            lane_colors: HashMap::default(),
 338            parent_to_lanes: HashMap::default(),
 339            next_color: BranchColor(0),
 340            accent_colors_count,
 341            commits: Vec::default(),
 342            max_commit_count: AllCommitCount::NotLoaded,
 343            max_lanes: 0,
 344            lines: Vec::default(),
 345            active_commit_lines: HashMap::default(),
 346            active_commit_lines_by_parent: HashMap::default(),
 347        }
 348    }
 349
 350    fn clear(&mut self) {
 351        self.lane_states.clear();
 352        self.lane_colors.clear();
 353        self.parent_to_lanes.clear();
 354        self.commits.clear();
 355        self.lines.clear();
 356        self.active_commit_lines.clear();
 357        self.active_commit_lines_by_parent.clear();
 358        self.next_color = BranchColor(0);
 359        self.max_commit_count = AllCommitCount::NotLoaded;
 360        self.max_lanes = 0;
 361    }
 362
 363    fn first_empty_lane_idx(&mut self) -> ActiveLaneIdx {
 364        self.lane_states
 365            .iter()
 366            .position(LaneState::is_empty)
 367            .unwrap_or_else(|| {
 368                self.lane_states.push(LaneState::Empty);
 369                self.lane_states.len() - 1
 370            })
 371    }
 372
 373    fn get_lane_color(&mut self, lane_idx: ActiveLaneIdx) -> BranchColor {
 374        let accent_colors_count = self.accent_colors_count;
 375        *self.lane_colors.entry(lane_idx).or_insert_with(|| {
 376            let color_idx = self.next_color;
 377            self.next_color = BranchColor((self.next_color.0 + 1) % accent_colors_count as u8);
 378            color_idx
 379        })
 380    }
 381
 382    fn add_commits(&mut self, commits: &[Arc<InitialGraphCommitData>]) {
 383        self.commits.reserve(commits.len());
 384        self.lines.reserve(commits.len() / 2);
 385
 386        for commit in commits.iter() {
 387            let commit_row = self.commits.len();
 388
 389            let commit_lane = self
 390                .parent_to_lanes
 391                .get(&commit.sha)
 392                .and_then(|lanes| lanes.first().copied());
 393
 394            let commit_lane = commit_lane.unwrap_or_else(|| self.first_empty_lane_idx());
 395
 396            let commit_color = self.get_lane_color(commit_lane);
 397
 398            if let Some(lanes) = self.parent_to_lanes.remove(&commit.sha) {
 399                for lane_column in lanes {
 400                    let state = &mut self.lane_states[lane_column];
 401
 402                    if let LaneState::Active {
 403                        starting_row,
 404                        segments,
 405                        ..
 406                    } = state
 407                    {
 408                        if let Some(CommitLineSegment::Curve {
 409                            to_column,
 410                            curve_kind: CurveKind::Merge,
 411                            ..
 412                        }) = segments.first_mut()
 413                        {
 414                            let curve_row = *starting_row + 1;
 415                            let would_overlap =
 416                                if lane_column != commit_lane && curve_row < commit_row {
 417                                    self.commits[curve_row..commit_row]
 418                                        .iter()
 419                                        .any(|c| c.lane == commit_lane)
 420                                } else {
 421                                    false
 422                                };
 423
 424                            if would_overlap {
 425                                *to_column = lane_column;
 426                            }
 427                        }
 428                    }
 429
 430                    if let Some(commit_line) =
 431                        state.to_commit_lines(commit_row, lane_column, commit_lane, commit_color)
 432                    {
 433                        self.lines.push(Rc::new(commit_line));
 434                    }
 435                }
 436            }
 437
 438            commit
 439                .parents
 440                .iter()
 441                .enumerate()
 442                .for_each(|(parent_idx, parent)| {
 443                    if parent_idx == 0 {
 444                        self.lane_states[commit_lane] = LaneState::Active {
 445                            parent: *parent,
 446                            child: commit.sha,
 447                            color: Some(commit_color),
 448                            starting_col: commit_lane,
 449                            starting_row: commit_row,
 450                            destination_column: None,
 451                            segments: smallvec![CommitLineSegment::Straight { to_row: usize::MAX }],
 452                        };
 453
 454                        self.parent_to_lanes
 455                            .entry(*parent)
 456                            .or_default()
 457                            .push(commit_lane);
 458                    } else {
 459                        let new_lane = self.first_empty_lane_idx();
 460
 461                        self.lane_states[new_lane] = LaneState::Active {
 462                            parent: *parent,
 463                            child: commit.sha,
 464                            color: None,
 465                            starting_col: commit_lane,
 466                            starting_row: commit_row,
 467                            destination_column: None,
 468                            segments: smallvec![CommitLineSegment::Curve {
 469                                to_column: usize::MAX,
 470                                on_row: usize::MAX,
 471                                curve_kind: CurveKind::Merge,
 472                            },],
 473                        };
 474
 475                        self.parent_to_lanes
 476                            .entry(*parent)
 477                            .or_default()
 478                            .push(new_lane);
 479                    }
 480                });
 481
 482            self.max_lanes = self.max_lanes.max(self.lane_states.len());
 483
 484            self.commits.push(Rc::new(CommitEntry {
 485                data: commit.clone(),
 486                lane: commit_lane,
 487                color_idx: commit_color.0 as usize,
 488            }));
 489        }
 490    }
 491}
 492
 493pub fn init(cx: &mut App) {
 494    workspace::register_serializable_item::<GitGraph>(cx);
 495
 496    cx.observe_new(|workspace: &mut workspace::Workspace, _, _| {
 497        workspace.register_action_renderer(|div, workspace, _, cx| {
 498            div.when(
 499                workspace.project().read(cx).active_repository(cx).is_some(),
 500                |div| {
 501                    let workspace = workspace.weak_handle();
 502
 503                    div.on_action(move |_: &Open, window, cx| {
 504                        workspace
 505                            .update(cx, |workspace, cx| {
 506                                let project = workspace.project().clone();
 507                                let git_graph = cx.new(|cx| GitGraph::new(project, window, cx));
 508                                workspace.add_item_to_active_pane(
 509                                    Box::new(git_graph),
 510                                    None,
 511                                    true,
 512                                    window,
 513                                    cx,
 514                                );
 515                            })
 516                            .ok();
 517                    })
 518                },
 519            )
 520        });
 521    })
 522    .detach();
 523}
 524
 525fn lane_center_x(bounds: Bounds<Pixels>, lane: f32, horizontal_scroll_offset: Pixels) -> Pixels {
 526    bounds.origin.x + LEFT_PADDING + lane * LANE_WIDTH + LANE_WIDTH / 2.0 - horizontal_scroll_offset
 527}
 528
 529fn to_row_center(
 530    to_row: usize,
 531    row_height: Pixels,
 532    scroll_offset: Pixels,
 533    bounds: Bounds<Pixels>,
 534) -> Pixels {
 535    bounds.origin.y + to_row as f32 * row_height + row_height / 2.0 - scroll_offset
 536}
 537
 538fn draw_commit_circle(center_x: Pixels, center_y: Pixels, color: Hsla, window: &mut Window) {
 539    let radius = COMMIT_CIRCLE_RADIUS;
 540    let stroke_width = COMMIT_CIRCLE_STROKE_WIDTH;
 541
 542    let mut builder = PathBuilder::stroke(stroke_width);
 543
 544    // Start at the rightmost point of the circle
 545    builder.move_to(point(center_x + radius, center_y));
 546
 547    // Draw the circle using two arc_to calls (top half, then bottom half)
 548    builder.arc_to(
 549        point(radius, radius),
 550        px(0.),
 551        false,
 552        true,
 553        point(center_x - radius, center_y),
 554    );
 555    builder.arc_to(
 556        point(radius, radius),
 557        px(0.),
 558        false,
 559        true,
 560        point(center_x + radius, center_y),
 561    );
 562    builder.close();
 563
 564    if let Ok(path) = builder.build() {
 565        window.paint_path(path, color);
 566    }
 567}
 568
 569pub struct GitGraph {
 570    focus_handle: FocusHandle,
 571    graph_data: GraphData,
 572    project: Entity<Project>,
 573    context_menu: Option<(Entity<ContextMenu>, Point<Pixels>, Subscription)>,
 574    row_height: Pixels,
 575    table_interaction_state: Entity<TableInteractionState>,
 576    horizontal_scroll_offset: Pixels,
 577    graph_viewport_width: Pixels,
 578    selected_entry_idx: Option<usize>,
 579    log_source: LogSource,
 580    log_order: LogOrder,
 581    selected_commit_diff: Option<CommitDiff>,
 582    _commit_diff_task: Option<Task<()>>,
 583    _load_task: Option<Task<()>>,
 584}
 585
 586impl GitGraph {
 587    fn row_height(cx: &App) -> Pixels {
 588        let settings = ThemeSettings::get_global(cx);
 589        let font_size = settings.buffer_font_size(cx);
 590        font_size + px(12.0)
 591    }
 592
 593    fn graph_content_width(&self) -> Pixels {
 594        (LANE_WIDTH * self.graph_data.max_lanes.min(8) as f32) + LEFT_PADDING * 2.0
 595    }
 596
 597    pub fn new(project: Entity<Project>, window: &mut Window, cx: &mut Context<Self>) -> Self {
 598        let focus_handle = cx.focus_handle();
 599        cx.on_focus(&focus_handle, window, |_, _, cx| cx.notify())
 600            .detach();
 601
 602        let git_store = project.read(cx).git_store().clone();
 603        let accent_colors = cx.theme().accents();
 604        let mut graph = GraphData::new(accent_colors_count(accent_colors));
 605        let log_source = LogSource::default();
 606        let log_order = LogOrder::default();
 607
 608        cx.subscribe(&git_store, |this, _, event, cx| match event {
 609            GitStoreEvent::RepositoryUpdated(_, repo_event, is_active) => {
 610                if *is_active {
 611                    if let Some(repository) = this.project.read(cx).active_repository(cx) {
 612                        this.on_repository_event(repository, repo_event, cx);
 613                    }
 614                }
 615            }
 616            GitStoreEvent::ActiveRepositoryChanged(_) => {
 617                this.graph_data.clear();
 618                cx.notify();
 619            }
 620            _ => {}
 621        })
 622        .detach();
 623
 624        if let Some(repository) = project.read(cx).active_repository(cx) {
 625            repository.update(cx, |repository, cx| {
 626                // This won't overlap with loading commits from the repository because
 627                // we either have all commits or commits loaded in chunks and loading commits
 628                // from the repository event is always adding the last chunk of commits.
 629                let (commits, _) =
 630                    repository.graph_data(log_source.clone(), log_order, 0..usize::MAX, cx);
 631                graph.add_commits(commits);
 632            });
 633        }
 634
 635        let table_interaction_state = cx.new(|cx| TableInteractionState::new(cx));
 636        let mut row_height = Self::row_height(cx);
 637
 638        cx.observe_global_in::<settings::SettingsStore>(window, move |this, _window, cx| {
 639            let new_row_height = Self::row_height(cx);
 640            if new_row_height != row_height {
 641                this.row_height = new_row_height;
 642                this.table_interaction_state.update(cx, |state, _cx| {
 643                    state.scroll_handle.0.borrow_mut().last_item_size = None;
 644                });
 645                row_height = new_row_height;
 646            }
 647            cx.notify();
 648        })
 649        .detach();
 650
 651        GitGraph {
 652            focus_handle,
 653            project,
 654            graph_data: graph,
 655            _load_task: None,
 656            _commit_diff_task: None,
 657            context_menu: None,
 658            row_height,
 659            table_interaction_state,
 660            horizontal_scroll_offset: px(0.),
 661            graph_viewport_width: px(88.),
 662            selected_entry_idx: None,
 663            selected_commit_diff: None,
 664            log_source,
 665            log_order,
 666        }
 667    }
 668
 669    fn on_repository_event(
 670        &mut self,
 671        repository: Entity<Repository>,
 672        event: &RepositoryEvent,
 673        cx: &mut Context<Self>,
 674    ) {
 675        match event {
 676            RepositoryEvent::GitGraphCountUpdated(_, commit_count) => {
 677                let old_count = self.graph_data.commits.len();
 678
 679                repository.update(cx, |repository, cx| {
 680                    let (commits, _) = repository.graph_data(
 681                        self.log_source.clone(),
 682                        self.log_order,
 683                        old_count..*commit_count,
 684                        cx,
 685                    );
 686                    self.graph_data.add_commits(commits);
 687                });
 688
 689                self.graph_data.max_commit_count = AllCommitCount::Loaded(*commit_count);
 690            }
 691            RepositoryEvent::BranchChanged => {
 692                self.graph_data.clear();
 693                cx.notify();
 694            }
 695            _ => {}
 696        }
 697
 698        cx.notify();
 699    }
 700
 701    fn render_badge(&self, name: &SharedString, accent_color: gpui::Hsla) -> impl IntoElement {
 702        div()
 703            .px_1p5()
 704            .py_0p5()
 705            .h(self.row_height - px(4.0))
 706            .flex()
 707            .items_center()
 708            .justify_center()
 709            .rounded_md()
 710            .bg(accent_color.opacity(0.18))
 711            .border_1()
 712            .border_color(accent_color.opacity(0.55))
 713            .child(
 714                Label::new(name.clone())
 715                    .size(LabelSize::Small)
 716                    .color(Color::Default)
 717                    .single_line(),
 718            )
 719    }
 720
 721    fn render_table_rows(
 722        &mut self,
 723        range: Range<usize>,
 724        _window: &mut Window,
 725        cx: &mut Context<Self>,
 726    ) -> Vec<Vec<AnyElement>> {
 727        let repository = self
 728            .project
 729            .read_with(cx, |project, cx| project.active_repository(cx));
 730
 731        let row_height = self.row_height;
 732
 733        // We fetch data outside the visible viewport to avoid loading entries when
 734        // users scroll through the git graph
 735        if let Some(repository) = repository.as_ref() {
 736            const FETCH_RANGE: usize = 100;
 737            repository.update(cx, |repository, cx| {
 738                self.graph_data.commits[range.start.saturating_sub(FETCH_RANGE)
 739                    ..(range.end + FETCH_RANGE)
 740                        .min(self.graph_data.commits.len().saturating_sub(1))]
 741                    .iter()
 742                    .for_each(|commit| {
 743                        repository.fetch_commit_data(commit.data.sha, cx);
 744                    });
 745            });
 746        }
 747
 748        range
 749            .map(|idx| {
 750                let Some((commit, repository)) =
 751                    self.graph_data.commits.get(idx).zip(repository.as_ref())
 752                else {
 753                    return vec![
 754                        div().h(row_height).into_any_element(),
 755                        div().h(row_height).into_any_element(),
 756                        div().h(row_height).into_any_element(),
 757                        div().h(row_height).into_any_element(),
 758                    ];
 759                };
 760
 761                let data = repository.update(cx, |repository, cx| {
 762                    repository.fetch_commit_data(commit.data.sha, cx).clone()
 763                });
 764
 765                let short_sha = commit.data.sha.display_short();
 766                let mut formatted_time = String::new();
 767                let subject;
 768                let author_name;
 769
 770                if let CommitDataState::Loaded(data) = data {
 771                    subject = data.subject.clone();
 772                    author_name = data.author_name.clone();
 773                    formatted_time = format_timestamp(data.commit_timestamp);
 774                } else {
 775                    subject = "Loading...".into();
 776                    author_name = "".into();
 777                }
 778
 779                let accent_colors = cx.theme().accents();
 780                let accent_color = accent_colors
 781                    .0
 782                    .get(commit.color_idx)
 783                    .copied()
 784                    .unwrap_or_else(|| accent_colors.0.first().copied().unwrap_or_default());
 785                let is_selected = self.selected_entry_idx == Some(idx);
 786                let text_color = if is_selected {
 787                    Color::Default
 788                } else {
 789                    Color::Muted
 790                };
 791
 792                vec![
 793                    div()
 794                        .id(ElementId::NamedInteger("commit-subject".into(), idx as u64))
 795                        .overflow_hidden()
 796                        .tooltip(Tooltip::text(subject.clone()))
 797                        .child(
 798                            h_flex()
 799                                .gap_1()
 800                                .items_center()
 801                                .overflow_hidden()
 802                                .children((!commit.data.ref_names.is_empty()).then(|| {
 803                                    h_flex().flex_shrink().gap_2().items_center().children(
 804                                        commit
 805                                            .data
 806                                            .ref_names
 807                                            .iter()
 808                                            .map(|name| self.render_badge(name, accent_color)),
 809                                    )
 810                                }))
 811                                .child(
 812                                    Label::new(subject)
 813                                        .color(text_color)
 814                                        .truncate()
 815                                        .single_line(),
 816                                ),
 817                        )
 818                        .into_any_element(),
 819                    Label::new(formatted_time)
 820                        .color(text_color)
 821                        .single_line()
 822                        .into_any_element(),
 823                    Label::new(author_name)
 824                        .color(text_color)
 825                        .single_line()
 826                        .into_any_element(),
 827                    Label::new(short_sha)
 828                        .color(text_color)
 829                        .single_line()
 830                        .into_any_element(),
 831                ]
 832            })
 833            .collect()
 834    }
 835
 836    fn select_entry(&mut self, idx: usize, cx: &mut Context<Self>) {
 837        if self.selected_entry_idx == Some(idx) {
 838            return;
 839        }
 840
 841        self.selected_entry_idx = Some(idx);
 842        self.selected_commit_diff = None;
 843
 844        let Some(commit) = self.graph_data.commits.get(idx) else {
 845            return;
 846        };
 847
 848        let sha = commit.data.sha.to_string();
 849        let repository = self
 850            .project
 851            .read_with(cx, |project, cx| project.active_repository(cx));
 852
 853        let Some(repository) = repository else {
 854            return;
 855        };
 856
 857        let diff_receiver = repository.update(cx, |repo, _| repo.load_commit_diff(sha));
 858
 859        self._commit_diff_task = Some(cx.spawn(async move |this, cx| {
 860            if let Ok(Ok(diff)) = diff_receiver.await {
 861                this.update(cx, |this, cx| {
 862                    this.selected_commit_diff = Some(diff);
 863                    cx.notify();
 864                })
 865                .ok();
 866            }
 867        }));
 868
 869        cx.notify();
 870    }
 871
 872    fn get_remote(
 873        &self,
 874        repository: &Repository,
 875        _window: &mut Window,
 876        cx: &mut App,
 877    ) -> Option<GitRemote> {
 878        let remote_url = repository.default_remote_url()?;
 879        let provider_registry = GitHostingProviderRegistry::default_global(cx);
 880        let (provider, parsed) = parse_git_remote_url(provider_registry, &remote_url)?;
 881        Some(GitRemote {
 882            host: provider,
 883            owner: parsed.owner.into(),
 884            repo: parsed.repo.into(),
 885        })
 886    }
 887
 888    fn render_loading_spinner(&self, cx: &App) -> AnyElement {
 889        let rems = TextSize::Large.rems(cx);
 890        Icon::new(IconName::LoadCircle)
 891            .size(IconSize::Custom(rems))
 892            .color(Color::Accent)
 893            .with_rotate_animation(3)
 894            .into_any_element()
 895    }
 896
 897    fn render_commit_detail_panel(
 898        &self,
 899        window: &mut Window,
 900        cx: &mut Context<Self>,
 901    ) -> impl IntoElement {
 902        let Some(selected_idx) = self.selected_entry_idx else {
 903            return div().into_any_element();
 904        };
 905
 906        let Some(commit_entry) = self.graph_data.commits.get(selected_idx) else {
 907            return div().into_any_element();
 908        };
 909
 910        let repository = self
 911            .project
 912            .read_with(cx, |project, cx| project.active_repository(cx));
 913
 914        let Some(repository) = repository else {
 915            return div().into_any_element();
 916        };
 917
 918        let data = repository.update(cx, |repository, cx| {
 919            repository
 920                .fetch_commit_data(commit_entry.data.sha, cx)
 921                .clone()
 922        });
 923
 924        let full_sha: SharedString = commit_entry.data.sha.to_string().into();
 925        let truncated_sha: SharedString = {
 926            let sha_str = full_sha.as_ref();
 927            if sha_str.len() > 24 {
 928                format!("{}...", &sha_str[..24]).into()
 929            } else {
 930                full_sha.clone()
 931            }
 932        };
 933        let ref_names = commit_entry.data.ref_names.clone();
 934        let accent_colors = cx.theme().accents();
 935        let accent_color = accent_colors
 936            .0
 937            .get(commit_entry.color_idx)
 938            .copied()
 939            .unwrap_or_else(|| accent_colors.0.first().copied().unwrap_or_default());
 940
 941        let (author_name, author_email, commit_timestamp, subject) = match &data {
 942            CommitDataState::Loaded(data) => (
 943                data.author_name.clone(),
 944                data.author_email.clone(),
 945                Some(data.commit_timestamp),
 946                data.subject.clone(),
 947            ),
 948            CommitDataState::Loading => ("Loading...".into(), "".into(), None, "Loading...".into()),
 949        };
 950
 951        let date_string = commit_timestamp
 952            .and_then(|ts| OffsetDateTime::from_unix_timestamp(ts).ok())
 953            .map(|datetime| {
 954                let local_offset = UtcOffset::current_local_offset().unwrap_or(UtcOffset::UTC);
 955                let local_datetime = datetime.to_offset(local_offset);
 956                let format =
 957                    time::format_description::parse("[month repr:short] [day], [year]").ok();
 958                format
 959                    .and_then(|f| local_datetime.format(&f).ok())
 960                    .unwrap_or_default()
 961            })
 962            .unwrap_or_default();
 963
 964        let remote = repository.update(cx, |repo, cx| self.get_remote(repo, window, cx));
 965
 966        let avatar = {
 967            let avatar = CommitAvatar::new(&full_sha, remote.as_ref());
 968            v_flex()
 969                .w(px(64.))
 970                .h(px(64.))
 971                .border_1()
 972                .border_color(cx.theme().colors().border)
 973                .rounded_full()
 974                .justify_center()
 975                .items_center()
 976                .child(
 977                    avatar
 978                        .avatar(window, cx)
 979                        .map(|a| a.size(px(64.)).into_any_element())
 980                        .unwrap_or_else(|| {
 981                            Icon::new(IconName::Person)
 982                                .color(Color::Muted)
 983                                .size(IconSize::XLarge)
 984                                .into_any_element()
 985                        }),
 986                )
 987        };
 988
 989        let changed_files_count = self
 990            .selected_commit_diff
 991            .as_ref()
 992            .map(|diff| diff.files.len())
 993            .unwrap_or(0);
 994
 995        v_flex()
 996            .w(px(300.))
 997            .h_full()
 998            .border_l_1()
 999            .border_color(cx.theme().colors().border)
1000            .bg(cx.theme().colors().surface_background)
1001            .child(
1002                v_flex()
1003                    .p_3()
1004                    .gap_3()
1005                    .child(
1006                        h_flex().justify_between().child(avatar).child(
1007                            IconButton::new("close-detail", IconName::Close)
1008                                .icon_size(IconSize::Small)
1009                                .on_click(cx.listener(move |this, _, _, cx| {
1010                                    this.selected_entry_idx = None;
1011                                    this.selected_commit_diff = None;
1012                                    this._commit_diff_task = None;
1013                                    cx.notify();
1014                                })),
1015                        ),
1016                    )
1017                    .child(
1018                        v_flex()
1019                            .gap_0p5()
1020                            .child(Label::new(author_name.clone()).weight(FontWeight::SEMIBOLD))
1021                            .child(
1022                                Label::new(date_string)
1023                                    .color(Color::Muted)
1024                                    .size(LabelSize::Small),
1025                            ),
1026                    )
1027                    .children((!ref_names.is_empty()).then(|| {
1028                        h_flex().gap_1().flex_wrap().children(
1029                            ref_names
1030                                .iter()
1031                                .map(|name| self.render_badge(name, accent_color)),
1032                        )
1033                    }))
1034                    .child(
1035                        v_flex()
1036                            .gap_1p5()
1037                            .child(
1038                                h_flex()
1039                                    .gap_1()
1040                                    .child(
1041                                        Icon::new(IconName::Person)
1042                                            .size(IconSize::Small)
1043                                            .color(Color::Muted),
1044                                    )
1045                                    .child(
1046                                        Label::new(author_name)
1047                                            .size(LabelSize::Small)
1048                                            .color(Color::Muted),
1049                                    )
1050                                    .when(!author_email.is_empty(), |this| {
1051                                        this.child(
1052                                            Label::new(format!("<{}>", author_email))
1053                                                .size(LabelSize::Small)
1054                                                .color(Color::Ignored),
1055                                        )
1056                                    }),
1057                            )
1058                            .child(
1059                                h_flex()
1060                                    .gap_1()
1061                                    .child(
1062                                        Icon::new(IconName::Hash)
1063                                            .size(IconSize::Small)
1064                                            .color(Color::Muted),
1065                                    )
1066                                    .child({
1067                                        let copy_sha = full_sha.clone();
1068                                        Button::new("sha-button", truncated_sha)
1069                                            .style(ButtonStyle::Transparent)
1070                                            .label_size(LabelSize::Small)
1071                                            .color(Color::Muted)
1072                                            .tooltip(Tooltip::text(format!(
1073                                                "Copy SHA: {}",
1074                                                copy_sha
1075                                            )))
1076                                            .on_click(move |_, _, cx| {
1077                                                cx.write_to_clipboard(ClipboardItem::new_string(
1078                                                    copy_sha.to_string(),
1079                                                ));
1080                                            })
1081                                    }),
1082                            )
1083                            .when_some(remote.clone(), |this, remote| {
1084                                let provider_name = remote.host.name();
1085                                let icon = match provider_name.as_str() {
1086                                    "GitHub" => IconName::Github,
1087                                    _ => IconName::Link,
1088                                };
1089                                let parsed_remote = ParsedGitRemote {
1090                                    owner: remote.owner.as_ref().into(),
1091                                    repo: remote.repo.as_ref().into(),
1092                                };
1093                                let params = BuildCommitPermalinkParams {
1094                                    sha: full_sha.as_ref(),
1095                                };
1096                                let url = remote
1097                                    .host
1098                                    .build_commit_permalink(&parsed_remote, params)
1099                                    .to_string();
1100                                this.child(
1101                                    h_flex()
1102                                        .gap_1()
1103                                        .child(
1104                                            Icon::new(icon)
1105                                                .size(IconSize::Small)
1106                                                .color(Color::Muted),
1107                                        )
1108                                        .child(
1109                                            Button::new(
1110                                                "view-on-provider",
1111                                                format!("View on {}", provider_name),
1112                                            )
1113                                            .style(ButtonStyle::Transparent)
1114                                            .label_size(LabelSize::Small)
1115                                            .color(Color::Muted)
1116                                            .on_click(
1117                                                move |_, _, cx| {
1118                                                    cx.open_url(&url);
1119                                                },
1120                                            ),
1121                                        ),
1122                                )
1123                            }),
1124                    ),
1125            )
1126            .child(
1127                div()
1128                    .border_t_1()
1129                    .border_color(cx.theme().colors().border)
1130                    .p_3()
1131                    .min_w_0()
1132                    .child(
1133                        v_flex()
1134                            .gap_2()
1135                            .child(Label::new(subject).weight(FontWeight::MEDIUM)),
1136                    ),
1137            )
1138            .child(
1139                div()
1140                    .flex_1()
1141                    .overflow_hidden()
1142                    .border_t_1()
1143                    .border_color(cx.theme().colors().border)
1144                    .p_3()
1145                    .child(
1146                        v_flex()
1147                            .gap_2()
1148                            .child(
1149                                Label::new(format!("{} Changed Files", changed_files_count))
1150                                    .size(LabelSize::Small)
1151                                    .color(Color::Muted),
1152                            )
1153                            .children(self.selected_commit_diff.as_ref().map(|diff| {
1154                                v_flex().gap_1().children(diff.files.iter().map(|file| {
1155                                    let file_name: String = file
1156                                        .path
1157                                        .file_name()
1158                                        .map(|n| n.to_string())
1159                                        .unwrap_or_default();
1160                                    let dir_path: String = file
1161                                        .path
1162                                        .parent()
1163                                        .map(|p| p.as_unix_str().to_string())
1164                                        .unwrap_or_default();
1165
1166                                    h_flex()
1167                                        .gap_1()
1168                                        .overflow_hidden()
1169                                        .child(
1170                                            Icon::new(IconName::File)
1171                                                .size(IconSize::Small)
1172                                                .color(Color::Accent),
1173                                        )
1174                                        .child(
1175                                            Label::new(file_name)
1176                                                .size(LabelSize::Small)
1177                                                .single_line(),
1178                                        )
1179                                        .when(!dir_path.is_empty(), |this| {
1180                                            this.child(
1181                                                Label::new(dir_path)
1182                                                    .size(LabelSize::Small)
1183                                                    .color(Color::Muted)
1184                                                    .single_line(),
1185                                            )
1186                                        })
1187                                }))
1188                            })),
1189                    ),
1190            )
1191            .into_any_element()
1192    }
1193
1194    pub fn render_graph(&self, cx: &mut Context<GitGraph>) -> impl IntoElement {
1195        let row_height = self.row_height;
1196        let table_state = self.table_interaction_state.read(cx);
1197        let viewport_height = table_state
1198            .scroll_handle
1199            .0
1200            .borrow()
1201            .last_item_size
1202            .map(|size| size.item.height)
1203            .unwrap_or(px(600.0));
1204        let loaded_commit_count = self.graph_data.commits.len();
1205
1206        let content_height = row_height * loaded_commit_count;
1207        let max_scroll = (content_height - viewport_height).max(px(0.));
1208        let scroll_offset_y = (-table_state.scroll_offset().y).clamp(px(0.), max_scroll);
1209
1210        let first_visible_row = (scroll_offset_y / row_height).floor() as usize;
1211        let vertical_scroll_offset = scroll_offset_y - (first_visible_row as f32 * row_height);
1212        let horizontal_scroll_offset = self.horizontal_scroll_offset;
1213
1214        let max_lanes = self.graph_data.max_lanes.max(6);
1215        let graph_width = LANE_WIDTH * max_lanes as f32 + LEFT_PADDING * 2.0;
1216        let last_visible_row =
1217            first_visible_row + (viewport_height / row_height).ceil() as usize + 1;
1218
1219        let viewport_range = first_visible_row.min(loaded_commit_count.saturating_sub(1))
1220            ..(last_visible_row).min(loaded_commit_count);
1221        let rows = self.graph_data.commits[viewport_range.clone()].to_vec();
1222        let commit_lines: Vec<_> = self
1223            .graph_data
1224            .lines
1225            .iter()
1226            .filter(|line| {
1227                line.full_interval.start <= viewport_range.end
1228                    && line.full_interval.end >= viewport_range.start
1229            })
1230            .cloned()
1231            .collect();
1232
1233        let mut lines: BTreeMap<usize, Vec<_>> = BTreeMap::new();
1234
1235        gpui::canvas(
1236            move |_bounds, _window, _cx| {},
1237            move |bounds: Bounds<Pixels>, _: (), window: &mut Window, cx: &mut App| {
1238                window.paint_layer(bounds, |window| {
1239                    let accent_colors = cx.theme().accents();
1240
1241                    for (row_idx, row) in rows.into_iter().enumerate() {
1242                        let row_color = accent_colors.color_for_index(row.color_idx as u32);
1243                        let row_y_center =
1244                            bounds.origin.y + row_idx as f32 * row_height + row_height / 2.0
1245                                - vertical_scroll_offset;
1246
1247                        let commit_x =
1248                            lane_center_x(bounds, row.lane as f32, horizontal_scroll_offset);
1249
1250                        draw_commit_circle(commit_x, row_y_center, row_color, window);
1251                    }
1252
1253                    for line in commit_lines {
1254                        let Some((start_segment_idx, start_column)) =
1255                            line.get_first_visible_segment_idx(first_visible_row)
1256                        else {
1257                            continue;
1258                        };
1259
1260                        let line_x =
1261                            lane_center_x(bounds, start_column as f32, horizontal_scroll_offset);
1262
1263                        let start_row = line.full_interval.start as i32 - first_visible_row as i32;
1264
1265                        let from_y =
1266                            bounds.origin.y + start_row as f32 * row_height + row_height / 2.0
1267                                - vertical_scroll_offset
1268                                + COMMIT_CIRCLE_RADIUS;
1269
1270                        let mut current_row = from_y;
1271                        let mut current_column = line_x;
1272
1273                        let mut builder = PathBuilder::stroke(LINE_WIDTH);
1274                        builder.move_to(point(line_x, from_y));
1275
1276                        let segments = &line.segments[start_segment_idx..];
1277
1278                        for (segment_idx, segment) in segments.iter().enumerate() {
1279                            let is_last = segment_idx + 1 == segments.len();
1280
1281                            match segment {
1282                                CommitLineSegment::Straight { to_row } => {
1283                                    let mut dest_row = to_row_center(
1284                                        to_row - first_visible_row,
1285                                        row_height,
1286                                        vertical_scroll_offset,
1287                                        bounds,
1288                                    );
1289                                    if is_last {
1290                                        dest_row -= COMMIT_CIRCLE_RADIUS;
1291                                    }
1292
1293                                    let dest_point = point(current_column, dest_row);
1294
1295                                    current_row = dest_point.y;
1296                                    builder.line_to(dest_point);
1297                                    builder.move_to(dest_point);
1298                                }
1299                                CommitLineSegment::Curve {
1300                                    to_column,
1301                                    on_row,
1302                                    curve_kind,
1303                                } => {
1304                                    let mut to_column = lane_center_x(
1305                                        bounds,
1306                                        *to_column as f32,
1307                                        horizontal_scroll_offset,
1308                                    );
1309
1310                                    let mut to_row = to_row_center(
1311                                        *on_row - first_visible_row,
1312                                        row_height,
1313                                        vertical_scroll_offset,
1314                                        bounds,
1315                                    );
1316
1317                                    // This means that this branch was a checkout
1318                                    let going_right = to_column > current_column;
1319                                    let column_shift = if going_right {
1320                                        COMMIT_CIRCLE_RADIUS + COMMIT_CIRCLE_STROKE_WIDTH
1321                                    } else {
1322                                        -COMMIT_CIRCLE_RADIUS - COMMIT_CIRCLE_STROKE_WIDTH
1323                                    };
1324
1325                                    let control = match curve_kind {
1326                                        CurveKind::Checkout => {
1327                                            if is_last {
1328                                                to_column -= column_shift;
1329                                            }
1330                                            builder.move_to(point(current_column, current_row));
1331                                            point(current_column, to_row)
1332                                        }
1333                                        CurveKind::Merge => {
1334                                            if is_last {
1335                                                to_row -= COMMIT_CIRCLE_RADIUS;
1336                                            }
1337                                            builder.move_to(point(
1338                                                current_column + column_shift,
1339                                                current_row - COMMIT_CIRCLE_RADIUS,
1340                                            ));
1341                                            point(to_column, current_row)
1342                                        }
1343                                    };
1344
1345                                    match curve_kind {
1346                                        CurveKind::Checkout
1347                                            if (to_row - current_row).abs() > row_height =>
1348                                        {
1349                                            let start_curve =
1350                                                point(current_column, current_row + row_height);
1351                                            builder.line_to(start_curve);
1352                                            builder.move_to(start_curve);
1353                                        }
1354                                        CurveKind::Merge
1355                                            if (to_column - current_column).abs() > LANE_WIDTH =>
1356                                        {
1357                                            let column_shift =
1358                                                if going_right { LANE_WIDTH } else { -LANE_WIDTH };
1359
1360                                            let start_curve = point(
1361                                                current_column + column_shift,
1362                                                current_row - COMMIT_CIRCLE_RADIUS,
1363                                            );
1364
1365                                            builder.line_to(start_curve);
1366                                            builder.move_to(start_curve);
1367                                        }
1368                                        _ => {}
1369                                    };
1370
1371                                    builder.curve_to(point(to_column, to_row), control);
1372                                    current_row = to_row;
1373                                    current_column = to_column;
1374                                    builder.move_to(point(current_column, current_row));
1375                                }
1376                            }
1377                        }
1378
1379                        builder.close();
1380                        lines.entry(line.color_idx).or_default().push(builder);
1381                    }
1382
1383                    for (color_idx, builders) in lines {
1384                        let line_color = accent_colors.color_for_index(color_idx as u32);
1385
1386                        for builder in builders {
1387                            if let Ok(path) = builder.build() {
1388                                // we paint each color on it's own layer to stop overlapping lines
1389                                // of different colors changing the color of a line
1390                                window.paint_layer(bounds, |window| {
1391                                    window.paint_path(path, line_color);
1392                                });
1393                            }
1394                        }
1395                    }
1396                })
1397            },
1398        )
1399        .w(graph_width)
1400        .h_full()
1401    }
1402
1403    fn handle_graph_scroll(
1404        &mut self,
1405        event: &ScrollWheelEvent,
1406        window: &mut Window,
1407        cx: &mut Context<Self>,
1408    ) {
1409        let line_height = window.line_height();
1410        let delta = event.delta.pixel_delta(line_height);
1411
1412        let table_state = self.table_interaction_state.read(cx);
1413        let current_offset = table_state.scroll_offset();
1414
1415        let viewport_height = table_state.scroll_handle.viewport().size.height;
1416
1417        let commit_count = match self.graph_data.max_commit_count {
1418            AllCommitCount::Loaded(count) => count,
1419            AllCommitCount::NotLoaded => self.graph_data.commits.len(),
1420        };
1421        let content_height = self.row_height * commit_count;
1422        let max_vertical_scroll = (viewport_height - content_height).min(px(0.));
1423
1424        let new_y = (current_offset.y + delta.y).clamp(max_vertical_scroll, px(0.));
1425        let new_offset = Point::new(current_offset.x, new_y);
1426
1427        let max_lanes = self.graph_data.max_lanes.max(1);
1428        let graph_content_width = LANE_WIDTH * max_lanes as f32 + LEFT_PADDING * 2.0;
1429        let max_horizontal_scroll = (graph_content_width - self.graph_viewport_width).max(px(0.));
1430
1431        let new_horizontal_offset =
1432            (self.horizontal_scroll_offset - delta.x).clamp(px(0.), max_horizontal_scroll);
1433
1434        let vertical_changed = new_offset != current_offset;
1435        let horizontal_changed = new_horizontal_offset != self.horizontal_scroll_offset;
1436
1437        if vertical_changed {
1438            table_state.set_scroll_offset(new_offset);
1439        }
1440
1441        if horizontal_changed {
1442            self.horizontal_scroll_offset = new_horizontal_offset;
1443        }
1444
1445        if vertical_changed || horizontal_changed {
1446            cx.notify();
1447        }
1448    }
1449}
1450
1451impl Render for GitGraph {
1452    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1453        let description_width_fraction = 0.72;
1454        let date_width_fraction = 0.12;
1455        let author_width_fraction = 0.10;
1456        let commit_width_fraction = 0.06;
1457
1458        let (commit_count, is_loading) = match self.graph_data.max_commit_count {
1459            AllCommitCount::Loaded(count) => (count, true),
1460            AllCommitCount::NotLoaded => {
1461                let is_loading = self.project.update(cx, |project, cx| {
1462                    if let Some(repository) = project.active_repository(cx) {
1463                        repository.update(cx, |repository, cx| {
1464                            // Start loading the graph data if we haven't started already
1465                            repository
1466                                .graph_data(self.log_source.clone(), self.log_order, 0..0, cx)
1467                                .1
1468                        })
1469                    } else {
1470                        false
1471                    }
1472                }) && self.graph_data.commits.is_empty();
1473
1474                (self.graph_data.commits.len(), is_loading)
1475            }
1476        };
1477
1478        let content = if self.graph_data.commits.is_empty() {
1479            let message = if is_loading {
1480                "Loading"
1481            } else {
1482                "No commits found"
1483            };
1484            let label = Label::new(message)
1485                .color(Color::Muted)
1486                .size(LabelSize::Large);
1487            div()
1488                .size_full()
1489                .h_flex()
1490                .gap_1()
1491                .items_center()
1492                .justify_center()
1493                .child(label)
1494                .when(is_loading, |this| {
1495                    this.child(self.render_loading_spinner(cx))
1496                })
1497        } else {
1498            div()
1499                .size_full()
1500                .flex()
1501                .flex_row()
1502                .child(
1503                    div()
1504                        .w(self.graph_content_width())
1505                        .h_full()
1506                        .flex()
1507                        .flex_col()
1508                        .child(
1509                            div()
1510                                .p_2()
1511                                .border_b_1()
1512                                .border_color(cx.theme().colors().border)
1513                                .child(Label::new("Graph").color(Color::Muted)),
1514                        )
1515                        .child(
1516                            div()
1517                                .id("graph-canvas")
1518                                .flex_1()
1519                                .overflow_hidden()
1520                                .child(self.render_graph(cx))
1521                                .on_scroll_wheel(cx.listener(Self::handle_graph_scroll)),
1522                        ),
1523                )
1524                .child({
1525                    let row_height = self.row_height;
1526                    let selected_entry_idx = self.selected_entry_idx;
1527                    let weak_self = cx.weak_entity();
1528                    div().flex_1().size_full().child(
1529                        Table::new(4)
1530                            .interactable(&self.table_interaction_state)
1531                            .hide_row_borders()
1532                            .header(vec![
1533                                Label::new("Description")
1534                                    .color(Color::Muted)
1535                                    .into_any_element(),
1536                                Label::new("Date").color(Color::Muted).into_any_element(),
1537                                Label::new("Author").color(Color::Muted).into_any_element(),
1538                                Label::new("Commit").color(Color::Muted).into_any_element(),
1539                            ])
1540                            .column_widths(
1541                                [
1542                                    DefiniteLength::Fraction(description_width_fraction),
1543                                    DefiniteLength::Fraction(date_width_fraction),
1544                                    DefiniteLength::Fraction(author_width_fraction),
1545                                    DefiniteLength::Fraction(commit_width_fraction),
1546                                ]
1547                                .to_vec(),
1548                            )
1549                            .map_row(move |(index, row), _window, cx| {
1550                                let is_selected = selected_entry_idx == Some(index);
1551                                let weak = weak_self.clone();
1552                                row.h(row_height)
1553                                    .when(is_selected, |row| {
1554                                        row.bg(cx.theme().colors().element_selected)
1555                                    })
1556                                    .on_click(move |_, _, cx| {
1557                                        weak.update(cx, |this, cx| {
1558                                            this.select_entry(index, cx);
1559                                        })
1560                                        .ok();
1561                                    })
1562                                    .into_any_element()
1563                            })
1564                            .uniform_list(
1565                                "git-graph-commits",
1566                                commit_count,
1567                                cx.processor(Self::render_table_rows),
1568                            ),
1569                    )
1570                })
1571                .when(self.selected_entry_idx.is_some(), |this| {
1572                    this.child(self.render_commit_detail_panel(window, cx))
1573                })
1574        };
1575
1576        div()
1577            .size_full()
1578            .bg(cx.theme().colors().editor_background)
1579            .key_context("GitGraph")
1580            .track_focus(&self.focus_handle)
1581            .child(content)
1582            .children(self.context_menu.as_ref().map(|(menu, position, _)| {
1583                deferred(
1584                    anchored()
1585                        .position(*position)
1586                        .anchor(Corner::TopLeft)
1587                        .child(menu.clone()),
1588                )
1589                .with_priority(1)
1590            }))
1591    }
1592}
1593
1594impl EventEmitter<ItemEvent> for GitGraph {}
1595
1596impl Focusable for GitGraph {
1597    fn focus_handle(&self, _cx: &App) -> FocusHandle {
1598        self.focus_handle.clone()
1599    }
1600}
1601
1602impl Item for GitGraph {
1603    type Event = ItemEvent;
1604
1605    fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
1606        "Git Graph".into()
1607    }
1608
1609    fn show_toolbar(&self) -> bool {
1610        false
1611    }
1612
1613    fn to_item_events(event: &Self::Event, mut f: impl FnMut(ItemEvent)) {
1614        f(*event)
1615    }
1616}
1617
1618impl SerializableItem for GitGraph {
1619    fn serialized_item_kind() -> &'static str {
1620        "GitGraph"
1621    }
1622
1623    fn cleanup(
1624        workspace_id: workspace::WorkspaceId,
1625        alive_items: Vec<workspace::ItemId>,
1626        _window: &mut Window,
1627        cx: &mut App,
1628    ) -> Task<gpui::Result<()>> {
1629        workspace::delete_unloaded_items(
1630            alive_items,
1631            workspace_id,
1632            "git_graphs",
1633            &persistence::GIT_GRAPHS,
1634            cx,
1635        )
1636    }
1637
1638    fn deserialize(
1639        project: Entity<Project>,
1640        _: WeakEntity<Workspace>,
1641        workspace_id: workspace::WorkspaceId,
1642        item_id: workspace::ItemId,
1643        window: &mut Window,
1644        cx: &mut App,
1645    ) -> Task<gpui::Result<Entity<Self>>> {
1646        if persistence::GIT_GRAPHS
1647            .get_git_graph(item_id, workspace_id)
1648            .ok()
1649            .is_some_and(|is_open| is_open)
1650        {
1651            let git_graph = cx.new(|cx| GitGraph::new(project, window, cx));
1652            Task::ready(Ok(git_graph))
1653        } else {
1654            Task::ready(Err(anyhow::anyhow!("No git graph to deserialize")))
1655        }
1656    }
1657
1658    fn serialize(
1659        &mut self,
1660        workspace: &mut Workspace,
1661        item_id: workspace::ItemId,
1662        _closing: bool,
1663        _window: &mut Window,
1664        cx: &mut Context<Self>,
1665    ) -> Option<Task<gpui::Result<()>>> {
1666        let workspace_id = workspace.database_id()?;
1667        Some(cx.background_spawn(async move {
1668            persistence::GIT_GRAPHS
1669                .save_git_graph(item_id, workspace_id, true)
1670                .await
1671        }))
1672    }
1673
1674    fn should_serialize(&self, event: &Self::Event) -> bool {
1675        event == &ItemEvent::UpdateTab
1676    }
1677}
1678
1679mod persistence {
1680    use db::{
1681        query,
1682        sqlez::{domain::Domain, thread_safe_connection::ThreadSafeConnection},
1683        sqlez_macros::sql,
1684    };
1685    use workspace::WorkspaceDb;
1686
1687    pub struct GitGraphsDb(ThreadSafeConnection);
1688
1689    impl Domain for GitGraphsDb {
1690        const NAME: &str = stringify!(GitGraphsDb);
1691
1692        const MIGRATIONS: &[&str] = (&[sql!(
1693            CREATE TABLE git_graphs (
1694                workspace_id INTEGER,
1695                item_id INTEGER UNIQUE,
1696                is_open INTEGER DEFAULT FALSE,
1697
1698                PRIMARY KEY(workspace_id, item_id),
1699                FOREIGN KEY(workspace_id) REFERENCES workspaces(workspace_id)
1700                ON DELETE CASCADE
1701            ) STRICT;
1702        )]);
1703    }
1704
1705    db::static_connection!(GIT_GRAPHS, GitGraphsDb, [WorkspaceDb]);
1706
1707    impl GitGraphsDb {
1708        query! {
1709            pub async fn save_git_graph(
1710                item_id: workspace::ItemId,
1711                workspace_id: workspace::WorkspaceId,
1712                is_open: bool
1713            ) -> Result<()> {
1714                INSERT OR REPLACE INTO git_graphs(item_id, workspace_id, is_open)
1715                VALUES (?, ?, ?)
1716            }
1717        }
1718
1719        query! {
1720            pub fn get_git_graph(
1721                item_id: workspace::ItemId,
1722                workspace_id: workspace::WorkspaceId
1723            ) -> Result<bool> {
1724                SELECT is_open
1725                FROM git_graphs
1726                WHERE item_id = ? AND workspace_id = ?
1727            }
1728        }
1729    }
1730}
1731
1732#[cfg(test)]
1733mod tests {
1734    use super::*;
1735    use anyhow::{Context, Result, bail};
1736    use collections::{HashMap, HashSet};
1737    use fs::FakeFs;
1738    use git::Oid;
1739    use git::repository::InitialGraphCommitData;
1740    use gpui::TestAppContext;
1741    use project::Project;
1742    use rand::prelude::*;
1743    use serde_json::json;
1744    use settings::SettingsStore;
1745    use smallvec::{SmallVec, smallvec};
1746    use std::path::Path;
1747    use std::sync::Arc;
1748
1749    fn init_test(cx: &mut TestAppContext) {
1750        cx.update(|cx| {
1751            let settings_store = SettingsStore::test(cx);
1752            cx.set_global(settings_store);
1753        });
1754    }
1755
1756    /// Generates a random commit DAG suitable for testing git graph rendering.
1757    ///
1758    /// The commits are ordered newest-first (like git log output), so:
1759    /// - Index 0 = most recent commit (HEAD)
1760    /// - Last index = oldest commit (root, has no parents)
1761    /// - Parents of commit at index I must have index > I
1762    ///
1763    /// When `adversarial` is true, generates complex topologies with many branches
1764    /// and octopus merges. Otherwise generates more realistic linear histories
1765    /// with occasional branches.
1766    fn generate_random_commit_dag(
1767        rng: &mut StdRng,
1768        num_commits: usize,
1769        adversarial: bool,
1770    ) -> Vec<Arc<InitialGraphCommitData>> {
1771        if num_commits == 0 {
1772            return Vec::new();
1773        }
1774
1775        let mut commits: Vec<Arc<InitialGraphCommitData>> = Vec::with_capacity(num_commits);
1776        let oids: Vec<Oid> = (0..num_commits).map(|_| Oid::random(rng)).collect();
1777
1778        for i in 0..num_commits {
1779            let sha = oids[i];
1780
1781            let parents = if i == num_commits - 1 {
1782                smallvec![]
1783            } else {
1784                generate_parents_from_oids(rng, &oids, i, num_commits, adversarial)
1785            };
1786
1787            let ref_names = if i == 0 {
1788                vec!["HEAD".into(), "main".into()]
1789            } else if adversarial && rng.random_bool(0.1) {
1790                vec![format!("branch-{}", i).into()]
1791            } else {
1792                Vec::new()
1793            };
1794
1795            commits.push(Arc::new(InitialGraphCommitData {
1796                sha,
1797                parents,
1798                ref_names,
1799            }));
1800        }
1801
1802        commits
1803    }
1804
1805    fn generate_parents_from_oids(
1806        rng: &mut StdRng,
1807        oids: &[Oid],
1808        current_idx: usize,
1809        num_commits: usize,
1810        adversarial: bool,
1811    ) -> SmallVec<[Oid; 1]> {
1812        let remaining = num_commits - current_idx - 1;
1813        if remaining == 0 {
1814            return smallvec![];
1815        }
1816
1817        if adversarial {
1818            let merge_chance = 0.4;
1819            let octopus_chance = 0.15;
1820
1821            if remaining >= 3 && rng.random_bool(octopus_chance) {
1822                let num_parents = rng.random_range(3..=remaining.min(5));
1823                let mut parent_indices: Vec<usize> = (current_idx + 1..num_commits).collect();
1824                parent_indices.shuffle(rng);
1825                parent_indices
1826                    .into_iter()
1827                    .take(num_parents)
1828                    .map(|idx| oids[idx])
1829                    .collect()
1830            } else if remaining >= 2 && rng.random_bool(merge_chance) {
1831                let mut parent_indices: Vec<usize> = (current_idx + 1..num_commits).collect();
1832                parent_indices.shuffle(rng);
1833                parent_indices
1834                    .into_iter()
1835                    .take(2)
1836                    .map(|idx| oids[idx])
1837                    .collect()
1838            } else {
1839                let parent_idx = rng.random_range(current_idx + 1..num_commits);
1840                smallvec![oids[parent_idx]]
1841            }
1842        } else {
1843            let merge_chance = 0.15;
1844            let skip_chance = 0.1;
1845
1846            if remaining >= 2 && rng.random_bool(merge_chance) {
1847                let first_parent = current_idx + 1;
1848                let second_parent = rng.random_range(current_idx + 2..num_commits);
1849                smallvec![oids[first_parent], oids[second_parent]]
1850            } else if rng.random_bool(skip_chance) && remaining >= 2 {
1851                let skip = rng.random_range(1..remaining.min(3));
1852                smallvec![oids[current_idx + 1 + skip]]
1853            } else {
1854                smallvec![oids[current_idx + 1]]
1855            }
1856        }
1857    }
1858
1859    fn build_oid_to_row_map(graph: &GraphData) -> HashMap<Oid, usize> {
1860        graph
1861            .commits
1862            .iter()
1863            .enumerate()
1864            .map(|(idx, entry)| (entry.data.sha, idx))
1865            .collect()
1866    }
1867
1868    fn verify_commit_order(
1869        graph: &GraphData,
1870        commits: &[Arc<InitialGraphCommitData>],
1871    ) -> Result<()> {
1872        if graph.commits.len() != commits.len() {
1873            bail!(
1874                "Commit count mismatch: graph has {} commits, expected {}",
1875                graph.commits.len(),
1876                commits.len()
1877            );
1878        }
1879
1880        for (idx, (graph_commit, expected_commit)) in
1881            graph.commits.iter().zip(commits.iter()).enumerate()
1882        {
1883            if graph_commit.data.sha != expected_commit.sha {
1884                bail!(
1885                    "Commit order mismatch at index {}: graph has {:?}, expected {:?}",
1886                    idx,
1887                    graph_commit.data.sha,
1888                    expected_commit.sha
1889                );
1890            }
1891        }
1892
1893        Ok(())
1894    }
1895
1896    fn verify_line_endpoints(graph: &GraphData, oid_to_row: &HashMap<Oid, usize>) -> Result<()> {
1897        for line in &graph.lines {
1898            let child_row = *oid_to_row
1899                .get(&line.child)
1900                .context("Line references non-existent child commit")?;
1901
1902            let parent_row = *oid_to_row
1903                .get(&line.parent)
1904                .context("Line references non-existent parent commit")?;
1905
1906            if child_row >= parent_row {
1907                bail!(
1908                    "child_row ({}) must be < parent_row ({})",
1909                    child_row,
1910                    parent_row
1911                );
1912            }
1913
1914            if line.full_interval.start != child_row {
1915                bail!(
1916                    "full_interval.start ({}) != child_row ({})",
1917                    line.full_interval.start,
1918                    child_row
1919                );
1920            }
1921
1922            if line.full_interval.end != parent_row {
1923                bail!(
1924                    "full_interval.end ({}) != parent_row ({})",
1925                    line.full_interval.end,
1926                    parent_row
1927                );
1928            }
1929
1930            if let Some(last_segment) = line.segments.last() {
1931                let segment_end_row = match last_segment {
1932                    CommitLineSegment::Straight { to_row } => *to_row,
1933                    CommitLineSegment::Curve { on_row, .. } => *on_row,
1934                };
1935
1936                if segment_end_row != line.full_interval.end {
1937                    bail!(
1938                        "last segment ends at row {} but full_interval.end is {}",
1939                        segment_end_row,
1940                        line.full_interval.end
1941                    );
1942                }
1943            }
1944        }
1945
1946        Ok(())
1947    }
1948
1949    fn verify_column_correctness(
1950        graph: &GraphData,
1951        oid_to_row: &HashMap<Oid, usize>,
1952    ) -> Result<()> {
1953        for line in &graph.lines {
1954            let child_row = *oid_to_row
1955                .get(&line.child)
1956                .context("Line references non-existent child commit")?;
1957
1958            let parent_row = *oid_to_row
1959                .get(&line.parent)
1960                .context("Line references non-existent parent commit")?;
1961
1962            let child_lane = graph.commits[child_row].lane;
1963            if line.child_column != child_lane {
1964                bail!(
1965                    "child_column ({}) != child's lane ({})",
1966                    line.child_column,
1967                    child_lane
1968                );
1969            }
1970
1971            let mut current_column = line.child_column;
1972            for segment in &line.segments {
1973                if let CommitLineSegment::Curve { to_column, .. } = segment {
1974                    current_column = *to_column;
1975                }
1976            }
1977
1978            let parent_lane = graph.commits[parent_row].lane;
1979            if current_column != parent_lane {
1980                bail!(
1981                    "ending column ({}) != parent's lane ({})",
1982                    current_column,
1983                    parent_lane
1984                );
1985            }
1986        }
1987
1988        Ok(())
1989    }
1990
1991    fn verify_segment_continuity(graph: &GraphData) -> Result<()> {
1992        for line in &graph.lines {
1993            if line.segments.is_empty() {
1994                bail!("Line has no segments");
1995            }
1996
1997            let mut current_row = line.full_interval.start;
1998
1999            for (idx, segment) in line.segments.iter().enumerate() {
2000                let segment_end_row = match segment {
2001                    CommitLineSegment::Straight { to_row } => *to_row,
2002                    CommitLineSegment::Curve { on_row, .. } => *on_row,
2003                };
2004
2005                if segment_end_row < current_row {
2006                    bail!(
2007                        "segment {} ends at row {} which is before current row {}",
2008                        idx,
2009                        segment_end_row,
2010                        current_row
2011                    );
2012                }
2013
2014                current_row = segment_end_row;
2015            }
2016        }
2017
2018        Ok(())
2019    }
2020
2021    fn verify_line_overlaps(graph: &GraphData) -> Result<()> {
2022        for line in &graph.lines {
2023            let child_row = line.full_interval.start;
2024
2025            let mut current_column = line.child_column;
2026            let mut current_row = child_row;
2027
2028            for segment in &line.segments {
2029                match segment {
2030                    CommitLineSegment::Straight { to_row } => {
2031                        for row in (current_row + 1)..*to_row {
2032                            if row < graph.commits.len() {
2033                                let commit_at_row = &graph.commits[row];
2034                                if commit_at_row.lane == current_column {
2035                                    bail!(
2036                                        "straight segment from row {} to {} in column {} passes through commit {:?} at row {}",
2037                                        current_row,
2038                                        to_row,
2039                                        current_column,
2040                                        commit_at_row.data.sha,
2041                                        row
2042                                    );
2043                                }
2044                            }
2045                        }
2046                        current_row = *to_row;
2047                    }
2048                    CommitLineSegment::Curve {
2049                        to_column, on_row, ..
2050                    } => {
2051                        current_column = *to_column;
2052                        current_row = *on_row;
2053                    }
2054                }
2055            }
2056        }
2057
2058        Ok(())
2059    }
2060
2061    fn verify_coverage(graph: &GraphData) -> Result<()> {
2062        let mut expected_edges: HashSet<(Oid, Oid)> = HashSet::default();
2063        for entry in &graph.commits {
2064            for parent in &entry.data.parents {
2065                expected_edges.insert((entry.data.sha, *parent));
2066            }
2067        }
2068
2069        let mut found_edges: HashSet<(Oid, Oid)> = HashSet::default();
2070        for line in &graph.lines {
2071            let edge = (line.child, line.parent);
2072
2073            if !found_edges.insert(edge) {
2074                bail!(
2075                    "Duplicate line found for edge {:?} -> {:?}",
2076                    line.child,
2077                    line.parent
2078                );
2079            }
2080
2081            if !expected_edges.contains(&edge) {
2082                bail!(
2083                    "Orphan line found: {:?} -> {:?} is not in the commit graph",
2084                    line.child,
2085                    line.parent
2086                );
2087            }
2088        }
2089
2090        for (child, parent) in &expected_edges {
2091            if !found_edges.contains(&(*child, *parent)) {
2092                bail!("Missing line for edge {:?} -> {:?}", child, parent);
2093            }
2094        }
2095
2096        assert_eq!(
2097            expected_edges.symmetric_difference(&found_edges).count(),
2098            0,
2099            "The symmetric difference should be zero"
2100        );
2101
2102        Ok(())
2103    }
2104
2105    fn verify_merge_line_optimality(
2106        graph: &GraphData,
2107        oid_to_row: &HashMap<Oid, usize>,
2108    ) -> Result<()> {
2109        for line in &graph.lines {
2110            let first_segment = line.segments.first();
2111            let is_merge_line = matches!(
2112                first_segment,
2113                Some(CommitLineSegment::Curve {
2114                    curve_kind: CurveKind::Merge,
2115                    ..
2116                })
2117            );
2118
2119            if !is_merge_line {
2120                continue;
2121            }
2122
2123            let child_row = *oid_to_row
2124                .get(&line.child)
2125                .context("Line references non-existent child commit")?;
2126
2127            let parent_row = *oid_to_row
2128                .get(&line.parent)
2129                .context("Line references non-existent parent commit")?;
2130
2131            let parent_lane = graph.commits[parent_row].lane;
2132
2133            let Some(CommitLineSegment::Curve { to_column, .. }) = first_segment else {
2134                continue;
2135            };
2136
2137            let curves_directly_to_parent = *to_column == parent_lane;
2138
2139            if !curves_directly_to_parent {
2140                continue;
2141            }
2142
2143            let curve_row = child_row + 1;
2144            let has_commits_in_path = graph.commits[curve_row..parent_row]
2145                .iter()
2146                .any(|c| c.lane == parent_lane);
2147
2148            if has_commits_in_path {
2149                bail!(
2150                    "Merge line from {:?} to {:?} curves directly to parent lane {} but there are commits in that lane between rows {} and {}",
2151                    line.child,
2152                    line.parent,
2153                    parent_lane,
2154                    curve_row,
2155                    parent_row
2156                );
2157            }
2158
2159            let curve_ends_at_parent = curve_row == parent_row;
2160
2161            if curve_ends_at_parent {
2162                if line.segments.len() != 1 {
2163                    bail!(
2164                        "Merge line from {:?} to {:?} curves directly to parent (curve_row == parent_row), but has {} segments instead of 1 [MergeCurve]",
2165                        line.child,
2166                        line.parent,
2167                        line.segments.len()
2168                    );
2169                }
2170            } else {
2171                if line.segments.len() != 2 {
2172                    bail!(
2173                        "Merge line from {:?} to {:?} curves directly to parent lane without overlap, but has {} segments instead of 2 [MergeCurve, Straight]",
2174                        line.child,
2175                        line.parent,
2176                        line.segments.len()
2177                    );
2178                }
2179
2180                let is_straight_segment = matches!(
2181                    line.segments.get(1),
2182                    Some(CommitLineSegment::Straight { .. })
2183                );
2184
2185                if !is_straight_segment {
2186                    bail!(
2187                        "Merge line from {:?} to {:?} curves directly to parent lane without overlap, but second segment is not a Straight segment",
2188                        line.child,
2189                        line.parent
2190                    );
2191                }
2192            }
2193        }
2194
2195        Ok(())
2196    }
2197
2198    fn verify_all_invariants(
2199        graph: &GraphData,
2200        commits: &[Arc<InitialGraphCommitData>],
2201    ) -> Result<()> {
2202        let oid_to_row = build_oid_to_row_map(graph);
2203
2204        verify_commit_order(graph, commits).context("commit order")?;
2205        verify_line_endpoints(graph, &oid_to_row).context("line endpoints")?;
2206        verify_column_correctness(graph, &oid_to_row).context("column correctness")?;
2207        verify_segment_continuity(graph).context("segment continuity")?;
2208        verify_merge_line_optimality(graph, &oid_to_row).context("merge line optimality")?;
2209        verify_coverage(graph).context("coverage")?;
2210        verify_line_overlaps(graph).context("line overlaps")?;
2211        Ok(())
2212    }
2213
2214    #[test]
2215    fn test_git_graph_merge_commits() {
2216        let mut rng = StdRng::seed_from_u64(42);
2217
2218        let oid1 = Oid::random(&mut rng);
2219        let oid2 = Oid::random(&mut rng);
2220        let oid3 = Oid::random(&mut rng);
2221        let oid4 = Oid::random(&mut rng);
2222
2223        let commits = vec![
2224            Arc::new(InitialGraphCommitData {
2225                sha: oid1,
2226                parents: smallvec![oid2, oid3],
2227                ref_names: vec!["HEAD".into()],
2228            }),
2229            Arc::new(InitialGraphCommitData {
2230                sha: oid2,
2231                parents: smallvec![oid4],
2232                ref_names: vec![],
2233            }),
2234            Arc::new(InitialGraphCommitData {
2235                sha: oid3,
2236                parents: smallvec![oid4],
2237                ref_names: vec![],
2238            }),
2239            Arc::new(InitialGraphCommitData {
2240                sha: oid4,
2241                parents: smallvec![],
2242                ref_names: vec![],
2243            }),
2244        ];
2245
2246        let mut graph_data = GraphData::new(8);
2247        graph_data.add_commits(&commits);
2248
2249        if let Err(error) = verify_all_invariants(&graph_data, &commits) {
2250            panic!("Graph invariant violation for merge commits:\n{}", error);
2251        }
2252    }
2253
2254    #[test]
2255    fn test_git_graph_linear_commits() {
2256        let mut rng = StdRng::seed_from_u64(42);
2257
2258        let oid1 = Oid::random(&mut rng);
2259        let oid2 = Oid::random(&mut rng);
2260        let oid3 = Oid::random(&mut rng);
2261
2262        let commits = vec![
2263            Arc::new(InitialGraphCommitData {
2264                sha: oid1,
2265                parents: smallvec![oid2],
2266                ref_names: vec!["HEAD".into()],
2267            }),
2268            Arc::new(InitialGraphCommitData {
2269                sha: oid2,
2270                parents: smallvec![oid3],
2271                ref_names: vec![],
2272            }),
2273            Arc::new(InitialGraphCommitData {
2274                sha: oid3,
2275                parents: smallvec![],
2276                ref_names: vec![],
2277            }),
2278        ];
2279
2280        let mut graph_data = GraphData::new(8);
2281        graph_data.add_commits(&commits);
2282
2283        if let Err(error) = verify_all_invariants(&graph_data, &commits) {
2284            panic!("Graph invariant violation for linear commits:\n{}", error);
2285        }
2286    }
2287
2288    #[test]
2289    fn test_git_graph_random_commits() {
2290        for seed in 0..100 {
2291            let mut rng = StdRng::seed_from_u64(seed);
2292
2293            let adversarial = rng.random_bool(0.2);
2294            let num_commits = if adversarial {
2295                rng.random_range(10..100)
2296            } else {
2297                rng.random_range(5..50)
2298            };
2299
2300            let commits = generate_random_commit_dag(&mut rng, num_commits, adversarial);
2301
2302            assert_eq!(
2303                num_commits,
2304                commits.len(),
2305                "seed={}: Generate random commit dag didn't generate the correct amount of commits",
2306                seed
2307            );
2308
2309            let mut graph_data = GraphData::new(8);
2310            graph_data.add_commits(&commits);
2311
2312            if let Err(error) = verify_all_invariants(&graph_data, &commits) {
2313                panic!(
2314                    "Graph invariant violation (seed={}, adversarial={}, num_commits={}):\n{:#}",
2315                    seed, adversarial, num_commits, error
2316                );
2317            }
2318        }
2319    }
2320
2321    // The full integration test has less iterations because it's significantly slower
2322    // than the random commit test
2323    #[gpui::test(iterations = 5)]
2324    async fn test_git_graph_random_integration(mut rng: StdRng, cx: &mut TestAppContext) {
2325        init_test(cx);
2326
2327        let adversarial = rng.random_bool(0.2);
2328        let num_commits = if adversarial {
2329            rng.random_range(10..100)
2330        } else {
2331            rng.random_range(5..50)
2332        };
2333
2334        let commits = generate_random_commit_dag(&mut rng, num_commits, adversarial);
2335
2336        let fs = FakeFs::new(cx.executor());
2337        fs.insert_tree(
2338            Path::new("/project"),
2339            json!({
2340                ".git": {},
2341                "file.txt": "content",
2342            }),
2343        )
2344        .await;
2345
2346        fs.set_graph_commits(Path::new("/project/.git"), commits.clone());
2347
2348        let project = Project::test(fs.clone(), [Path::new("/project")], cx).await;
2349        cx.run_until_parked();
2350
2351        let repository = project.read_with(cx, |project, cx| {
2352            project
2353                .active_repository(cx)
2354                .expect("should have a repository")
2355        });
2356
2357        repository.update(cx, |repo, cx| {
2358            repo.graph_data(
2359                crate::LogSource::default(),
2360                crate::LogOrder::default(),
2361                0..usize::MAX,
2362                cx,
2363            );
2364        });
2365        cx.run_until_parked();
2366
2367        let graph_commits: Vec<Arc<InitialGraphCommitData>> = repository.update(cx, |repo, cx| {
2368            repo.graph_data(
2369                crate::LogSource::default(),
2370                crate::LogOrder::default(),
2371                0..usize::MAX,
2372                cx,
2373            )
2374            .0
2375            .to_vec()
2376        });
2377
2378        let mut graph_data = GraphData::new(8);
2379        graph_data.add_commits(&graph_commits);
2380
2381        if let Err(error) = verify_all_invariants(&graph_data, &commits) {
2382            panic!(
2383                "Graph invariant violation (adversarial={}, num_commits={}):\n{:#}",
2384                adversarial, num_commits, error
2385            );
2386        }
2387    }
2388}