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