db.rs

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