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 semver::Version;
 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 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            let test_options = self.test_options.as_ref().unwrap();
254            test_options.executor.simulate_random_delay().await;
255            let fail_probability = *test_options.query_failure_probability.lock();
256            if test_options.executor.rng().random_bool(fail_probability) {
257                return Err(anyhow!("simulated query failure"))?;
258            }
259
260            test_options.runtime.block_on(future)
261        }
262
263        #[cfg(not(test))]
264        {
265            future.await
266        }
267    }
268}
269
270/// A handle to a [`DatabaseTransaction`].
271pub struct TransactionHandle(pub(crate) Arc<Option<DatabaseTransaction>>);
272
273impl Deref for TransactionHandle {
274    type Target = DatabaseTransaction;
275
276    fn deref(&self) -> &Self::Target {
277        self.0.as_ref().as_ref().unwrap()
278    }
279}
280
281/// [`TransactionGuard`] keeps a database transaction alive until it is dropped.
282/// It wraps data that depends on the state of the database and prevents an additional
283/// transaction from starting that would invalidate that data.
284pub struct TransactionGuard<T> {
285    data: T,
286    _guard: OwnedMutexGuard<()>,
287    _not_send: PhantomData<Rc<()>>,
288}
289
290impl<T> Deref for TransactionGuard<T> {
291    type Target = T;
292
293    fn deref(&self) -> &T {
294        &self.data
295    }
296}
297
298impl<T> DerefMut for TransactionGuard<T> {
299    fn deref_mut(&mut self) -> &mut T {
300        &mut self.data
301    }
302}
303
304impl<T> TransactionGuard<T> {
305    /// Returns the inner value of the guard.
306    pub fn into_inner(self) -> T {
307        self.data
308    }
309}
310
311#[derive(Clone, Debug, PartialEq, Eq)]
312pub enum Contact {
313    Accepted { user_id: UserId, busy: bool },
314    Outgoing { user_id: UserId },
315    Incoming { user_id: UserId },
316}
317
318impl Contact {
319    pub fn user_id(&self) -> UserId {
320        match self {
321            Contact::Accepted { user_id, .. } => *user_id,
322            Contact::Outgoing { user_id } => *user_id,
323            Contact::Incoming { user_id, .. } => *user_id,
324        }
325    }
326}
327
328pub type NotificationBatch = Vec<(UserId, proto::Notification)>;
329
330pub struct CreatedChannelMessage {
331    pub message_id: MessageId,
332    pub participant_connection_ids: HashSet<ConnectionId>,
333    pub notifications: NotificationBatch,
334}
335
336pub struct UpdatedChannelMessage {
337    pub message_id: MessageId,
338    pub participant_connection_ids: Vec<ConnectionId>,
339    pub notifications: NotificationBatch,
340    pub reply_to_message_id: Option<MessageId>,
341    pub timestamp: PrimitiveDateTime,
342    pub deleted_mention_notification_ids: Vec<NotificationId>,
343    pub updated_mention_notifications: Vec<rpc::proto::Notification>,
344}
345
346#[derive(Clone, Debug, PartialEq, Eq, FromQueryResult, Serialize, Deserialize)]
347pub struct Invite {
348    pub email_address: String,
349    pub email_confirmation_code: String,
350}
351
352#[derive(Clone, Debug, Deserialize)]
353pub struct NewSignup {
354    pub email_address: String,
355    pub platform_mac: bool,
356    pub platform_windows: bool,
357    pub platform_linux: bool,
358    pub editor_features: Vec<String>,
359    pub programming_languages: Vec<String>,
360    pub device_id: Option<String>,
361    pub added_to_mailing_list: bool,
362    pub created_at: Option<DateTime>,
363}
364
365#[derive(Clone, Debug, PartialEq, Deserialize, Serialize, FromQueryResult)]
366pub struct WaitlistSummary {
367    pub count: i64,
368    pub linux_count: i64,
369    pub mac_count: i64,
370    pub windows_count: i64,
371    pub unknown_count: i64,
372}
373
374/// The parameters to create a new user.
375#[derive(Debug, Serialize, Deserialize)]
376pub struct NewUserParams {
377    pub github_login: String,
378    pub github_user_id: i32,
379}
380
381/// The result of creating a new user.
382#[derive(Debug)]
383pub struct NewUserResult {
384    pub user_id: UserId,
385}
386
387/// The result of updating a channel membership.
388#[derive(Debug)]
389pub struct MembershipUpdated {
390    pub channel_id: ChannelId,
391    pub new_channels: ChannelsForUser,
392    pub removed_channels: Vec<ChannelId>,
393}
394
395/// The result of setting a member's role.
396#[derive(Debug)]
397
398pub enum SetMemberRoleResult {
399    InviteUpdated(Channel),
400    MembershipUpdated(MembershipUpdated),
401}
402
403/// The result of inviting a member to a channel.
404#[derive(Debug)]
405pub struct InviteMemberResult {
406    pub channel: Channel,
407    pub notifications: NotificationBatch,
408}
409
410#[derive(Debug)]
411pub struct RespondToChannelInvite {
412    pub membership_update: Option<MembershipUpdated>,
413    pub notifications: NotificationBatch,
414}
415
416#[derive(Debug)]
417pub struct RemoveChannelMemberResult {
418    pub membership_update: MembershipUpdated,
419    pub notification_id: Option<NotificationId>,
420}
421
422#[derive(Debug, PartialEq, Eq, Hash)]
423pub struct Channel {
424    pub id: ChannelId,
425    pub name: String,
426    pub visibility: ChannelVisibility,
427    /// parent_path is the channel ids from the root to this one (not including this one)
428    pub parent_path: Vec<ChannelId>,
429    pub channel_order: i32,
430}
431
432impl Channel {
433    pub fn from_model(value: channel::Model) -> Self {
434        Channel {
435            id: value.id,
436            visibility: value.visibility,
437            name: value.clone().name,
438            parent_path: value.ancestors().collect(),
439            channel_order: value.channel_order,
440        }
441    }
442
443    pub fn to_proto(&self) -> proto::Channel {
444        proto::Channel {
445            id: self.id.to_proto(),
446            name: self.name.clone(),
447            visibility: self.visibility.into(),
448            parent_path: self.parent_path.iter().map(|c| c.to_proto()).collect(),
449            channel_order: self.channel_order,
450        }
451    }
452
453    pub fn root_id(&self) -> ChannelId {
454        self.parent_path.first().copied().unwrap_or(self.id)
455    }
456}
457
458#[derive(Debug, PartialEq, Eq, Hash)]
459pub struct ChannelMember {
460    pub role: ChannelRole,
461    pub user_id: UserId,
462    pub kind: proto::channel_member::Kind,
463}
464
465impl ChannelMember {
466    pub fn to_proto(&self) -> proto::ChannelMember {
467        proto::ChannelMember {
468            role: self.role.into(),
469            user_id: self.user_id.to_proto(),
470            kind: self.kind.into(),
471        }
472    }
473}
474
475#[derive(Debug, PartialEq)]
476pub struct ChannelsForUser {
477    pub channels: Vec<Channel>,
478    pub channel_memberships: Vec<channel_member::Model>,
479    pub channel_participants: HashMap<ChannelId, Vec<UserId>>,
480    pub invited_channels: Vec<Channel>,
481
482    pub observed_buffer_versions: Vec<proto::ChannelBufferVersion>,
483    pub latest_buffer_versions: Vec<proto::ChannelBufferVersion>,
484}
485
486#[derive(Debug)]
487pub struct RejoinedChannelBuffer {
488    pub buffer: proto::RejoinedChannelBuffer,
489    pub old_connection_id: ConnectionId,
490}
491
492#[derive(Clone)]
493pub struct JoinRoom {
494    pub room: proto::Room,
495    pub channel: Option<channel::Model>,
496}
497
498pub struct RejoinedRoom {
499    pub room: proto::Room,
500    pub rejoined_projects: Vec<RejoinedProject>,
501    pub reshared_projects: Vec<ResharedProject>,
502    pub channel: Option<channel::Model>,
503}
504
505pub struct ResharedProject {
506    pub id: ProjectId,
507    pub old_connection_id: ConnectionId,
508    pub collaborators: Vec<ProjectCollaborator>,
509    pub worktrees: Vec<proto::WorktreeMetadata>,
510}
511
512pub struct RejoinedProject {
513    pub id: ProjectId,
514    pub old_connection_id: ConnectionId,
515    pub collaborators: Vec<ProjectCollaborator>,
516    pub worktrees: Vec<RejoinedWorktree>,
517    pub updated_repositories: Vec<proto::UpdateRepository>,
518    pub removed_repositories: Vec<u64>,
519    pub language_servers: Vec<LanguageServer>,
520}
521
522impl RejoinedProject {
523    pub fn to_proto(&self) -> proto::RejoinedProject {
524        let (language_servers, language_server_capabilities) = self
525            .language_servers
526            .clone()
527            .into_iter()
528            .map(|server| (server.server, server.capabilities))
529            .unzip();
530        proto::RejoinedProject {
531            id: self.id.to_proto(),
532            worktrees: self
533                .worktrees
534                .iter()
535                .map(|worktree| proto::WorktreeMetadata {
536                    id: worktree.id,
537                    root_name: worktree.root_name.clone(),
538                    visible: worktree.visible,
539                    abs_path: worktree.abs_path.clone(),
540                })
541                .collect(),
542            collaborators: self
543                .collaborators
544                .iter()
545                .map(|collaborator| collaborator.to_proto())
546                .collect(),
547            language_servers,
548            language_server_capabilities,
549        }
550    }
551}
552
553#[derive(Debug)]
554pub struct RejoinedWorktree {
555    pub id: u64,
556    pub abs_path: String,
557    pub root_name: String,
558    pub visible: bool,
559    pub updated_entries: Vec<proto::Entry>,
560    pub removed_entries: Vec<u64>,
561    pub updated_repositories: Vec<proto::RepositoryEntry>,
562    pub removed_repositories: Vec<u64>,
563    pub diagnostic_summaries: Vec<proto::DiagnosticSummary>,
564    pub settings_files: Vec<WorktreeSettingsFile>,
565    pub scan_id: u64,
566    pub completed_scan_id: u64,
567}
568
569pub struct LeftRoom {
570    pub room: proto::Room,
571    pub channel: Option<channel::Model>,
572    pub left_projects: HashMap<ProjectId, LeftProject>,
573    pub canceled_calls_to_user_ids: Vec<UserId>,
574    pub deleted: bool,
575}
576
577pub struct RefreshedRoom {
578    pub room: proto::Room,
579    pub channel: Option<channel::Model>,
580    pub stale_participant_user_ids: Vec<UserId>,
581    pub canceled_calls_to_user_ids: Vec<UserId>,
582}
583
584pub struct RefreshedChannelBuffer {
585    pub connection_ids: Vec<ConnectionId>,
586    pub collaborators: Vec<proto::Collaborator>,
587}
588
589pub struct Project {
590    pub id: ProjectId,
591    pub role: ChannelRole,
592    pub collaborators: Vec<ProjectCollaborator>,
593    pub worktrees: BTreeMap<u64, Worktree>,
594    pub repositories: Vec<proto::UpdateRepository>,
595    pub language_servers: Vec<LanguageServer>,
596    pub path_style: PathStyle,
597}
598
599pub struct ProjectCollaborator {
600    pub connection_id: ConnectionId,
601    pub user_id: UserId,
602    pub replica_id: ReplicaId,
603    pub is_host: bool,
604    pub committer_name: Option<String>,
605    pub committer_email: Option<String>,
606}
607
608impl ProjectCollaborator {
609    pub fn to_proto(&self) -> proto::Collaborator {
610        proto::Collaborator {
611            peer_id: Some(self.connection_id.into()),
612            replica_id: self.replica_id.0 as u32,
613            user_id: self.user_id.to_proto(),
614            is_host: self.is_host,
615            committer_name: self.committer_name.clone(),
616            committer_email: self.committer_email.clone(),
617        }
618    }
619}
620
621#[derive(Debug, Clone)]
622pub struct LanguageServer {
623    pub server: proto::LanguageServer,
624    pub capabilities: String,
625}
626
627#[derive(Debug)]
628pub struct LeftProject {
629    pub id: ProjectId,
630    pub should_unshare: bool,
631    pub connection_ids: Vec<ConnectionId>,
632}
633
634pub struct Worktree {
635    pub id: u64,
636    pub abs_path: String,
637    pub root_name: String,
638    pub visible: bool,
639    pub entries: Vec<proto::Entry>,
640    pub legacy_repository_entries: BTreeMap<u64, proto::RepositoryEntry>,
641    pub diagnostic_summaries: Vec<proto::DiagnosticSummary>,
642    pub settings_files: Vec<WorktreeSettingsFile>,
643    pub scan_id: u64,
644    pub completed_scan_id: u64,
645}
646
647#[derive(Debug)]
648pub struct WorktreeSettingsFile {
649    pub path: String,
650    pub content: String,
651    pub kind: LocalSettingsKind,
652}
653
654pub struct NewExtensionVersion {
655    pub name: String,
656    pub version: semver::Version,
657    pub description: String,
658    pub authors: Vec<String>,
659    pub repository: String,
660    pub schema_version: i32,
661    pub wasm_api_version: Option<String>,
662    pub provides: BTreeSet<ExtensionProvides>,
663    pub published_at: PrimitiveDateTime,
664}
665
666pub struct ExtensionVersionConstraints {
667    pub schema_versions: RangeInclusive<i32>,
668    pub wasm_api_versions: RangeInclusive<semver::Version>,
669}
670
671impl LocalSettingsKind {
672    pub fn from_proto(proto_kind: proto::LocalSettingsKind) -> Self {
673        match proto_kind {
674            proto::LocalSettingsKind::Settings => Self::Settings,
675            proto::LocalSettingsKind::Tasks => Self::Tasks,
676            proto::LocalSettingsKind::Editorconfig => Self::Editorconfig,
677            proto::LocalSettingsKind::Debug => Self::Debug,
678        }
679    }
680
681    pub fn to_proto(self) -> proto::LocalSettingsKind {
682        match self {
683            Self::Settings => proto::LocalSettingsKind::Settings,
684            Self::Tasks => proto::LocalSettingsKind::Tasks,
685            Self::Editorconfig => proto::LocalSettingsKind::Editorconfig,
686            Self::Debug => proto::LocalSettingsKind::Debug,
687        }
688    }
689}
690
691fn db_status_to_proto(
692    entry: project_repository_statuses::Model,
693) -> anyhow::Result<proto::StatusEntry> {
694    use proto::git_file_status::{Tracked, Unmerged, Variant};
695
696    let (simple_status, variant) =
697        match (entry.status_kind, entry.first_status, entry.second_status) {
698            (StatusKind::Untracked, None, None) => (
699                proto::GitStatus::Added as i32,
700                Variant::Untracked(Default::default()),
701            ),
702            (StatusKind::Ignored, None, None) => (
703                proto::GitStatus::Added as i32,
704                Variant::Ignored(Default::default()),
705            ),
706            (StatusKind::Unmerged, Some(first_head), Some(second_head)) => (
707                proto::GitStatus::Conflict as i32,
708                Variant::Unmerged(Unmerged {
709                    first_head,
710                    second_head,
711                }),
712            ),
713            (StatusKind::Tracked, Some(index_status), Some(worktree_status)) => {
714                let simple_status = if worktree_status != proto::GitStatus::Unmodified as i32 {
715                    worktree_status
716                } else if index_status != proto::GitStatus::Unmodified as i32 {
717                    index_status
718                } else {
719                    proto::GitStatus::Unmodified as i32
720                };
721                (
722                    simple_status,
723                    Variant::Tracked(Tracked {
724                        index_status,
725                        worktree_status,
726                    }),
727                )
728            }
729            _ => {
730                anyhow::bail!("Unexpected combination of status fields: {entry:?}");
731            }
732        };
733    Ok(proto::StatusEntry {
734        repo_path: entry.repo_path,
735        simple_status,
736        status: Some(proto::GitFileStatus {
737            variant: Some(variant),
738        }),
739    })
740}
741
742fn proto_status_to_db(
743    status_entry: proto::StatusEntry,
744) -> (String, StatusKind, Option<i32>, Option<i32>) {
745    use proto::git_file_status::{Tracked, Unmerged, Variant};
746
747    let (status_kind, first_status, second_status) = status_entry
748        .status
749        .clone()
750        .and_then(|status| status.variant)
751        .map_or(
752            (StatusKind::Untracked, None, None),
753            |variant| match variant {
754                Variant::Untracked(_) => (StatusKind::Untracked, None, None),
755                Variant::Ignored(_) => (StatusKind::Ignored, None, None),
756                Variant::Unmerged(Unmerged {
757                    first_head,
758                    second_head,
759                }) => (StatusKind::Unmerged, Some(first_head), Some(second_head)),
760                Variant::Tracked(Tracked {
761                    index_status,
762                    worktree_status,
763                }) => (
764                    StatusKind::Tracked,
765                    Some(index_status),
766                    Some(worktree_status),
767                ),
768            },
769        );
770    (
771        status_entry.repo_path,
772        status_kind,
773        first_status,
774        second_status,
775    )
776}