1mod ids;
  2mod queries;
  3mod tables;
  4#[cfg(test)]
  5pub mod tests;
  6
  7use crate::{Error, Result};
  8use anyhow::{Context as _, anyhow};
  9use collections::{BTreeMap, BTreeSet, HashMap, HashSet};
 10use dashmap::DashMap;
 11use futures::StreamExt;
 12use project_repository_statuses::StatusKind;
 13use rpc::ExtensionProvides;
 14use rpc::{
 15    ConnectionId, ExtensionMetadata,
 16    proto::{self},
 17};
 18use sea_orm::{
 19    ActiveValue, Condition, ConnectionTrait, DatabaseConnection, DatabaseTransaction,
 20    FromQueryResult, IntoActiveModel, IsolationLevel, JoinType, QueryOrder, QuerySelect, Statement,
 21    TransactionTrait,
 22    entity::prelude::*,
 23    sea_query::{Alias, Expr, OnConflict},
 24};
 25use semantic_version::SemanticVersion;
 26use serde::{Deserialize, Serialize};
 27use std::ops::RangeInclusive;
 28use std::{
 29    future::Future,
 30    marker::PhantomData,
 31    ops::{Deref, DerefMut},
 32    rc::Rc,
 33    sync::Arc,
 34};
 35use time::PrimitiveDateTime;
 36use tokio::sync::{Mutex, OwnedMutexGuard};
 37use util::paths::PathStyle;
 38use worktree_settings_file::LocalSettingsKind;
 39
 40#[cfg(test)]
 41pub use tests::TestDb;
 42
 43pub use ids::*;
 44pub use queries::contributors::ContributorSelector;
 45pub use sea_orm::ConnectOptions;
 46pub use tables::user::Model as User;
 47pub use tables::*;
 48
 49#[cfg(test)]
 50pub struct DatabaseTestOptions {
 51    pub executor: gpui::BackgroundExecutor,
 52    pub runtime: tokio::runtime::Runtime,
 53    pub query_failure_probability: parking_lot::Mutex<f64>,
 54}
 55
 56/// Database gives you a handle that lets you access the database.
 57/// It handles pooling internally.
 58pub struct Database {
 59    options: ConnectOptions,
 60    pool: DatabaseConnection,
 61    rooms: DashMap<RoomId, Arc<Mutex<()>>>,
 62    projects: DashMap<ProjectId, Arc<Mutex<()>>>,
 63    notification_kinds_by_id: HashMap<NotificationKindId, &'static str>,
 64    notification_kinds_by_name: HashMap<String, NotificationKindId>,
 65    #[cfg(test)]
 66    test_options: Option<DatabaseTestOptions>,
 67}
 68
 69// The `Database` type has so many methods that its impl blocks are split into
 70// separate files in the `queries` folder.
 71impl Database {
 72    /// Connects to the database with the given options
 73    pub async fn new(options: ConnectOptions) -> Result<Self> {
 74        sqlx::any::install_default_drivers();
 75        Ok(Self {
 76            options: options.clone(),
 77            pool: sea_orm::Database::connect(options).await?,
 78            rooms: DashMap::with_capacity(16384),
 79            projects: DashMap::with_capacity(16384),
 80            notification_kinds_by_id: HashMap::default(),
 81            notification_kinds_by_name: HashMap::default(),
 82            #[cfg(test)]
 83            test_options: None,
 84        })
 85    }
 86
 87    pub fn options(&self) -> &ConnectOptions {
 88        &self.options
 89    }
 90
 91    #[cfg(test)]
 92    pub fn reset(&self) {
 93        self.rooms.clear();
 94        self.projects.clear();
 95    }
 96
 97    pub async fn transaction<F, Fut, T>(&self, f: F) -> Result<T>
 98    where
 99        F: Send + Fn(TransactionHandle) -> Fut,
100        Fut: Send + Future<Output = Result<T>>,
101    {
102        let body = async {
103            let (tx, result) = self.with_transaction(&f).await?;
104            match result {
105                Ok(result) => match tx.commit().await.map_err(Into::into) {
106                    Ok(()) => Ok(result),
107                    Err(error) => Err(error),
108                },
109                Err(error) => {
110                    tx.rollback().await?;
111                    Err(error)
112                }
113            }
114        };
115
116        self.run(body).await
117    }
118
119    /// The same as room_transaction, but if you need to only optionally return a Room.
120    async fn optional_room_transaction<F, Fut, T>(
121        &self,
122        f: F,
123    ) -> Result<Option<TransactionGuard<T>>>
124    where
125        F: Send + Fn(TransactionHandle) -> Fut,
126        Fut: Send + Future<Output = Result<Option<(RoomId, T)>>>,
127    {
128        let body = async {
129            let (tx, result) = self.with_transaction(&f).await?;
130            match result {
131                Ok(Some((room_id, data))) => {
132                    let lock = self.rooms.entry(room_id).or_default().clone();
133                    let _guard = lock.lock_owned().await;
134                    match tx.commit().await.map_err(Into::into) {
135                        Ok(()) => Ok(Some(TransactionGuard {
136                            data,
137                            _guard,
138                            _not_send: PhantomData,
139                        })),
140                        Err(error) => Err(error),
141                    }
142                }
143                Ok(None) => match tx.commit().await.map_err(Into::into) {
144                    Ok(()) => Ok(None),
145                    Err(error) => Err(error),
146                },
147                Err(error) => {
148                    tx.rollback().await?;
149                    Err(error)
150                }
151            }
152        };
153
154        self.run(body).await
155    }
156
157    async fn project_transaction<F, Fut, T>(
158        &self,
159        project_id: ProjectId,
160        f: F,
161    ) -> Result<TransactionGuard<T>>
162    where
163        F: Send + Fn(TransactionHandle) -> Fut,
164        Fut: Send + Future<Output = Result<T>>,
165    {
166        let room_id = Database::room_id_for_project(self, project_id).await?;
167        let body = async {
168            let lock = if let Some(room_id) = room_id {
169                self.rooms.entry(room_id).or_default().clone()
170            } else {
171                self.projects.entry(project_id).or_default().clone()
172            };
173            let _guard = lock.lock_owned().await;
174            let (tx, result) = self.with_transaction(&f).await?;
175            match result {
176                Ok(data) => match tx.commit().await.map_err(Into::into) {
177                    Ok(()) => Ok(TransactionGuard {
178                        data,
179                        _guard,
180                        _not_send: PhantomData,
181                    }),
182                    Err(error) => Err(error),
183                },
184                Err(error) => {
185                    tx.rollback().await?;
186                    Err(error)
187                }
188            }
189        };
190
191        self.run(body).await
192    }
193
194    /// room_transaction runs the block in a transaction. It returns a RoomGuard, that keeps
195    /// the database locked until it is dropped. This ensures that updates sent to clients are
196    /// properly serialized with respect to database changes.
197    async fn room_transaction<F, Fut, T>(
198        &self,
199        room_id: RoomId,
200        f: F,
201    ) -> Result<TransactionGuard<T>>
202    where
203        F: Send + Fn(TransactionHandle) -> Fut,
204        Fut: Send + Future<Output = Result<T>>,
205    {
206        let body = async {
207            let lock = self.rooms.entry(room_id).or_default().clone();
208            let _guard = lock.lock_owned().await;
209            let (tx, result) = self.with_transaction(&f).await?;
210            match result {
211                Ok(data) => match tx.commit().await.map_err(Into::into) {
212                    Ok(()) => Ok(TransactionGuard {
213                        data,
214                        _guard,
215                        _not_send: PhantomData,
216                    }),
217                    Err(error) => Err(error),
218                },
219                Err(error) => {
220                    tx.rollback().await?;
221                    Err(error)
222                }
223            }
224        };
225
226        self.run(body).await
227    }
228
229    async fn with_transaction<F, Fut, T>(&self, f: &F) -> Result<(DatabaseTransaction, Result<T>)>
230    where
231        F: Send + Fn(TransactionHandle) -> Fut,
232        Fut: Send + Future<Output = Result<T>>,
233    {
234        let tx = self
235            .pool
236            .begin_with_config(Some(IsolationLevel::ReadCommitted), None)
237            .await?;
238
239        let mut tx = Arc::new(Some(tx));
240        let result = f(TransactionHandle(tx.clone())).await;
241        let tx = Arc::get_mut(&mut tx)
242            .and_then(|tx| tx.take())
243            .context("couldn't complete transaction because it's still in use")?;
244
245        Ok((tx, result))
246    }
247
248    async fn run<F, T>(&self, future: F) -> Result<T>
249    where
250        F: Future<Output = Result<T>>,
251    {
252        #[cfg(test)]
253        {
254            use rand::prelude::*;
255
256            let test_options = self.test_options.as_ref().unwrap();
257            test_options.executor.simulate_random_delay().await;
258            let fail_probability = *test_options.query_failure_probability.lock();
259            if test_options.executor.rng().random_bool(fail_probability) {
260                return Err(anyhow!("simulated query failure"))?;
261            }
262
263            test_options.runtime.block_on(future)
264        }
265
266        #[cfg(not(test))]
267        {
268            future.await
269        }
270    }
271}
272
273/// A handle to a [`DatabaseTransaction`].
274pub struct TransactionHandle(pub(crate) Arc<Option<DatabaseTransaction>>);
275
276impl Deref for TransactionHandle {
277    type Target = DatabaseTransaction;
278
279    fn deref(&self) -> &Self::Target {
280        self.0.as_ref().as_ref().unwrap()
281    }
282}
283
284/// [`TransactionGuard`] keeps a database transaction alive until it is dropped.
285/// It wraps data that depends on the state of the database and prevents an additional
286/// transaction from starting that would invalidate that data.
287pub struct TransactionGuard<T> {
288    data: T,
289    _guard: OwnedMutexGuard<()>,
290    _not_send: PhantomData<Rc<()>>,
291}
292
293impl<T> Deref for TransactionGuard<T> {
294    type Target = T;
295
296    fn deref(&self) -> &T {
297        &self.data
298    }
299}
300
301impl<T> DerefMut for TransactionGuard<T> {
302    fn deref_mut(&mut self) -> &mut T {
303        &mut self.data
304    }
305}
306
307impl<T> TransactionGuard<T> {
308    /// Returns the inner value of the guard.
309    pub fn into_inner(self) -> T {
310        self.data
311    }
312}
313
314#[derive(Clone, Debug, PartialEq, Eq)]
315pub enum Contact {
316    Accepted { user_id: UserId, busy: bool },
317    Outgoing { user_id: UserId },
318    Incoming { user_id: UserId },
319}
320
321impl Contact {
322    pub fn user_id(&self) -> UserId {
323        match self {
324            Contact::Accepted { user_id, .. } => *user_id,
325            Contact::Outgoing { user_id } => *user_id,
326            Contact::Incoming { user_id, .. } => *user_id,
327        }
328    }
329}
330
331pub type NotificationBatch = Vec<(UserId, proto::Notification)>;
332
333pub struct CreatedChannelMessage {
334    pub message_id: MessageId,
335    pub participant_connection_ids: HashSet<ConnectionId>,
336    pub notifications: NotificationBatch,
337}
338
339pub struct UpdatedChannelMessage {
340    pub message_id: MessageId,
341    pub participant_connection_ids: Vec<ConnectionId>,
342    pub notifications: NotificationBatch,
343    pub reply_to_message_id: Option<MessageId>,
344    pub timestamp: PrimitiveDateTime,
345    pub deleted_mention_notification_ids: Vec<NotificationId>,
346    pub updated_mention_notifications: Vec<rpc::proto::Notification>,
347}
348
349#[derive(Clone, Debug, PartialEq, Eq, FromQueryResult, Serialize, Deserialize)]
350pub struct Invite {
351    pub email_address: String,
352    pub email_confirmation_code: String,
353}
354
355#[derive(Clone, Debug, Deserialize)]
356pub struct NewSignup {
357    pub email_address: String,
358    pub platform_mac: bool,
359    pub platform_windows: bool,
360    pub platform_linux: bool,
361    pub editor_features: Vec<String>,
362    pub programming_languages: Vec<String>,
363    pub device_id: Option<String>,
364    pub added_to_mailing_list: bool,
365    pub created_at: Option<DateTime>,
366}
367
368#[derive(Clone, Debug, PartialEq, Deserialize, Serialize, FromQueryResult)]
369pub struct WaitlistSummary {
370    pub count: i64,
371    pub linux_count: i64,
372    pub mac_count: i64,
373    pub windows_count: i64,
374    pub unknown_count: i64,
375}
376
377/// The parameters to create a new user.
378#[derive(Debug, Serialize, Deserialize)]
379pub struct NewUserParams {
380    pub github_login: String,
381    pub github_user_id: i32,
382}
383
384/// The result of creating a new user.
385#[derive(Debug)]
386pub struct NewUserResult {
387    pub user_id: UserId,
388    pub metrics_id: String,
389    pub inviting_user_id: Option<UserId>,
390    pub signup_device_id: Option<String>,
391}
392
393/// The result of updating a channel membership.
394#[derive(Debug)]
395pub struct MembershipUpdated {
396    pub channel_id: ChannelId,
397    pub new_channels: ChannelsForUser,
398    pub removed_channels: Vec<ChannelId>,
399}
400
401/// The result of setting a member's role.
402#[derive(Debug)]
403
404pub enum SetMemberRoleResult {
405    InviteUpdated(Channel),
406    MembershipUpdated(MembershipUpdated),
407}
408
409/// The result of inviting a member to a channel.
410#[derive(Debug)]
411pub struct InviteMemberResult {
412    pub channel: Channel,
413    pub notifications: NotificationBatch,
414}
415
416#[derive(Debug)]
417pub struct RespondToChannelInvite {
418    pub membership_update: Option<MembershipUpdated>,
419    pub notifications: NotificationBatch,
420}
421
422#[derive(Debug)]
423pub struct RemoveChannelMemberResult {
424    pub membership_update: MembershipUpdated,
425    pub notification_id: Option<NotificationId>,
426}
427
428#[derive(Debug, PartialEq, Eq, Hash)]
429pub struct Channel {
430    pub id: ChannelId,
431    pub name: String,
432    pub visibility: ChannelVisibility,
433    /// parent_path is the channel ids from the root to this one (not including this one)
434    pub parent_path: Vec<ChannelId>,
435    pub channel_order: i32,
436}
437
438impl Channel {
439    pub fn from_model(value: channel::Model) -> Self {
440        Channel {
441            id: value.id,
442            visibility: value.visibility,
443            name: value.clone().name,
444            parent_path: value.ancestors().collect(),
445            channel_order: value.channel_order,
446        }
447    }
448
449    pub fn to_proto(&self) -> proto::Channel {
450        proto::Channel {
451            id: self.id.to_proto(),
452            name: self.name.clone(),
453            visibility: self.visibility.into(),
454            parent_path: self.parent_path.iter().map(|c| c.to_proto()).collect(),
455            channel_order: self.channel_order,
456        }
457    }
458
459    pub fn root_id(&self) -> ChannelId {
460        self.parent_path.first().copied().unwrap_or(self.id)
461    }
462}
463
464#[derive(Debug, PartialEq, Eq, Hash)]
465pub struct ChannelMember {
466    pub role: ChannelRole,
467    pub user_id: UserId,
468    pub kind: proto::channel_member::Kind,
469}
470
471impl ChannelMember {
472    pub fn to_proto(&self) -> proto::ChannelMember {
473        proto::ChannelMember {
474            role: self.role.into(),
475            user_id: self.user_id.to_proto(),
476            kind: self.kind.into(),
477        }
478    }
479}
480
481#[derive(Debug, PartialEq)]
482pub struct ChannelsForUser {
483    pub channels: Vec<Channel>,
484    pub channel_memberships: Vec<channel_member::Model>,
485    pub channel_participants: HashMap<ChannelId, Vec<UserId>>,
486    pub invited_channels: Vec<Channel>,
487
488    pub observed_buffer_versions: Vec<proto::ChannelBufferVersion>,
489    pub latest_buffer_versions: Vec<proto::ChannelBufferVersion>,
490}
491
492#[derive(Debug)]
493pub struct RejoinedChannelBuffer {
494    pub buffer: proto::RejoinedChannelBuffer,
495    pub old_connection_id: ConnectionId,
496}
497
498#[derive(Clone)]
499pub struct JoinRoom {
500    pub room: proto::Room,
501    pub channel: Option<channel::Model>,
502}
503
504pub struct RejoinedRoom {
505    pub room: proto::Room,
506    pub rejoined_projects: Vec<RejoinedProject>,
507    pub reshared_projects: Vec<ResharedProject>,
508    pub channel: Option<channel::Model>,
509}
510
511pub struct ResharedProject {
512    pub id: ProjectId,
513    pub old_connection_id: ConnectionId,
514    pub collaborators: Vec<ProjectCollaborator>,
515    pub worktrees: Vec<proto::WorktreeMetadata>,
516}
517
518pub struct RejoinedProject {
519    pub id: ProjectId,
520    pub old_connection_id: ConnectionId,
521    pub collaborators: Vec<ProjectCollaborator>,
522    pub worktrees: Vec<RejoinedWorktree>,
523    pub updated_repositories: Vec<proto::UpdateRepository>,
524    pub removed_repositories: Vec<u64>,
525    pub language_servers: Vec<LanguageServer>,
526}
527
528impl RejoinedProject {
529    pub fn to_proto(&self) -> proto::RejoinedProject {
530        let (language_servers, language_server_capabilities) = self
531            .language_servers
532            .clone()
533            .into_iter()
534            .map(|server| (server.server, server.capabilities))
535            .unzip();
536        proto::RejoinedProject {
537            id: self.id.to_proto(),
538            worktrees: self
539                .worktrees
540                .iter()
541                .map(|worktree| proto::WorktreeMetadata {
542                    id: worktree.id,
543                    root_name: worktree.root_name.clone(),
544                    visible: worktree.visible,
545                    abs_path: worktree.abs_path.clone(),
546                })
547                .collect(),
548            collaborators: self
549                .collaborators
550                .iter()
551                .map(|collaborator| collaborator.to_proto())
552                .collect(),
553            language_servers,
554            language_server_capabilities,
555        }
556    }
557}
558
559#[derive(Debug)]
560pub struct RejoinedWorktree {
561    pub id: u64,
562    pub abs_path: String,
563    pub root_name: String,
564    pub visible: bool,
565    pub updated_entries: Vec<proto::Entry>,
566    pub removed_entries: Vec<u64>,
567    pub updated_repositories: Vec<proto::RepositoryEntry>,
568    pub removed_repositories: Vec<u64>,
569    pub diagnostic_summaries: Vec<proto::DiagnosticSummary>,
570    pub settings_files: Vec<WorktreeSettingsFile>,
571    pub scan_id: u64,
572    pub completed_scan_id: u64,
573}
574
575pub struct LeftRoom {
576    pub room: proto::Room,
577    pub channel: Option<channel::Model>,
578    pub left_projects: HashMap<ProjectId, LeftProject>,
579    pub canceled_calls_to_user_ids: Vec<UserId>,
580    pub deleted: bool,
581}
582
583pub struct RefreshedRoom {
584    pub room: proto::Room,
585    pub channel: Option<channel::Model>,
586    pub stale_participant_user_ids: Vec<UserId>,
587    pub canceled_calls_to_user_ids: Vec<UserId>,
588}
589
590pub struct RefreshedChannelBuffer {
591    pub connection_ids: Vec<ConnectionId>,
592    pub collaborators: Vec<proto::Collaborator>,
593}
594
595pub struct Project {
596    pub id: ProjectId,
597    pub role: ChannelRole,
598    pub collaborators: Vec<ProjectCollaborator>,
599    pub worktrees: BTreeMap<u64, Worktree>,
600    pub repositories: Vec<proto::UpdateRepository>,
601    pub language_servers: Vec<LanguageServer>,
602    pub path_style: PathStyle,
603}
604
605pub struct ProjectCollaborator {
606    pub connection_id: ConnectionId,
607    pub user_id: UserId,
608    pub replica_id: ReplicaId,
609    pub is_host: bool,
610    pub committer_name: Option<String>,
611    pub committer_email: Option<String>,
612}
613
614impl ProjectCollaborator {
615    pub fn to_proto(&self) -> proto::Collaborator {
616        proto::Collaborator {
617            peer_id: Some(self.connection_id.into()),
618            replica_id: self.replica_id.0 as u32,
619            user_id: self.user_id.to_proto(),
620            is_host: self.is_host,
621            committer_name: self.committer_name.clone(),
622            committer_email: self.committer_email.clone(),
623        }
624    }
625}
626
627#[derive(Debug, Clone)]
628pub struct LanguageServer {
629    pub server: proto::LanguageServer,
630    pub capabilities: String,
631}
632
633#[derive(Debug)]
634pub struct LeftProject {
635    pub id: ProjectId,
636    pub should_unshare: bool,
637    pub connection_ids: Vec<ConnectionId>,
638}
639
640pub struct Worktree {
641    pub id: u64,
642    pub abs_path: String,
643    pub root_name: String,
644    pub visible: bool,
645    pub entries: Vec<proto::Entry>,
646    pub legacy_repository_entries: BTreeMap<u64, proto::RepositoryEntry>,
647    pub diagnostic_summaries: Vec<proto::DiagnosticSummary>,
648    pub settings_files: Vec<WorktreeSettingsFile>,
649    pub scan_id: u64,
650    pub completed_scan_id: u64,
651}
652
653#[derive(Debug)]
654pub struct WorktreeSettingsFile {
655    pub path: String,
656    pub content: String,
657    pub kind: LocalSettingsKind,
658}
659
660pub struct NewExtensionVersion {
661    pub name: String,
662    pub version: semver::Version,
663    pub description: String,
664    pub authors: Vec<String>,
665    pub repository: String,
666    pub schema_version: i32,
667    pub wasm_api_version: Option<String>,
668    pub provides: BTreeSet<ExtensionProvides>,
669    pub published_at: PrimitiveDateTime,
670}
671
672pub struct ExtensionVersionConstraints {
673    pub schema_versions: RangeInclusive<i32>,
674    pub wasm_api_versions: RangeInclusive<SemanticVersion>,
675}
676
677impl LocalSettingsKind {
678    pub fn from_proto(proto_kind: proto::LocalSettingsKind) -> Self {
679        match proto_kind {
680            proto::LocalSettingsKind::Settings => Self::Settings,
681            proto::LocalSettingsKind::Tasks => Self::Tasks,
682            proto::LocalSettingsKind::Editorconfig => Self::Editorconfig,
683            proto::LocalSettingsKind::Debug => Self::Debug,
684        }
685    }
686
687    pub fn to_proto(self) -> proto::LocalSettingsKind {
688        match self {
689            Self::Settings => proto::LocalSettingsKind::Settings,
690            Self::Tasks => proto::LocalSettingsKind::Tasks,
691            Self::Editorconfig => proto::LocalSettingsKind::Editorconfig,
692            Self::Debug => proto::LocalSettingsKind::Debug,
693        }
694    }
695}
696
697fn db_status_to_proto(
698    entry: project_repository_statuses::Model,
699) -> anyhow::Result<proto::StatusEntry> {
700    use proto::git_file_status::{Tracked, Unmerged, Variant};
701
702    let (simple_status, variant) =
703        match (entry.status_kind, entry.first_status, entry.second_status) {
704            (StatusKind::Untracked, None, None) => (
705                proto::GitStatus::Added as i32,
706                Variant::Untracked(Default::default()),
707            ),
708            (StatusKind::Ignored, None, None) => (
709                proto::GitStatus::Added as i32,
710                Variant::Ignored(Default::default()),
711            ),
712            (StatusKind::Unmerged, Some(first_head), Some(second_head)) => (
713                proto::GitStatus::Conflict as i32,
714                Variant::Unmerged(Unmerged {
715                    first_head,
716                    second_head,
717                }),
718            ),
719            (StatusKind::Tracked, Some(index_status), Some(worktree_status)) => {
720                let simple_status = if worktree_status != proto::GitStatus::Unmodified as i32 {
721                    worktree_status
722                } else if index_status != proto::GitStatus::Unmodified as i32 {
723                    index_status
724                } else {
725                    proto::GitStatus::Unmodified as i32
726                };
727                (
728                    simple_status,
729                    Variant::Tracked(Tracked {
730                        index_status,
731                        worktree_status,
732                    }),
733                )
734            }
735            _ => {
736                anyhow::bail!("Unexpected combination of status fields: {entry:?}");
737            }
738        };
739    Ok(proto::StatusEntry {
740        repo_path: entry.repo_path,
741        simple_status,
742        status: Some(proto::GitFileStatus {
743            variant: Some(variant),
744        }),
745    })
746}
747
748fn proto_status_to_db(
749    status_entry: proto::StatusEntry,
750) -> (String, StatusKind, Option<i32>, Option<i32>) {
751    use proto::git_file_status::{Tracked, Unmerged, Variant};
752
753    let (status_kind, first_status, second_status) = status_entry
754        .status
755        .clone()
756        .and_then(|status| status.variant)
757        .map_or(
758            (StatusKind::Untracked, None, None),
759            |variant| match variant {
760                Variant::Untracked(_) => (StatusKind::Untracked, None, None),
761                Variant::Ignored(_) => (StatusKind::Ignored, None, None),
762                Variant::Unmerged(Unmerged {
763                    first_head,
764                    second_head,
765                }) => (StatusKind::Unmerged, Some(first_head), Some(second_head)),
766                Variant::Tracked(Tracked {
767                    index_status,
768                    worktree_status,
769                }) => (
770                    StatusKind::Tracked,
771                    Some(index_status),
772                    Some(worktree_status),
773                ),
774            },
775        );
776    (
777        status_entry.repo_path,
778        status_kind,
779        first_status,
780        second_status,
781    )
782}