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::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 observed_channel_messages: Vec<proto::ChannelMessageId>,
490    pub latest_buffer_versions: Vec<proto::ChannelBufferVersion>,
491    pub latest_channel_messages: Vec<proto::ChannelMessageId>,
492}
493
494#[derive(Debug)]
495pub struct RejoinedChannelBuffer {
496    pub buffer: proto::RejoinedChannelBuffer,
497    pub old_connection_id: ConnectionId,
498}
499
500#[derive(Clone)]
501pub struct JoinRoom {
502    pub room: proto::Room,
503    pub channel: Option<channel::Model>,
504}
505
506pub struct RejoinedRoom {
507    pub room: proto::Room,
508    pub rejoined_projects: Vec<RejoinedProject>,
509    pub reshared_projects: Vec<ResharedProject>,
510    pub channel: Option<channel::Model>,
511}
512
513pub struct ResharedProject {
514    pub id: ProjectId,
515    pub old_connection_id: ConnectionId,
516    pub collaborators: Vec<ProjectCollaborator>,
517    pub worktrees: Vec<proto::WorktreeMetadata>,
518}
519
520pub struct RejoinedProject {
521    pub id: ProjectId,
522    pub old_connection_id: ConnectionId,
523    pub collaborators: Vec<ProjectCollaborator>,
524    pub worktrees: Vec<RejoinedWorktree>,
525    pub updated_repositories: Vec<proto::UpdateRepository>,
526    pub removed_repositories: Vec<u64>,
527    pub language_servers: Vec<LanguageServer>,
528}
529
530impl RejoinedProject {
531    pub fn to_proto(&self) -> proto::RejoinedProject {
532        let (language_servers, language_server_capabilities) = self
533            .language_servers
534            .clone()
535            .into_iter()
536            .map(|server| (server.server, server.capabilities))
537            .unzip();
538        proto::RejoinedProject {
539            id: self.id.to_proto(),
540            worktrees: self
541                .worktrees
542                .iter()
543                .map(|worktree| proto::WorktreeMetadata {
544                    id: worktree.id,
545                    root_name: worktree.root_name.clone(),
546                    visible: worktree.visible,
547                    abs_path: worktree.abs_path.clone(),
548                })
549                .collect(),
550            collaborators: self
551                .collaborators
552                .iter()
553                .map(|collaborator| collaborator.to_proto())
554                .collect(),
555            language_servers,
556            language_server_capabilities,
557        }
558    }
559}
560
561#[derive(Debug)]
562pub struct RejoinedWorktree {
563    pub id: u64,
564    pub abs_path: String,
565    pub root_name: String,
566    pub visible: bool,
567    pub updated_entries: Vec<proto::Entry>,
568    pub removed_entries: Vec<u64>,
569    pub updated_repositories: Vec<proto::RepositoryEntry>,
570    pub removed_repositories: Vec<u64>,
571    pub diagnostic_summaries: Vec<proto::DiagnosticSummary>,
572    pub settings_files: Vec<WorktreeSettingsFile>,
573    pub scan_id: u64,
574    pub completed_scan_id: u64,
575}
576
577pub struct LeftRoom {
578    pub room: proto::Room,
579    pub channel: Option<channel::Model>,
580    pub left_projects: HashMap<ProjectId, LeftProject>,
581    pub canceled_calls_to_user_ids: Vec<UserId>,
582    pub deleted: bool,
583}
584
585pub struct RefreshedRoom {
586    pub room: proto::Room,
587    pub channel: Option<channel::Model>,
588    pub stale_participant_user_ids: Vec<UserId>,
589    pub canceled_calls_to_user_ids: Vec<UserId>,
590}
591
592pub struct RefreshedChannelBuffer {
593    pub connection_ids: Vec<ConnectionId>,
594    pub collaborators: Vec<proto::Collaborator>,
595}
596
597pub struct Project {
598    pub id: ProjectId,
599    pub role: ChannelRole,
600    pub collaborators: Vec<ProjectCollaborator>,
601    pub worktrees: BTreeMap<u64, Worktree>,
602    pub repositories: Vec<proto::UpdateRepository>,
603    pub language_servers: Vec<LanguageServer>,
604}
605
606pub struct ProjectCollaborator {
607    pub connection_id: ConnectionId,
608    pub user_id: UserId,
609    pub replica_id: ReplicaId,
610    pub is_host: bool,
611    pub committer_name: Option<String>,
612    pub committer_email: Option<String>,
613}
614
615impl ProjectCollaborator {
616    pub fn to_proto(&self) -> proto::Collaborator {
617        proto::Collaborator {
618            peer_id: Some(self.connection_id.into()),
619            replica_id: self.replica_id.0 as u32,
620            user_id: self.user_id.to_proto(),
621            is_host: self.is_host,
622            committer_name: self.committer_name.clone(),
623            committer_email: self.committer_email.clone(),
624        }
625    }
626}
627
628#[derive(Debug, Clone)]
629pub struct LanguageServer {
630    pub server: proto::LanguageServer,
631    pub capabilities: String,
632}
633
634#[derive(Debug)]
635pub struct LeftProject {
636    pub id: ProjectId,
637    pub should_unshare: bool,
638    pub connection_ids: Vec<ConnectionId>,
639}
640
641pub struct Worktree {
642    pub id: u64,
643    pub abs_path: String,
644    pub root_name: String,
645    pub visible: bool,
646    pub entries: Vec<proto::Entry>,
647    pub legacy_repository_entries: BTreeMap<u64, proto::RepositoryEntry>,
648    pub diagnostic_summaries: Vec<proto::DiagnosticSummary>,
649    pub settings_files: Vec<WorktreeSettingsFile>,
650    pub scan_id: u64,
651    pub completed_scan_id: u64,
652}
653
654#[derive(Debug)]
655pub struct WorktreeSettingsFile {
656    pub path: String,
657    pub content: String,
658    pub kind: LocalSettingsKind,
659}
660
661pub struct NewExtensionVersion {
662    pub name: String,
663    pub version: semver::Version,
664    pub description: String,
665    pub authors: Vec<String>,
666    pub repository: String,
667    pub schema_version: i32,
668    pub wasm_api_version: Option<String>,
669    pub provides: BTreeSet<ExtensionProvides>,
670    pub published_at: PrimitiveDateTime,
671}
672
673pub struct ExtensionVersionConstraints {
674    pub schema_versions: RangeInclusive<i32>,
675    pub wasm_api_versions: RangeInclusive<SemanticVersion>,
676}
677
678impl LocalSettingsKind {
679    pub fn from_proto(proto_kind: proto::LocalSettingsKind) -> Self {
680        match proto_kind {
681            proto::LocalSettingsKind::Settings => Self::Settings,
682            proto::LocalSettingsKind::Tasks => Self::Tasks,
683            proto::LocalSettingsKind::Editorconfig => Self::Editorconfig,
684            proto::LocalSettingsKind::Debug => Self::Debug,
685        }
686    }
687
688    pub fn to_proto(self) -> proto::LocalSettingsKind {
689        match self {
690            Self::Settings => proto::LocalSettingsKind::Settings,
691            Self::Tasks => proto::LocalSettingsKind::Tasks,
692            Self::Editorconfig => proto::LocalSettingsKind::Editorconfig,
693            Self::Debug => proto::LocalSettingsKind::Debug,
694        }
695    }
696}
697
698fn db_status_to_proto(
699    entry: project_repository_statuses::Model,
700) -> anyhow::Result<proto::StatusEntry> {
701    use proto::git_file_status::{Tracked, Unmerged, Variant};
702
703    let (simple_status, variant) =
704        match (entry.status_kind, entry.first_status, entry.second_status) {
705            (StatusKind::Untracked, None, None) => (
706                proto::GitStatus::Added as i32,
707                Variant::Untracked(Default::default()),
708            ),
709            (StatusKind::Ignored, None, None) => (
710                proto::GitStatus::Added as i32,
711                Variant::Ignored(Default::default()),
712            ),
713            (StatusKind::Unmerged, Some(first_head), Some(second_head)) => (
714                proto::GitStatus::Conflict as i32,
715                Variant::Unmerged(Unmerged {
716                    first_head,
717                    second_head,
718                }),
719            ),
720            (StatusKind::Tracked, Some(index_status), Some(worktree_status)) => {
721                let simple_status = if worktree_status != proto::GitStatus::Unmodified as i32 {
722                    worktree_status
723                } else if index_status != proto::GitStatus::Unmodified as i32 {
724                    index_status
725                } else {
726                    proto::GitStatus::Unmodified as i32
727                };
728                (
729                    simple_status,
730                    Variant::Tracked(Tracked {
731                        index_status,
732                        worktree_status,
733                    }),
734                )
735            }
736            _ => {
737                anyhow::bail!("Unexpected combination of status fields: {entry:?}");
738            }
739        };
740    Ok(proto::StatusEntry {
741        repo_path: entry.repo_path,
742        simple_status,
743        status: Some(proto::GitFileStatus {
744            variant: Some(variant),
745        }),
746    })
747}
748
749fn proto_status_to_db(
750    status_entry: proto::StatusEntry,
751) -> (String, StatusKind, Option<i32>, Option<i32>) {
752    use proto::git_file_status::{Tracked, Unmerged, Variant};
753
754    let (status_kind, first_status, second_status) = status_entry
755        .status
756        .clone()
757        .and_then(|status| status.variant)
758        .map_or(
759            (StatusKind::Untracked, None, None),
760            |variant| match variant {
761                Variant::Untracked(_) => (StatusKind::Untracked, None, None),
762                Variant::Ignored(_) => (StatusKind::Ignored, None, None),
763                Variant::Unmerged(Unmerged {
764                    first_head,
765                    second_head,
766                }) => (StatusKind::Unmerged, Some(first_head), Some(second_head)),
767                Variant::Tracked(Tracked {
768                    index_status,
769                    worktree_status,
770                }) => (
771                    StatusKind::Tracked,
772                    Some(index_status),
773                    Some(worktree_status),
774                ),
775            },
776        );
777    (
778        status_entry.repo_path,
779        status_kind,
780        first_status,
781        second_status,
782    )
783}