worktree.rs

   1mod ignore;
   2mod worktree_settings;
   3#[cfg(test)]
   4mod worktree_tests;
   5
   6use ::ignore::gitignore::{Gitignore, GitignoreBuilder};
   7use anyhow::{Context as _, Result, anyhow};
   8use clock::ReplicaId;
   9use collections::{HashMap, HashSet, VecDeque};
  10use fs::{Fs, MTime, PathEvent, RemoveOptions, Watcher, copy_recursive, read_dir_items};
  11use futures::{
  12    FutureExt as _, Stream, StreamExt,
  13    channel::{
  14        mpsc::{self, UnboundedSender},
  15        oneshot,
  16    },
  17    select_biased,
  18    task::Poll,
  19};
  20use fuzzy::CharBag;
  21use git::{
  22    COMMIT_MESSAGE, DOT_GIT, FSMONITOR_DAEMON, GITIGNORE, INDEX_LOCK, LFS_DIR, status::GitSummary,
  23};
  24use gpui::{
  25    App, AppContext as _, AsyncApp, BackgroundExecutor, Context, Entity, EventEmitter, Task,
  26};
  27use ignore::IgnoreStack;
  28use language::DiskState;
  29
  30use parking_lot::Mutex;
  31use paths::{local_settings_folder_name, local_vscode_folder_name};
  32use postage::{
  33    barrier,
  34    prelude::{Sink as _, Stream as _},
  35    watch,
  36};
  37use rpc::{
  38    AnyProtoClient,
  39    proto::{self, split_worktree_update},
  40};
  41pub use settings::WorktreeId;
  42use settings::{Settings, SettingsLocation, SettingsStore};
  43use smallvec::{SmallVec, smallvec};
  44use smol::channel::{self, Sender};
  45use std::{
  46    any::Any,
  47    borrow::Borrow as _,
  48    cmp::Ordering,
  49    collections::hash_map,
  50    convert::TryFrom,
  51    ffi::OsStr,
  52    fmt,
  53    future::Future,
  54    mem::{self},
  55    ops::{Deref, DerefMut},
  56    path::{Path, PathBuf},
  57    pin::Pin,
  58    sync::{
  59        Arc,
  60        atomic::{AtomicUsize, Ordering::SeqCst},
  61    },
  62    time::{Duration, Instant},
  63};
  64use sum_tree::{Bias, Dimensions, Edit, KeyedItem, SeekTarget, SumTree, Summary, TreeMap, TreeSet};
  65use text::{LineEnding, Rope};
  66use util::{
  67    ResultExt, debug_panic, maybe,
  68    paths::{PathMatcher, PathStyle, SanitizedPath, home_dir},
  69    rel_path::RelPath,
  70};
  71pub use worktree_settings::WorktreeSettings;
  72
  73pub const FS_WATCH_LATENCY: Duration = Duration::from_millis(100);
  74
  75/// A set of local or remote files that are being opened as part of a project.
  76/// Responsible for tracking related FS (for local)/collab (for remote) events and corresponding updates.
  77/// Stores git repositories data and the diagnostics for the file(s).
  78///
  79/// Has an absolute path, and may be set to be visible in Zed UI or not.
  80/// May correspond to a directory or a single file.
  81/// Possible examples:
  82/// * a drag and dropped file — may be added as an invisible, "ephemeral" entry to the current worktree
  83/// * a directory opened in Zed — may be added as a visible entry to the current worktree
  84///
  85/// Uses [`Entry`] to track the state of each file/directory, can look up absolute paths for entries.
  86pub enum Worktree {
  87    Local(LocalWorktree),
  88    Remote(RemoteWorktree),
  89}
  90
  91/// An entry, created in the worktree.
  92#[derive(Debug)]
  93pub enum CreatedEntry {
  94    /// Got created and indexed by the worktree, receiving a corresponding entry.
  95    Included(Entry),
  96    /// Got created, but not indexed due to falling under exclusion filters.
  97    Excluded { abs_path: PathBuf },
  98}
  99
 100pub struct LoadedFile {
 101    pub file: Arc<File>,
 102    pub text: String,
 103}
 104
 105pub struct LoadedBinaryFile {
 106    pub file: Arc<File>,
 107    pub content: Vec<u8>,
 108}
 109
 110impl fmt::Debug for LoadedBinaryFile {
 111    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
 112        f.debug_struct("LoadedBinaryFile")
 113            .field("file", &self.file)
 114            .field("content_bytes", &self.content.len())
 115            .finish()
 116    }
 117}
 118
 119pub struct LocalWorktree {
 120    snapshot: LocalSnapshot,
 121    scan_requests_tx: channel::Sender<ScanRequest>,
 122    path_prefixes_to_scan_tx: channel::Sender<PathPrefixScanRequest>,
 123    is_scanning: (watch::Sender<bool>, watch::Receiver<bool>),
 124    _background_scanner_tasks: Vec<Task<()>>,
 125    update_observer: Option<UpdateObservationState>,
 126    fs: Arc<dyn Fs>,
 127    fs_case_sensitive: bool,
 128    visible: bool,
 129    next_entry_id: Arc<AtomicUsize>,
 130    settings: WorktreeSettings,
 131    share_private_files: bool,
 132}
 133
 134pub struct PathPrefixScanRequest {
 135    path: Arc<RelPath>,
 136    done: SmallVec<[barrier::Sender; 1]>,
 137}
 138
 139struct ScanRequest {
 140    relative_paths: Vec<Arc<RelPath>>,
 141    done: SmallVec<[barrier::Sender; 1]>,
 142}
 143
 144pub struct RemoteWorktree {
 145    snapshot: Snapshot,
 146    background_snapshot: Arc<Mutex<(Snapshot, Vec<proto::UpdateWorktree>)>>,
 147    project_id: u64,
 148    client: AnyProtoClient,
 149    file_scan_inclusions: PathMatcher,
 150    updates_tx: Option<UnboundedSender<proto::UpdateWorktree>>,
 151    update_observer: Option<mpsc::UnboundedSender<proto::UpdateWorktree>>,
 152    snapshot_subscriptions: VecDeque<(usize, oneshot::Sender<()>)>,
 153    replica_id: ReplicaId,
 154    visible: bool,
 155    disconnected: bool,
 156}
 157
 158#[derive(Clone)]
 159pub struct Snapshot {
 160    id: WorktreeId,
 161    /// The absolute path of the worktree root.
 162    abs_path: Arc<SanitizedPath>,
 163    path_style: PathStyle,
 164    root_name: Arc<RelPath>,
 165    root_char_bag: CharBag,
 166    entries_by_path: SumTree<Entry>,
 167    entries_by_id: SumTree<PathEntry>,
 168    always_included_entries: Vec<Arc<RelPath>>,
 169
 170    /// A number that increases every time the worktree begins scanning
 171    /// a set of paths from the filesystem. This scanning could be caused
 172    /// by some operation performed on the worktree, such as reading or
 173    /// writing a file, or by an event reported by the filesystem.
 174    scan_id: usize,
 175
 176    /// The latest scan id that has completed, and whose preceding scans
 177    /// have all completed. The current `scan_id` could be more than one
 178    /// greater than the `completed_scan_id` if operations are performed
 179    /// on the worktree while it is processing a file-system event.
 180    completed_scan_id: usize,
 181}
 182
 183/// This path corresponds to the 'content path' of a repository in relation
 184/// to Zed's project root.
 185/// In the majority of the cases, this is the folder that contains the .git folder.
 186/// But if a sub-folder of a git repository is opened, this corresponds to the
 187/// project root and the .git folder is located in a parent directory.
 188#[derive(Clone, Debug, Ord, PartialOrd, Eq, PartialEq, Hash)]
 189pub enum WorkDirectory {
 190    InProject {
 191        relative_path: Arc<RelPath>,
 192    },
 193    AboveProject {
 194        absolute_path: Arc<Path>,
 195        location_in_repo: Arc<Path>,
 196    },
 197}
 198
 199impl WorkDirectory {
 200    fn path_key(&self) -> PathKey {
 201        match self {
 202            WorkDirectory::InProject { relative_path } => PathKey(relative_path.clone()),
 203            WorkDirectory::AboveProject { .. } => PathKey(RelPath::empty().into()),
 204        }
 205    }
 206
 207    /// Returns true if the given path is a child of the work directory.
 208    ///
 209    /// Note that the path may not be a member of this repository, if there
 210    /// is a repository in a directory between these two paths
 211    /// external .git folder in a parent folder of the project root.
 212    #[track_caller]
 213    pub fn directory_contains(&self, path: &RelPath) -> bool {
 214        match self {
 215            WorkDirectory::InProject { relative_path } => path.starts_with(relative_path),
 216            WorkDirectory::AboveProject { .. } => true,
 217        }
 218    }
 219}
 220
 221impl Default for WorkDirectory {
 222    fn default() -> Self {
 223        Self::InProject {
 224            relative_path: Arc::from(RelPath::empty()),
 225        }
 226    }
 227}
 228
 229#[derive(Clone)]
 230pub struct LocalSnapshot {
 231    snapshot: Snapshot,
 232    global_gitignore: Option<Arc<Gitignore>>,
 233    /// All of the gitignore files in the worktree, indexed by their absolute path.
 234    /// The boolean indicates whether the gitignore needs to be updated.
 235    ignores_by_parent_abs_path: HashMap<Arc<Path>, (Arc<Gitignore>, bool)>,
 236    /// All of the git repositories in the worktree, indexed by the project entry
 237    /// id of their parent directory.
 238    git_repositories: TreeMap<ProjectEntryId, LocalRepositoryEntry>,
 239    /// The file handle of the worktree root
 240    /// (so we can find it after it's been moved)
 241    root_file_handle: Option<Arc<dyn fs::FileHandle>>,
 242    executor: BackgroundExecutor,
 243}
 244
 245struct BackgroundScannerState {
 246    snapshot: LocalSnapshot,
 247    scanned_dirs: HashSet<ProjectEntryId>,
 248    path_prefixes_to_scan: HashSet<Arc<RelPath>>,
 249    paths_to_scan: HashSet<Arc<RelPath>>,
 250    /// The ids of all of the entries that were removed from the snapshot
 251    /// as part of the current update. These entry ids may be re-used
 252    /// if the same inode is discovered at a new path, or if the given
 253    /// path is re-created after being deleted.
 254    removed_entries: HashMap<u64, Entry>,
 255    changed_paths: Vec<Arc<RelPath>>,
 256    prev_snapshot: Snapshot,
 257}
 258
 259#[derive(Debug, Clone)]
 260struct LocalRepositoryEntry {
 261    work_directory_id: ProjectEntryId,
 262    work_directory: WorkDirectory,
 263    work_directory_abs_path: Arc<Path>,
 264    git_dir_scan_id: usize,
 265    /// Absolute path to the original .git entry that caused us to create this repository.
 266    ///
 267    /// This is normally a directory, but may be a "gitfile" that points to a directory elsewhere
 268    /// (whose path we then store in `repository_dir_abs_path`).
 269    dot_git_abs_path: Arc<Path>,
 270    /// Absolute path to the "commondir" for this repository.
 271    ///
 272    /// This is always a directory. For a normal repository, this is the same as dot_git_abs_path,
 273    /// but in the case of a submodule or a worktree it is the path to the "parent" .git directory
 274    /// from which the submodule/worktree was derived.
 275    common_dir_abs_path: Arc<Path>,
 276    /// Absolute path to the directory holding the repository's state.
 277    ///
 278    /// For a normal repository, this is a directory and coincides with `dot_git_abs_path` and
 279    /// `common_dir_abs_path`. For a submodule or worktree, this is some subdirectory of the
 280    /// commondir like `/project/.git/modules/foo`.
 281    repository_dir_abs_path: Arc<Path>,
 282}
 283
 284impl sum_tree::Item for LocalRepositoryEntry {
 285    type Summary = PathSummary<sum_tree::NoSummary>;
 286
 287    fn summary(&self, _: <Self::Summary as Summary>::Context<'_>) -> Self::Summary {
 288        PathSummary {
 289            max_path: self.work_directory.path_key().0,
 290            item_summary: sum_tree::NoSummary,
 291        }
 292    }
 293}
 294
 295impl KeyedItem for LocalRepositoryEntry {
 296    type Key = PathKey;
 297
 298    fn key(&self) -> Self::Key {
 299        self.work_directory.path_key()
 300    }
 301}
 302
 303impl Deref for LocalRepositoryEntry {
 304    type Target = WorkDirectory;
 305
 306    fn deref(&self) -> &Self::Target {
 307        &self.work_directory
 308    }
 309}
 310
 311impl Deref for LocalSnapshot {
 312    type Target = Snapshot;
 313
 314    fn deref(&self) -> &Self::Target {
 315        &self.snapshot
 316    }
 317}
 318
 319impl DerefMut for LocalSnapshot {
 320    fn deref_mut(&mut self) -> &mut Self::Target {
 321        &mut self.snapshot
 322    }
 323}
 324
 325enum ScanState {
 326    Started,
 327    Updated {
 328        snapshot: LocalSnapshot,
 329        changes: UpdatedEntriesSet,
 330        barrier: SmallVec<[barrier::Sender; 1]>,
 331        scanning: bool,
 332    },
 333    RootUpdated {
 334        new_path: Arc<SanitizedPath>,
 335    },
 336}
 337
 338struct UpdateObservationState {
 339    snapshots_tx: mpsc::UnboundedSender<(LocalSnapshot, UpdatedEntriesSet)>,
 340    resume_updates: watch::Sender<()>,
 341    _maintain_remote_snapshot: Task<Option<()>>,
 342}
 343
 344#[derive(Clone)]
 345pub enum Event {
 346    UpdatedEntries(UpdatedEntriesSet),
 347    UpdatedGitRepositories(UpdatedGitRepositoriesSet),
 348    DeletedEntry(ProjectEntryId),
 349}
 350
 351impl EventEmitter<Event> for Worktree {}
 352
 353impl Worktree {
 354    pub async fn local(
 355        path: impl Into<Arc<Path>>,
 356        visible: bool,
 357        fs: Arc<dyn Fs>,
 358        next_entry_id: Arc<AtomicUsize>,
 359        cx: &mut AsyncApp,
 360    ) -> Result<Entity<Self>> {
 361        let abs_path = path.into();
 362        let metadata = fs
 363            .metadata(&abs_path)
 364            .await
 365            .context("failed to stat worktree path")?;
 366
 367        let fs_case_sensitive = fs.is_case_sensitive().await.unwrap_or_else(|e| {
 368            log::error!(
 369                "Failed to determine whether filesystem is case sensitive (falling back to true) due to error: {e:#}"
 370            );
 371            true
 372        });
 373
 374        let root_file_handle = if metadata.as_ref().is_some() {
 375            fs.open_handle(&abs_path)
 376                .await
 377                .with_context(|| {
 378                    format!(
 379                        "failed to open local worktree root at {}",
 380                        abs_path.display()
 381                    )
 382                })
 383                .log_err()
 384        } else {
 385            None
 386        };
 387
 388        cx.new(move |cx: &mut Context<Worktree>| {
 389            let mut snapshot = LocalSnapshot {
 390                ignores_by_parent_abs_path: Default::default(),
 391                global_gitignore: Default::default(),
 392                git_repositories: Default::default(),
 393                snapshot: Snapshot::new(
 394                    cx.entity_id().as_u64(),
 395                    abs_path
 396                        .file_name()
 397                        .and_then(|f| f.to_str())
 398                        .map_or(RelPath::empty().into(), |f| {
 399                            RelPath::unix(f).unwrap().into()
 400                        }),
 401                    abs_path.clone(),
 402                    PathStyle::local(),
 403                ),
 404                root_file_handle,
 405                executor: cx.background_executor().clone(),
 406            };
 407
 408            let worktree_id = snapshot.id();
 409            let settings_location = Some(SettingsLocation {
 410                worktree_id,
 411                path: RelPath::empty(),
 412            });
 413
 414            let settings = WorktreeSettings::get(settings_location, cx).clone();
 415            cx.observe_global::<SettingsStore>(move |this, cx| {
 416                if let Self::Local(this) = this {
 417                    let settings = WorktreeSettings::get(settings_location, cx).clone();
 418                    if this.settings != settings {
 419                        this.settings = settings;
 420                        this.restart_background_scanners(cx);
 421                    }
 422                }
 423            })
 424            .detach();
 425
 426            let share_private_files = false;
 427            if let Some(metadata) = metadata {
 428                let mut entry = Entry::new(
 429                    RelPath::empty().into(),
 430                    &metadata,
 431                    &next_entry_id,
 432                    snapshot.root_char_bag,
 433                    None,
 434                );
 435                if !metadata.is_dir {
 436                    if let Some(file_name) = abs_path.file_name()
 437                        && let Some(file_name) = file_name.to_str()
 438                        && let Ok(path) = RelPath::unix(file_name)
 439                    {
 440                        entry.is_private = !share_private_files && settings.is_path_private(path);
 441                    }
 442                }
 443                entry.is_hidden = abs_path
 444                    .file_name()
 445                    .and_then(|name| name.to_str())
 446                    .map_or(false, |name| is_path_hidden(name));
 447                snapshot.insert_entry(entry, fs.as_ref());
 448            }
 449
 450            let (scan_requests_tx, scan_requests_rx) = channel::unbounded();
 451            let (path_prefixes_to_scan_tx, path_prefixes_to_scan_rx) = channel::unbounded();
 452            let mut worktree = LocalWorktree {
 453                share_private_files,
 454                next_entry_id,
 455                snapshot,
 456                is_scanning: watch::channel_with(true),
 457                update_observer: None,
 458                scan_requests_tx,
 459                path_prefixes_to_scan_tx,
 460                _background_scanner_tasks: Vec::new(),
 461                fs,
 462                fs_case_sensitive,
 463                visible,
 464                settings,
 465            };
 466            worktree.start_background_scanner(scan_requests_rx, path_prefixes_to_scan_rx, cx);
 467            Worktree::Local(worktree)
 468        })
 469    }
 470
 471    pub fn remote(
 472        project_id: u64,
 473        replica_id: ReplicaId,
 474        worktree: proto::WorktreeMetadata,
 475        client: AnyProtoClient,
 476        path_style: PathStyle,
 477        cx: &mut App,
 478    ) -> Entity<Self> {
 479        cx.new(|cx: &mut Context<Self>| {
 480            let snapshot = Snapshot::new(
 481                worktree.id,
 482                RelPath::from_proto(&worktree.root_name)
 483                    .unwrap_or_else(|_| RelPath::empty().into()),
 484                Path::new(&worktree.abs_path).into(),
 485                path_style,
 486            );
 487
 488            let background_snapshot = Arc::new(Mutex::new((
 489                snapshot.clone(),
 490                Vec::<proto::UpdateWorktree>::new(),
 491            )));
 492            let (background_updates_tx, mut background_updates_rx) =
 493                mpsc::unbounded::<proto::UpdateWorktree>();
 494            let (mut snapshot_updated_tx, mut snapshot_updated_rx) = watch::channel();
 495
 496            let worktree_id = snapshot.id();
 497            let settings_location = Some(SettingsLocation {
 498                worktree_id,
 499                path: RelPath::empty(),
 500            });
 501
 502            let settings = WorktreeSettings::get(settings_location, cx).clone();
 503            let worktree = RemoteWorktree {
 504                client,
 505                project_id,
 506                replica_id,
 507                snapshot,
 508                file_scan_inclusions: settings.file_scan_inclusions.clone(),
 509                background_snapshot: background_snapshot.clone(),
 510                updates_tx: Some(background_updates_tx),
 511                update_observer: None,
 512                snapshot_subscriptions: Default::default(),
 513                visible: worktree.visible,
 514                disconnected: false,
 515            };
 516
 517            // Apply updates to a separate snapshot in a background task, then
 518            // send them to a foreground task which updates the model.
 519            cx.background_spawn(async move {
 520                while let Some(update) = background_updates_rx.next().await {
 521                    {
 522                        let mut lock = background_snapshot.lock();
 523                        lock.0
 524                            .apply_remote_update(update.clone(), &settings.file_scan_inclusions);
 525                        lock.1.push(update);
 526                    }
 527                    snapshot_updated_tx.send(()).await.ok();
 528                }
 529            })
 530            .detach();
 531
 532            // On the foreground task, update to the latest snapshot and notify
 533            // any update observer of all updates that led to that snapshot.
 534            cx.spawn(async move |this, cx| {
 535                while (snapshot_updated_rx.recv().await).is_some() {
 536                    this.update(cx, |this, cx| {
 537                        let mut entries_changed = false;
 538                        let this = this.as_remote_mut().unwrap();
 539                        {
 540                            let mut lock = this.background_snapshot.lock();
 541                            this.snapshot = lock.0.clone();
 542                            for update in lock.1.drain(..) {
 543                                entries_changed |= !update.updated_entries.is_empty()
 544                                    || !update.removed_entries.is_empty();
 545                                if let Some(tx) = &this.update_observer {
 546                                    tx.unbounded_send(update).ok();
 547                                }
 548                            }
 549                        };
 550
 551                        if entries_changed {
 552                            cx.emit(Event::UpdatedEntries(Arc::default()));
 553                        }
 554                        cx.notify();
 555                        while let Some((scan_id, _)) = this.snapshot_subscriptions.front() {
 556                            if this.observed_snapshot(*scan_id) {
 557                                let (_, tx) = this.snapshot_subscriptions.pop_front().unwrap();
 558                                let _ = tx.send(());
 559                            } else {
 560                                break;
 561                            }
 562                        }
 563                    })?;
 564                }
 565                anyhow::Ok(())
 566            })
 567            .detach();
 568
 569            Worktree::Remote(worktree)
 570        })
 571    }
 572
 573    pub fn as_local(&self) -> Option<&LocalWorktree> {
 574        if let Worktree::Local(worktree) = self {
 575            Some(worktree)
 576        } else {
 577            None
 578        }
 579    }
 580
 581    pub fn as_remote(&self) -> Option<&RemoteWorktree> {
 582        if let Worktree::Remote(worktree) = self {
 583            Some(worktree)
 584        } else {
 585            None
 586        }
 587    }
 588
 589    pub fn as_local_mut(&mut self) -> Option<&mut LocalWorktree> {
 590        if let Worktree::Local(worktree) = self {
 591            Some(worktree)
 592        } else {
 593            None
 594        }
 595    }
 596
 597    pub fn as_remote_mut(&mut self) -> Option<&mut RemoteWorktree> {
 598        if let Worktree::Remote(worktree) = self {
 599            Some(worktree)
 600        } else {
 601            None
 602        }
 603    }
 604
 605    pub fn is_local(&self) -> bool {
 606        matches!(self, Worktree::Local(_))
 607    }
 608
 609    pub fn is_remote(&self) -> bool {
 610        !self.is_local()
 611    }
 612
 613    pub fn settings_location(&self, _: &Context<Self>) -> SettingsLocation<'static> {
 614        SettingsLocation {
 615            worktree_id: self.id(),
 616            path: RelPath::empty(),
 617        }
 618    }
 619
 620    pub fn snapshot(&self) -> Snapshot {
 621        match self {
 622            Worktree::Local(worktree) => worktree.snapshot.snapshot.clone(),
 623            Worktree::Remote(worktree) => worktree.snapshot.clone(),
 624        }
 625    }
 626
 627    pub fn scan_id(&self) -> usize {
 628        match self {
 629            Worktree::Local(worktree) => worktree.snapshot.scan_id,
 630            Worktree::Remote(worktree) => worktree.snapshot.scan_id,
 631        }
 632    }
 633
 634    pub fn metadata_proto(&self) -> proto::WorktreeMetadata {
 635        proto::WorktreeMetadata {
 636            id: self.id().to_proto(),
 637            root_name: self.root_name().to_proto(),
 638            visible: self.is_visible(),
 639            abs_path: self.abs_path().to_string_lossy().into_owned(),
 640        }
 641    }
 642
 643    pub fn completed_scan_id(&self) -> usize {
 644        match self {
 645            Worktree::Local(worktree) => worktree.snapshot.completed_scan_id,
 646            Worktree::Remote(worktree) => worktree.snapshot.completed_scan_id,
 647        }
 648    }
 649
 650    pub fn is_visible(&self) -> bool {
 651        match self {
 652            Worktree::Local(worktree) => worktree.visible,
 653            Worktree::Remote(worktree) => worktree.visible,
 654        }
 655    }
 656
 657    pub fn replica_id(&self) -> ReplicaId {
 658        match self {
 659            Worktree::Local(_) => ReplicaId::LOCAL,
 660            Worktree::Remote(worktree) => worktree.replica_id,
 661        }
 662    }
 663
 664    pub fn abs_path(&self) -> Arc<Path> {
 665        match self {
 666            Worktree::Local(worktree) => SanitizedPath::cast_arc(worktree.abs_path.clone()),
 667            Worktree::Remote(worktree) => SanitizedPath::cast_arc(worktree.abs_path.clone()),
 668        }
 669    }
 670
 671    pub fn root_file(&self, cx: &Context<Self>) -> Option<Arc<File>> {
 672        let entry = self.root_entry()?;
 673        Some(File::for_entry(entry.clone(), cx.entity()))
 674    }
 675
 676    pub fn observe_updates<F, Fut>(&mut self, project_id: u64, cx: &Context<Worktree>, callback: F)
 677    where
 678        F: 'static + Send + Fn(proto::UpdateWorktree) -> Fut,
 679        Fut: 'static + Send + Future<Output = bool>,
 680    {
 681        match self {
 682            Worktree::Local(this) => this.observe_updates(project_id, cx, callback),
 683            Worktree::Remote(this) => this.observe_updates(project_id, cx, callback),
 684        }
 685    }
 686
 687    pub fn stop_observing_updates(&mut self) {
 688        match self {
 689            Worktree::Local(this) => {
 690                this.update_observer.take();
 691            }
 692            Worktree::Remote(this) => {
 693                this.update_observer.take();
 694            }
 695        }
 696    }
 697
 698    #[cfg(any(test, feature = "test-support"))]
 699    pub fn has_update_observer(&self) -> bool {
 700        match self {
 701            Worktree::Local(this) => this.update_observer.is_some(),
 702            Worktree::Remote(this) => this.update_observer.is_some(),
 703        }
 704    }
 705
 706    pub fn load_file(&self, path: &RelPath, cx: &Context<Worktree>) -> Task<Result<LoadedFile>> {
 707        match self {
 708            Worktree::Local(this) => this.load_file(path, cx),
 709            Worktree::Remote(_) => {
 710                Task::ready(Err(anyhow!("remote worktrees can't yet load files")))
 711            }
 712        }
 713    }
 714
 715    pub fn load_binary_file(
 716        &self,
 717        path: &RelPath,
 718        cx: &Context<Worktree>,
 719    ) -> Task<Result<LoadedBinaryFile>> {
 720        match self {
 721            Worktree::Local(this) => this.load_binary_file(path, cx),
 722            Worktree::Remote(this) => this.load_binary_file(path, cx),
 723        }
 724    }
 725
 726    pub fn write_file(
 727        &self,
 728        path: Arc<RelPath>,
 729        text: Rope,
 730        line_ending: LineEnding,
 731        cx: &Context<Worktree>,
 732    ) -> Task<Result<Arc<File>>> {
 733        match self {
 734            Worktree::Local(this) => this.write_file(path, text, line_ending, cx),
 735            Worktree::Remote(_) => {
 736                Task::ready(Err(anyhow!("remote worktree can't yet write files")))
 737            }
 738        }
 739    }
 740
 741    pub fn create_entry(
 742        &mut self,
 743        path: Arc<RelPath>,
 744        is_directory: bool,
 745        content: Option<Vec<u8>>,
 746        cx: &Context<Worktree>,
 747    ) -> Task<Result<CreatedEntry>> {
 748        let worktree_id = self.id();
 749        match self {
 750            Worktree::Local(this) => this.create_entry(path, is_directory, content, cx),
 751            Worktree::Remote(this) => {
 752                let project_id = this.project_id;
 753                let request = this.client.request(proto::CreateProjectEntry {
 754                    worktree_id: worktree_id.to_proto(),
 755                    project_id,
 756                    path: path.as_ref().to_proto(),
 757                    content,
 758                    is_directory,
 759                });
 760                cx.spawn(async move |this, cx| {
 761                    let response = request.await?;
 762                    match response.entry {
 763                        Some(entry) => this
 764                            .update(cx, |worktree, cx| {
 765                                worktree.as_remote_mut().unwrap().insert_entry(
 766                                    entry,
 767                                    response.worktree_scan_id as usize,
 768                                    cx,
 769                                )
 770                            })?
 771                            .await
 772                            .map(CreatedEntry::Included),
 773                        None => {
 774                            let abs_path =
 775                                this.read_with(cx, |worktree, _| worktree.absolutize(&path))?;
 776                            Ok(CreatedEntry::Excluded { abs_path })
 777                        }
 778                    }
 779                })
 780            }
 781        }
 782    }
 783
 784    pub fn delete_entry(
 785        &mut self,
 786        entry_id: ProjectEntryId,
 787        trash: bool,
 788        cx: &mut Context<Worktree>,
 789    ) -> Option<Task<Result<()>>> {
 790        let task = match self {
 791            Worktree::Local(this) => this.delete_entry(entry_id, trash, cx),
 792            Worktree::Remote(this) => this.delete_entry(entry_id, trash, cx),
 793        }?;
 794
 795        let entry = match &*self {
 796            Worktree::Local(this) => this.entry_for_id(entry_id),
 797            Worktree::Remote(this) => this.entry_for_id(entry_id),
 798        }?;
 799
 800        let mut ids = vec![entry_id];
 801        let path = &*entry.path;
 802
 803        self.get_children_ids_recursive(path, &mut ids);
 804
 805        for id in ids {
 806            cx.emit(Event::DeletedEntry(id));
 807        }
 808        Some(task)
 809    }
 810
 811    fn get_children_ids_recursive(&self, path: &RelPath, ids: &mut Vec<ProjectEntryId>) {
 812        let children_iter = self.child_entries(path);
 813        for child in children_iter {
 814            ids.push(child.id);
 815            self.get_children_ids_recursive(&child.path, ids);
 816        }
 817    }
 818
 819    // pub fn rename_entry(
 820    //     &mut self,
 821    //     entry_id: ProjectEntryId,
 822    //     new_path: Arc<RelPath>,
 823    //     cx: &Context<Self>,
 824    // ) -> Task<Result<CreatedEntry>> {
 825    //     match self {
 826    //         Worktree::Local(this) => this.rename_entry(entry_id, new_path, cx),
 827    //         Worktree::Remote(this) => this.rename_entry(entry_id, new_path, cx),
 828    //     }
 829    // }
 830
 831    pub fn copy_external_entries(
 832        &mut self,
 833        target_directory: Arc<RelPath>,
 834        paths: Vec<Arc<Path>>,
 835        fs: Arc<dyn Fs>,
 836        cx: &Context<Worktree>,
 837    ) -> Task<Result<Vec<ProjectEntryId>>> {
 838        match self {
 839            Worktree::Local(this) => this.copy_external_entries(target_directory, paths, cx),
 840            Worktree::Remote(this) => this.copy_external_entries(target_directory, paths, fs, cx),
 841        }
 842    }
 843
 844    pub fn expand_entry(
 845        &mut self,
 846        entry_id: ProjectEntryId,
 847        cx: &Context<Worktree>,
 848    ) -> Option<Task<Result<()>>> {
 849        match self {
 850            Worktree::Local(this) => this.expand_entry(entry_id, cx),
 851            Worktree::Remote(this) => {
 852                let response = this.client.request(proto::ExpandProjectEntry {
 853                    project_id: this.project_id,
 854                    entry_id: entry_id.to_proto(),
 855                });
 856                Some(cx.spawn(async move |this, cx| {
 857                    let response = response.await?;
 858                    this.update(cx, |this, _| {
 859                        this.as_remote_mut()
 860                            .unwrap()
 861                            .wait_for_snapshot(response.worktree_scan_id as usize)
 862                    })?
 863                    .await?;
 864                    Ok(())
 865                }))
 866            }
 867        }
 868    }
 869
 870    pub fn expand_all_for_entry(
 871        &mut self,
 872        entry_id: ProjectEntryId,
 873        cx: &Context<Worktree>,
 874    ) -> Option<Task<Result<()>>> {
 875        match self {
 876            Worktree::Local(this) => this.expand_all_for_entry(entry_id, cx),
 877            Worktree::Remote(this) => {
 878                let response = this.client.request(proto::ExpandAllForProjectEntry {
 879                    project_id: this.project_id,
 880                    entry_id: entry_id.to_proto(),
 881                });
 882                Some(cx.spawn(async move |this, cx| {
 883                    let response = response.await?;
 884                    this.update(cx, |this, _| {
 885                        this.as_remote_mut()
 886                            .unwrap()
 887                            .wait_for_snapshot(response.worktree_scan_id as usize)
 888                    })?
 889                    .await?;
 890                    Ok(())
 891                }))
 892            }
 893        }
 894    }
 895
 896    pub async fn handle_create_entry(
 897        this: Entity<Self>,
 898        request: proto::CreateProjectEntry,
 899        mut cx: AsyncApp,
 900    ) -> Result<proto::ProjectEntryResponse> {
 901        let (scan_id, entry) = this.update(&mut cx, |this, cx| {
 902            anyhow::Ok((
 903                this.scan_id(),
 904                this.create_entry(
 905                    RelPath::from_proto(&request.path).with_context(|| {
 906                        format!("received invalid relative path {:?}", request.path)
 907                    })?,
 908                    request.is_directory,
 909                    request.content,
 910                    cx,
 911                ),
 912            ))
 913        })??;
 914        Ok(proto::ProjectEntryResponse {
 915            entry: match &entry.await? {
 916                CreatedEntry::Included(entry) => Some(entry.into()),
 917                CreatedEntry::Excluded { .. } => None,
 918            },
 919            worktree_scan_id: scan_id as u64,
 920        })
 921    }
 922
 923    pub async fn handle_delete_entry(
 924        this: Entity<Self>,
 925        request: proto::DeleteProjectEntry,
 926        mut cx: AsyncApp,
 927    ) -> Result<proto::ProjectEntryResponse> {
 928        let (scan_id, task) = this.update(&mut cx, |this, cx| {
 929            (
 930                this.scan_id(),
 931                this.delete_entry(
 932                    ProjectEntryId::from_proto(request.entry_id),
 933                    request.use_trash,
 934                    cx,
 935                ),
 936            )
 937        })?;
 938        task.context("invalid entry")?.await?;
 939        Ok(proto::ProjectEntryResponse {
 940            entry: None,
 941            worktree_scan_id: scan_id as u64,
 942        })
 943    }
 944
 945    pub async fn handle_expand_entry(
 946        this: Entity<Self>,
 947        request: proto::ExpandProjectEntry,
 948        mut cx: AsyncApp,
 949    ) -> Result<proto::ExpandProjectEntryResponse> {
 950        let task = this.update(&mut cx, |this, cx| {
 951            this.expand_entry(ProjectEntryId::from_proto(request.entry_id), cx)
 952        })?;
 953        task.context("no such entry")?.await?;
 954        let scan_id = this.read_with(&cx, |this, _| this.scan_id())?;
 955        Ok(proto::ExpandProjectEntryResponse {
 956            worktree_scan_id: scan_id as u64,
 957        })
 958    }
 959
 960    pub async fn handle_expand_all_for_entry(
 961        this: Entity<Self>,
 962        request: proto::ExpandAllForProjectEntry,
 963        mut cx: AsyncApp,
 964    ) -> Result<proto::ExpandAllForProjectEntryResponse> {
 965        let task = this.update(&mut cx, |this, cx| {
 966            this.expand_all_for_entry(ProjectEntryId::from_proto(request.entry_id), cx)
 967        })?;
 968        task.context("no such entry")?.await?;
 969        let scan_id = this.read_with(&cx, |this, _| this.scan_id())?;
 970        Ok(proto::ExpandAllForProjectEntryResponse {
 971            worktree_scan_id: scan_id as u64,
 972        })
 973    }
 974
 975    pub fn is_single_file(&self) -> bool {
 976        self.root_dir().is_none()
 977    }
 978
 979    /// For visible worktrees, returns the path with the worktree name as the first component.
 980    /// Otherwise, returns an absolute path.
 981    pub fn full_path(&self, worktree_relative_path: &RelPath) -> PathBuf {
 982        if self.is_visible() {
 983            self.root_name()
 984                .join(worktree_relative_path)
 985                .display(self.path_style)
 986                .to_string()
 987                .into()
 988        } else {
 989            let full_path = self.abs_path();
 990            let mut full_path_string = if self.is_local()
 991                && let Ok(stripped) = full_path.strip_prefix(home_dir())
 992            {
 993                self.path_style
 994                    .join("~", &*stripped.to_string_lossy())
 995                    .unwrap()
 996            } else {
 997                full_path.to_string_lossy().into_owned()
 998            };
 999
1000            if worktree_relative_path.components().next().is_some() {
1001                full_path_string.push_str(self.path_style.separator());
1002                full_path_string.push_str(&worktree_relative_path.display(self.path_style));
1003            }
1004
1005            full_path_string.into()
1006        }
1007    }
1008}
1009
1010impl LocalWorktree {
1011    pub fn fs(&self) -> &Arc<dyn Fs> {
1012        &self.fs
1013    }
1014
1015    pub fn is_path_private(&self, path: &RelPath) -> bool {
1016        !self.share_private_files && self.settings.is_path_private(path)
1017    }
1018
1019    pub fn fs_is_case_sensitive(&self) -> bool {
1020        self.fs_case_sensitive
1021    }
1022
1023    fn restart_background_scanners(&mut self, cx: &Context<Worktree>) {
1024        let (scan_requests_tx, scan_requests_rx) = channel::unbounded();
1025        let (path_prefixes_to_scan_tx, path_prefixes_to_scan_rx) = channel::unbounded();
1026        self.scan_requests_tx = scan_requests_tx;
1027        self.path_prefixes_to_scan_tx = path_prefixes_to_scan_tx;
1028
1029        self.start_background_scanner(scan_requests_rx, path_prefixes_to_scan_rx, cx);
1030        let always_included_entries = mem::take(&mut self.snapshot.always_included_entries);
1031        log::debug!(
1032            "refreshing entries for the following always included paths: {:?}",
1033            always_included_entries
1034        );
1035
1036        // Cleans up old always included entries to ensure they get updated properly. Otherwise,
1037        // nested always included entries may not get updated and will result in out-of-date info.
1038        self.refresh_entries_for_paths(always_included_entries);
1039    }
1040
1041    fn start_background_scanner(
1042        &mut self,
1043        scan_requests_rx: channel::Receiver<ScanRequest>,
1044        path_prefixes_to_scan_rx: channel::Receiver<PathPrefixScanRequest>,
1045        cx: &Context<Worktree>,
1046    ) {
1047        let snapshot = self.snapshot();
1048        let share_private_files = self.share_private_files;
1049        let next_entry_id = self.next_entry_id.clone();
1050        let fs = self.fs.clone();
1051        let settings = self.settings.clone();
1052        let (scan_states_tx, mut scan_states_rx) = mpsc::unbounded();
1053        let background_scanner = cx.background_spawn({
1054            let abs_path = snapshot.abs_path.as_path().to_path_buf();
1055            let background = cx.background_executor().clone();
1056            async move {
1057                let (events, watcher) = fs.watch(&abs_path, FS_WATCH_LATENCY).await;
1058                let fs_case_sensitive = fs.is_case_sensitive().await.unwrap_or_else(|e| {
1059                    log::error!("Failed to determine whether filesystem is case sensitive: {e:#}");
1060                    true
1061                });
1062
1063                let mut scanner = BackgroundScanner {
1064                    fs,
1065                    fs_case_sensitive,
1066                    status_updates_tx: scan_states_tx,
1067                    executor: background,
1068                    scan_requests_rx,
1069                    path_prefixes_to_scan_rx,
1070                    next_entry_id,
1071                    state: async_lock::Mutex::new(BackgroundScannerState {
1072                        prev_snapshot: snapshot.snapshot.clone(),
1073                        snapshot,
1074                        scanned_dirs: Default::default(),
1075                        path_prefixes_to_scan: Default::default(),
1076                        paths_to_scan: Default::default(),
1077                        removed_entries: Default::default(),
1078                        changed_paths: Default::default(),
1079                    }),
1080                    phase: BackgroundScannerPhase::InitialScan,
1081                    share_private_files,
1082                    settings,
1083                    watcher,
1084                };
1085
1086                scanner
1087                    .run(Box::pin(events.map(|events| events.into_iter().collect())))
1088                    .await;
1089            }
1090        });
1091        let scan_state_updater = cx.spawn(async move |this, cx| {
1092            while let Some((state, this)) = scan_states_rx.next().await.zip(this.upgrade()) {
1093                this.update(cx, |this, cx| {
1094                    let this = this.as_local_mut().unwrap();
1095                    match state {
1096                        ScanState::Started => {
1097                            *this.is_scanning.0.borrow_mut() = true;
1098                        }
1099                        ScanState::Updated {
1100                            snapshot,
1101                            changes,
1102                            barrier,
1103                            scanning,
1104                        } => {
1105                            *this.is_scanning.0.borrow_mut() = scanning;
1106                            this.set_snapshot(snapshot, changes, cx);
1107                            drop(barrier);
1108                        }
1109                        ScanState::RootUpdated { new_path } => {
1110                            this.update_abs_path_and_refresh(new_path, cx);
1111                        }
1112                    }
1113                })
1114                .ok();
1115            }
1116        });
1117        self._background_scanner_tasks = vec![background_scanner, scan_state_updater];
1118        *self.is_scanning.0.borrow_mut() = true;
1119    }
1120
1121    fn set_snapshot(
1122        &mut self,
1123        mut new_snapshot: LocalSnapshot,
1124        entry_changes: UpdatedEntriesSet,
1125        cx: &mut Context<Worktree>,
1126    ) {
1127        let repo_changes = self.changed_repos(&self.snapshot, &mut new_snapshot);
1128        self.snapshot = new_snapshot;
1129
1130        if let Some(share) = self.update_observer.as_mut() {
1131            share
1132                .snapshots_tx
1133                .unbounded_send((self.snapshot.clone(), entry_changes.clone()))
1134                .ok();
1135        }
1136
1137        if !entry_changes.is_empty() {
1138            cx.emit(Event::UpdatedEntries(entry_changes));
1139        }
1140        if !repo_changes.is_empty() {
1141            cx.emit(Event::UpdatedGitRepositories(repo_changes));
1142        }
1143    }
1144
1145    fn changed_repos(
1146        &self,
1147        old_snapshot: &LocalSnapshot,
1148        new_snapshot: &mut LocalSnapshot,
1149    ) -> UpdatedGitRepositoriesSet {
1150        let mut changes = Vec::new();
1151        let mut old_repos = old_snapshot.git_repositories.iter().peekable();
1152        let new_repos = new_snapshot.git_repositories.clone();
1153        let mut new_repos = new_repos.iter().peekable();
1154
1155        loop {
1156            match (new_repos.peek().map(clone), old_repos.peek().map(clone)) {
1157                (Some((new_entry_id, new_repo)), Some((old_entry_id, old_repo))) => {
1158                    match Ord::cmp(&new_entry_id, &old_entry_id) {
1159                        Ordering::Less => {
1160                            changes.push(UpdatedGitRepository {
1161                                work_directory_id: new_entry_id,
1162                                old_work_directory_abs_path: None,
1163                                new_work_directory_abs_path: Some(
1164                                    new_repo.work_directory_abs_path.clone(),
1165                                ),
1166                                dot_git_abs_path: Some(new_repo.dot_git_abs_path.clone()),
1167                                repository_dir_abs_path: Some(
1168                                    new_repo.repository_dir_abs_path.clone(),
1169                                ),
1170                                common_dir_abs_path: Some(new_repo.common_dir_abs_path.clone()),
1171                            });
1172                            new_repos.next();
1173                        }
1174                        Ordering::Equal => {
1175                            if new_repo.git_dir_scan_id != old_repo.git_dir_scan_id
1176                                || new_repo.work_directory_abs_path
1177                                    != old_repo.work_directory_abs_path
1178                            {
1179                                changes.push(UpdatedGitRepository {
1180                                    work_directory_id: new_entry_id,
1181                                    old_work_directory_abs_path: Some(
1182                                        old_repo.work_directory_abs_path.clone(),
1183                                    ),
1184                                    new_work_directory_abs_path: Some(
1185                                        new_repo.work_directory_abs_path.clone(),
1186                                    ),
1187                                    dot_git_abs_path: Some(new_repo.dot_git_abs_path.clone()),
1188                                    repository_dir_abs_path: Some(
1189                                        new_repo.repository_dir_abs_path.clone(),
1190                                    ),
1191                                    common_dir_abs_path: Some(new_repo.common_dir_abs_path.clone()),
1192                                });
1193                            }
1194                            new_repos.next();
1195                            old_repos.next();
1196                        }
1197                        Ordering::Greater => {
1198                            changes.push(UpdatedGitRepository {
1199                                work_directory_id: old_entry_id,
1200                                old_work_directory_abs_path: Some(
1201                                    old_repo.work_directory_abs_path.clone(),
1202                                ),
1203                                new_work_directory_abs_path: None,
1204                                dot_git_abs_path: None,
1205                                repository_dir_abs_path: None,
1206                                common_dir_abs_path: None,
1207                            });
1208                            old_repos.next();
1209                        }
1210                    }
1211                }
1212                (Some((entry_id, repo)), None) => {
1213                    changes.push(UpdatedGitRepository {
1214                        work_directory_id: entry_id,
1215                        old_work_directory_abs_path: None,
1216                        new_work_directory_abs_path: Some(repo.work_directory_abs_path.clone()),
1217                        dot_git_abs_path: Some(repo.dot_git_abs_path.clone()),
1218                        repository_dir_abs_path: Some(repo.repository_dir_abs_path.clone()),
1219                        common_dir_abs_path: Some(repo.common_dir_abs_path.clone()),
1220                    });
1221                    new_repos.next();
1222                }
1223                (None, Some((entry_id, repo))) => {
1224                    changes.push(UpdatedGitRepository {
1225                        work_directory_id: entry_id,
1226                        old_work_directory_abs_path: Some(repo.work_directory_abs_path.clone()),
1227                        new_work_directory_abs_path: None,
1228                        dot_git_abs_path: Some(repo.dot_git_abs_path.clone()),
1229                        repository_dir_abs_path: Some(repo.repository_dir_abs_path.clone()),
1230                        common_dir_abs_path: Some(repo.common_dir_abs_path.clone()),
1231                    });
1232                    old_repos.next();
1233                }
1234                (None, None) => break,
1235            }
1236        }
1237
1238        fn clone<T: Clone, U: Clone>(value: &(&T, &U)) -> (T, U) {
1239            (value.0.clone(), value.1.clone())
1240        }
1241
1242        changes.into()
1243    }
1244
1245    pub fn scan_complete(&self) -> impl Future<Output = ()> + use<> {
1246        let mut is_scanning_rx = self.is_scanning.1.clone();
1247        async move {
1248            let mut is_scanning = *is_scanning_rx.borrow();
1249            while is_scanning {
1250                if let Some(value) = is_scanning_rx.recv().await {
1251                    is_scanning = value;
1252                } else {
1253                    break;
1254                }
1255            }
1256        }
1257    }
1258
1259    pub fn snapshot(&self) -> LocalSnapshot {
1260        self.snapshot.clone()
1261    }
1262
1263    pub fn settings(&self) -> WorktreeSettings {
1264        self.settings.clone()
1265    }
1266
1267    fn load_binary_file(
1268        &self,
1269        path: &RelPath,
1270        cx: &Context<Worktree>,
1271    ) -> Task<Result<LoadedBinaryFile>> {
1272        let path = Arc::from(path);
1273        let abs_path = self.absolutize(&path);
1274        let fs = self.fs.clone();
1275        let entry = self.refresh_entry(path.clone(), None, cx);
1276        let is_private = self.is_path_private(&path);
1277
1278        let worktree = cx.weak_entity();
1279        cx.background_spawn(async move {
1280            let content = fs.load_bytes(&abs_path).await?;
1281
1282            let worktree = worktree.upgrade().context("worktree was dropped")?;
1283            let file = match entry.await? {
1284                Some(entry) => File::for_entry(entry, worktree),
1285                None => {
1286                    let metadata = fs
1287                        .metadata(&abs_path)
1288                        .await
1289                        .with_context(|| {
1290                            format!("Loading metadata for excluded file {abs_path:?}")
1291                        })?
1292                        .with_context(|| {
1293                            format!("Excluded file {abs_path:?} got removed during loading")
1294                        })?;
1295                    Arc::new(File {
1296                        entry_id: None,
1297                        worktree,
1298                        path,
1299                        disk_state: DiskState::Present {
1300                            mtime: metadata.mtime,
1301                        },
1302                        is_local: true,
1303                        is_private,
1304                    })
1305                }
1306            };
1307
1308            Ok(LoadedBinaryFile { file, content })
1309        })
1310    }
1311
1312    fn load_file(&self, path: &RelPath, cx: &Context<Worktree>) -> Task<Result<LoadedFile>> {
1313        let path = Arc::from(path);
1314        let abs_path = self.absolutize(&path);
1315        let fs = self.fs.clone();
1316        let entry = self.refresh_entry(path.clone(), None, cx);
1317        let is_private = self.is_path_private(path.as_ref());
1318
1319        let this = cx.weak_entity();
1320        cx.background_spawn(async move {
1321            // WARN: Temporary workaround for #27283.
1322            //       We are not efficient with our memory usage per file, and use in excess of 64GB for a 10GB file
1323            //       Therefore, as a temporary workaround to prevent system freezes, we just bail before opening a file
1324            //       if it is too large
1325            //       5GB seems to be more reasonable, peaking at ~16GB, while 6GB jumps up to >24GB which seems like a
1326            //       reasonable limit
1327            {
1328                const FILE_SIZE_MAX: u64 = 6 * 1024 * 1024 * 1024; // 6GB
1329                if let Ok(Some(metadata)) = fs.metadata(&abs_path).await
1330                    && metadata.len >= FILE_SIZE_MAX
1331                {
1332                    anyhow::bail!("File is too large to load");
1333                }
1334            }
1335            let text = fs.load(&abs_path).await?;
1336
1337            let worktree = this.upgrade().context("worktree was dropped")?;
1338            let file = match entry.await? {
1339                Some(entry) => File::for_entry(entry, worktree),
1340                None => {
1341                    let metadata = fs
1342                        .metadata(&abs_path)
1343                        .await
1344                        .with_context(|| {
1345                            format!("Loading metadata for excluded file {abs_path:?}")
1346                        })?
1347                        .with_context(|| {
1348                            format!("Excluded file {abs_path:?} got removed during loading")
1349                        })?;
1350                    Arc::new(File {
1351                        entry_id: None,
1352                        worktree,
1353                        path,
1354                        disk_state: DiskState::Present {
1355                            mtime: metadata.mtime,
1356                        },
1357                        is_local: true,
1358                        is_private,
1359                    })
1360                }
1361            };
1362
1363            Ok(LoadedFile { file, text })
1364        })
1365    }
1366
1367    /// Find the lowest path in the worktree's datastructures that is an ancestor
1368    fn lowest_ancestor(&self, path: &RelPath) -> Arc<RelPath> {
1369        let mut lowest_ancestor = None;
1370        for path in path.ancestors() {
1371            if self.entry_for_path(path).is_some() {
1372                lowest_ancestor = Some(path.into());
1373                break;
1374            }
1375        }
1376
1377        lowest_ancestor.unwrap_or_else(|| RelPath::empty().into())
1378    }
1379
1380    fn create_entry(
1381        &self,
1382        path: Arc<RelPath>,
1383        is_dir: bool,
1384        content: Option<Vec<u8>>,
1385        cx: &Context<Worktree>,
1386    ) -> Task<Result<CreatedEntry>> {
1387        let abs_path = self.absolutize(&path);
1388        let path_excluded = self.settings.is_path_excluded(&path);
1389        let fs = self.fs.clone();
1390        let task_abs_path = abs_path.clone();
1391        let write = cx.background_spawn(async move {
1392            if is_dir {
1393                fs.create_dir(&task_abs_path)
1394                    .await
1395                    .with_context(|| format!("creating directory {task_abs_path:?}"))
1396            } else {
1397                fs.write(&task_abs_path, content.as_deref().unwrap_or(&[]))
1398                    .await
1399                    .with_context(|| format!("creating file {task_abs_path:?}"))
1400            }
1401        });
1402
1403        let lowest_ancestor = self.lowest_ancestor(&path);
1404        cx.spawn(async move |this, cx| {
1405            write.await?;
1406            if path_excluded {
1407                return Ok(CreatedEntry::Excluded { abs_path });
1408            }
1409
1410            let (result, refreshes) = this.update(cx, |this, cx| {
1411                let mut refreshes = Vec::new();
1412                let refresh_paths = path.strip_prefix(&lowest_ancestor).unwrap();
1413                for refresh_path in refresh_paths.ancestors() {
1414                    if refresh_path == RelPath::empty() {
1415                        continue;
1416                    }
1417                    let refresh_full_path = lowest_ancestor.join(refresh_path);
1418
1419                    refreshes.push(this.as_local_mut().unwrap().refresh_entry(
1420                        refresh_full_path,
1421                        None,
1422                        cx,
1423                    ));
1424                }
1425                (
1426                    this.as_local_mut().unwrap().refresh_entry(path, None, cx),
1427                    refreshes,
1428                )
1429            })?;
1430            for refresh in refreshes {
1431                refresh.await.log_err();
1432            }
1433
1434            Ok(result
1435                .await?
1436                .map(CreatedEntry::Included)
1437                .unwrap_or_else(|| CreatedEntry::Excluded { abs_path }))
1438        })
1439    }
1440
1441    fn write_file(
1442        &self,
1443        path: Arc<RelPath>,
1444        text: Rope,
1445        line_ending: LineEnding,
1446        cx: &Context<Worktree>,
1447    ) -> Task<Result<Arc<File>>> {
1448        let fs = self.fs.clone();
1449        let is_private = self.is_path_private(&path);
1450        let abs_path = self.absolutize(&path);
1451
1452        let write = cx.background_spawn({
1453            let fs = fs.clone();
1454            let abs_path = abs_path.clone();
1455            async move { fs.save(&abs_path, &text, line_ending).await }
1456        });
1457
1458        cx.spawn(async move |this, cx| {
1459            write.await?;
1460            let entry = this
1461                .update(cx, |this, cx| {
1462                    this.as_local_mut()
1463                        .unwrap()
1464                        .refresh_entry(path.clone(), None, cx)
1465                })?
1466                .await?;
1467            let worktree = this.upgrade().context("worktree dropped")?;
1468            if let Some(entry) = entry {
1469                Ok(File::for_entry(entry, worktree))
1470            } else {
1471                let metadata = fs
1472                    .metadata(&abs_path)
1473                    .await
1474                    .with_context(|| {
1475                        format!("Fetching metadata after saving the excluded buffer {abs_path:?}")
1476                    })?
1477                    .with_context(|| {
1478                        format!("Excluded buffer {path:?} got removed during saving")
1479                    })?;
1480                Ok(Arc::new(File {
1481                    worktree,
1482                    path,
1483                    disk_state: DiskState::Present {
1484                        mtime: metadata.mtime,
1485                    },
1486                    entry_id: None,
1487                    is_local: true,
1488                    is_private,
1489                }))
1490            }
1491        })
1492    }
1493
1494    fn delete_entry(
1495        &self,
1496        entry_id: ProjectEntryId,
1497        trash: bool,
1498        cx: &Context<Worktree>,
1499    ) -> Option<Task<Result<()>>> {
1500        let entry = self.entry_for_id(entry_id)?.clone();
1501        let abs_path = self.absolutize(&entry.path);
1502        let fs = self.fs.clone();
1503
1504        let delete = cx.background_spawn(async move {
1505            if entry.is_file() {
1506                if trash {
1507                    fs.trash_file(&abs_path, Default::default()).await?;
1508                } else {
1509                    fs.remove_file(&abs_path, Default::default()).await?;
1510                }
1511            } else if trash {
1512                fs.trash_dir(
1513                    &abs_path,
1514                    RemoveOptions {
1515                        recursive: true,
1516                        ignore_if_not_exists: false,
1517                    },
1518                )
1519                .await?;
1520            } else {
1521                fs.remove_dir(
1522                    &abs_path,
1523                    RemoveOptions {
1524                        recursive: true,
1525                        ignore_if_not_exists: false,
1526                    },
1527                )
1528                .await?;
1529            }
1530            anyhow::Ok(entry.path)
1531        });
1532
1533        Some(cx.spawn(async move |this, cx| {
1534            let path = delete.await?;
1535            this.update(cx, |this, _| {
1536                this.as_local_mut()
1537                    .unwrap()
1538                    .refresh_entries_for_paths(vec![path])
1539            })?
1540            .recv()
1541            .await;
1542            Ok(())
1543        }))
1544    }
1545
1546    pub fn copy_external_entries(
1547        &self,
1548        target_directory: Arc<RelPath>,
1549        paths: Vec<Arc<Path>>,
1550        cx: &Context<Worktree>,
1551    ) -> Task<Result<Vec<ProjectEntryId>>> {
1552        let target_directory = self.absolutize(&target_directory);
1553        let worktree_path = self.abs_path().clone();
1554        let fs = self.fs.clone();
1555        let paths = paths
1556            .into_iter()
1557            .filter_map(|source| {
1558                let file_name = source.file_name()?;
1559                let mut target = target_directory.clone();
1560                target.push(file_name);
1561
1562                // Do not allow copying the same file to itself.
1563                if source.as_ref() != target.as_path() {
1564                    Some((source, target))
1565                } else {
1566                    None
1567                }
1568            })
1569            .collect::<Vec<_>>();
1570
1571        let paths_to_refresh = paths
1572            .iter()
1573            .filter_map(|(_, target)| {
1574                RelPath::new(
1575                    target.strip_prefix(&worktree_path).ok()?,
1576                    PathStyle::local(),
1577                )
1578                .ok()
1579                .map(|path| path.into_arc())
1580            })
1581            .collect::<Vec<_>>();
1582
1583        cx.spawn(async move |this, cx| {
1584            cx.background_spawn(async move {
1585                for (source, target) in paths {
1586                    copy_recursive(
1587                        fs.as_ref(),
1588                        &source,
1589                        &target,
1590                        fs::CopyOptions {
1591                            overwrite: true,
1592                            ..Default::default()
1593                        },
1594                    )
1595                    .await
1596                    .with_context(|| {
1597                        format!("Failed to copy file from {source:?} to {target:?}")
1598                    })?;
1599                }
1600                anyhow::Ok(())
1601            })
1602            .await
1603            .log_err();
1604            let mut refresh = cx.read_entity(
1605                &this.upgrade().with_context(|| "Dropped worktree")?,
1606                |this, _| {
1607                    anyhow::Ok::<postage::barrier::Receiver>(
1608                        this.as_local()
1609                            .with_context(|| "Worktree is not local")?
1610                            .refresh_entries_for_paths(paths_to_refresh.clone()),
1611                    )
1612                },
1613            )??;
1614
1615            cx.background_spawn(async move {
1616                refresh.next().await;
1617                anyhow::Ok(())
1618            })
1619            .await
1620            .log_err();
1621
1622            let this = this.upgrade().with_context(|| "Dropped worktree")?;
1623            cx.read_entity(&this, |this, _| {
1624                paths_to_refresh
1625                    .iter()
1626                    .filter_map(|path| Some(this.entry_for_path(path)?.id))
1627                    .collect()
1628            })
1629        })
1630    }
1631
1632    fn expand_entry(
1633        &self,
1634        entry_id: ProjectEntryId,
1635        cx: &Context<Worktree>,
1636    ) -> Option<Task<Result<()>>> {
1637        let path = self.entry_for_id(entry_id)?.path.clone();
1638        let mut refresh = self.refresh_entries_for_paths(vec![path]);
1639        Some(cx.background_spawn(async move {
1640            refresh.next().await;
1641            Ok(())
1642        }))
1643    }
1644
1645    fn expand_all_for_entry(
1646        &self,
1647        entry_id: ProjectEntryId,
1648        cx: &Context<Worktree>,
1649    ) -> Option<Task<Result<()>>> {
1650        let path = self.entry_for_id(entry_id).unwrap().path.clone();
1651        let mut rx = self.add_path_prefix_to_scan(path);
1652        Some(cx.background_spawn(async move {
1653            rx.next().await;
1654            Ok(())
1655        }))
1656    }
1657
1658    pub fn refresh_entries_for_paths(&self, paths: Vec<Arc<RelPath>>) -> barrier::Receiver {
1659        let (tx, rx) = barrier::channel();
1660        self.scan_requests_tx
1661            .try_send(ScanRequest {
1662                relative_paths: paths,
1663                done: smallvec![tx],
1664            })
1665            .ok();
1666        rx
1667    }
1668
1669    #[cfg(feature = "test-support")]
1670    pub fn manually_refresh_entries_for_paths(
1671        &self,
1672        paths: Vec<Arc<RelPath>>,
1673    ) -> barrier::Receiver {
1674        self.refresh_entries_for_paths(paths)
1675    }
1676
1677    pub fn add_path_prefix_to_scan(&self, path_prefix: Arc<RelPath>) -> barrier::Receiver {
1678        let (tx, rx) = barrier::channel();
1679        self.path_prefixes_to_scan_tx
1680            .try_send(PathPrefixScanRequest {
1681                path: path_prefix,
1682                done: smallvec![tx],
1683            })
1684            .ok();
1685        rx
1686    }
1687
1688    pub fn refresh_entry(
1689        &self,
1690        path: Arc<RelPath>,
1691        old_path: Option<Arc<RelPath>>,
1692        cx: &Context<Worktree>,
1693    ) -> Task<Result<Option<Entry>>> {
1694        if self.settings.is_path_excluded(&path) {
1695            return Task::ready(Ok(None));
1696        }
1697        let paths = if let Some(old_path) = old_path.as_ref() {
1698            vec![old_path.clone(), path.clone()]
1699        } else {
1700            vec![path.clone()]
1701        };
1702        let t0 = Instant::now();
1703        let mut refresh = self.refresh_entries_for_paths(paths);
1704        // todo(lw): Hot foreground spawn
1705        cx.spawn(async move |this, cx| {
1706            refresh.recv().await;
1707            log::trace!("refreshed entry {path:?} in {:?}", t0.elapsed());
1708            let new_entry = this.read_with(cx, |this, _| {
1709                this.entry_for_path(&path).cloned().with_context(|| {
1710                    format!("Could not find entry in worktree for {path:?} after refresh")
1711                })
1712            })??;
1713            Ok(Some(new_entry))
1714        })
1715    }
1716
1717    fn observe_updates<F, Fut>(&mut self, project_id: u64, cx: &Context<Worktree>, callback: F)
1718    where
1719        F: 'static + Send + Fn(proto::UpdateWorktree) -> Fut,
1720        Fut: 'static + Send + Future<Output = bool>,
1721    {
1722        if let Some(observer) = self.update_observer.as_mut() {
1723            *observer.resume_updates.borrow_mut() = ();
1724            return;
1725        }
1726
1727        let (resume_updates_tx, mut resume_updates_rx) = watch::channel::<()>();
1728        let (snapshots_tx, mut snapshots_rx) =
1729            mpsc::unbounded::<(LocalSnapshot, UpdatedEntriesSet)>();
1730        snapshots_tx
1731            .unbounded_send((self.snapshot(), Arc::default()))
1732            .ok();
1733
1734        let worktree_id = cx.entity_id().as_u64();
1735        let _maintain_remote_snapshot = cx.background_spawn(async move {
1736            let mut is_first = true;
1737            while let Some((snapshot, entry_changes)) = snapshots_rx.next().await {
1738                let update = if is_first {
1739                    is_first = false;
1740                    snapshot.build_initial_update(project_id, worktree_id)
1741                } else {
1742                    snapshot.build_update(project_id, worktree_id, entry_changes)
1743                };
1744
1745                for update in proto::split_worktree_update(update) {
1746                    let _ = resume_updates_rx.try_recv();
1747                    loop {
1748                        let result = callback(update.clone());
1749                        if result.await {
1750                            break;
1751                        } else {
1752                            log::info!("waiting to resume updates");
1753                            if resume_updates_rx.next().await.is_none() {
1754                                return Some(());
1755                            }
1756                        }
1757                    }
1758                }
1759            }
1760            Some(())
1761        });
1762
1763        self.update_observer = Some(UpdateObservationState {
1764            snapshots_tx,
1765            resume_updates: resume_updates_tx,
1766            _maintain_remote_snapshot,
1767        });
1768    }
1769
1770    pub fn share_private_files(&mut self, cx: &Context<Worktree>) {
1771        self.share_private_files = true;
1772        self.restart_background_scanners(cx);
1773    }
1774
1775    pub fn update_abs_path_and_refresh(
1776        &mut self,
1777        new_path: Arc<SanitizedPath>,
1778        cx: &Context<Worktree>,
1779    ) {
1780        self.snapshot.git_repositories = Default::default();
1781        self.snapshot.ignores_by_parent_abs_path = Default::default();
1782        let root_name = new_path
1783            .as_path()
1784            .file_name()
1785            .and_then(|f| f.to_str())
1786            .map_or(RelPath::empty().into(), |f| {
1787                RelPath::unix(f).unwrap().into()
1788            });
1789        self.snapshot.update_abs_path(new_path, root_name);
1790        self.restart_background_scanners(cx);
1791    }
1792}
1793
1794impl RemoteWorktree {
1795    pub fn project_id(&self) -> u64 {
1796        self.project_id
1797    }
1798
1799    pub fn client(&self) -> AnyProtoClient {
1800        self.client.clone()
1801    }
1802
1803    pub fn disconnected_from_host(&mut self) {
1804        self.updates_tx.take();
1805        self.snapshot_subscriptions.clear();
1806        self.disconnected = true;
1807    }
1808
1809    pub fn update_from_remote(&self, update: proto::UpdateWorktree) {
1810        if let Some(updates_tx) = &self.updates_tx {
1811            updates_tx
1812                .unbounded_send(update)
1813                .expect("consumer runs to completion");
1814        }
1815    }
1816
1817    fn observe_updates<F, Fut>(&mut self, project_id: u64, cx: &Context<Worktree>, callback: F)
1818    where
1819        F: 'static + Send + Fn(proto::UpdateWorktree) -> Fut,
1820        Fut: 'static + Send + Future<Output = bool>,
1821    {
1822        let (tx, mut rx) = mpsc::unbounded();
1823        let initial_update = self
1824            .snapshot
1825            .build_initial_update(project_id, self.id().to_proto());
1826        self.update_observer = Some(tx);
1827        cx.spawn(async move |this, cx| {
1828            let mut update = initial_update;
1829            'outer: loop {
1830                // SSH projects use a special project ID of 0, and we need to
1831                // remap it to the correct one here.
1832                update.project_id = project_id;
1833
1834                for chunk in split_worktree_update(update) {
1835                    if !callback(chunk).await {
1836                        break 'outer;
1837                    }
1838                }
1839
1840                if let Some(next_update) = rx.next().await {
1841                    update = next_update;
1842                } else {
1843                    break;
1844                }
1845            }
1846            this.update(cx, |this, _| {
1847                let this = this.as_remote_mut().unwrap();
1848                this.update_observer.take();
1849            })
1850        })
1851        .detach();
1852    }
1853
1854    fn observed_snapshot(&self, scan_id: usize) -> bool {
1855        self.completed_scan_id >= scan_id
1856    }
1857
1858    pub fn wait_for_snapshot(
1859        &mut self,
1860        scan_id: usize,
1861    ) -> impl Future<Output = Result<()>> + use<> {
1862        let (tx, rx) = oneshot::channel();
1863        if self.observed_snapshot(scan_id) {
1864            let _ = tx.send(());
1865        } else if self.disconnected {
1866            drop(tx);
1867        } else {
1868            match self
1869                .snapshot_subscriptions
1870                .binary_search_by_key(&scan_id, |probe| probe.0)
1871            {
1872                Ok(ix) | Err(ix) => self.snapshot_subscriptions.insert(ix, (scan_id, tx)),
1873            }
1874        }
1875
1876        async move {
1877            rx.await?;
1878            Ok(())
1879        }
1880    }
1881
1882    pub fn insert_entry(
1883        &mut self,
1884        entry: proto::Entry,
1885        scan_id: usize,
1886        cx: &Context<Worktree>,
1887    ) -> Task<Result<Entry>> {
1888        let wait_for_snapshot = self.wait_for_snapshot(scan_id);
1889        cx.spawn(async move |this, cx| {
1890            wait_for_snapshot.await?;
1891            this.update(cx, |worktree, _| {
1892                let worktree = worktree.as_remote_mut().unwrap();
1893                let snapshot = &mut worktree.background_snapshot.lock().0;
1894                let entry = snapshot.insert_entry(entry, &worktree.file_scan_inclusions);
1895                worktree.snapshot = snapshot.clone();
1896                entry
1897            })?
1898        })
1899    }
1900
1901    fn delete_entry(
1902        &self,
1903        entry_id: ProjectEntryId,
1904        trash: bool,
1905        cx: &Context<Worktree>,
1906    ) -> Option<Task<Result<()>>> {
1907        let response = self.client.request(proto::DeleteProjectEntry {
1908            project_id: self.project_id,
1909            entry_id: entry_id.to_proto(),
1910            use_trash: trash,
1911        });
1912        Some(cx.spawn(async move |this, cx| {
1913            let response = response.await?;
1914            let scan_id = response.worktree_scan_id as usize;
1915
1916            this.update(cx, move |this, _| {
1917                this.as_remote_mut().unwrap().wait_for_snapshot(scan_id)
1918            })?
1919            .await?;
1920
1921            this.update(cx, |this, _| {
1922                let this = this.as_remote_mut().unwrap();
1923                let snapshot = &mut this.background_snapshot.lock().0;
1924                snapshot.delete_entry(entry_id);
1925                this.snapshot = snapshot.clone();
1926            })
1927        }))
1928    }
1929
1930    // fn rename_entry(
1931    //     &self,
1932    //     entry_id: ProjectEntryId,
1933    //     new_path: impl Into<Arc<RelPath>>,
1934    //     cx: &Context<Worktree>,
1935    // ) -> Task<Result<CreatedEntry>> {
1936    //     let new_path: Arc<RelPath> = new_path.into();
1937    //     let response = self.client.request(proto::RenameProjectEntry {
1938    //         project_id: self.project_id,
1939    //         entry_id: entry_id.to_proto(),
1940    //         new_worktree_id: new_path.worktree_id,
1941    //         new_path: new_path.as_ref().to_proto(),
1942    //     });
1943    //     cx.spawn(async move |this, cx| {
1944    //         let response = response.await?;
1945    //         match response.entry {
1946    //             Some(entry) => this
1947    //                 .update(cx, |this, cx| {
1948    //                     this.as_remote_mut().unwrap().insert_entry(
1949    //                         entry,
1950    //                         response.worktree_scan_id as usize,
1951    //                         cx,
1952    //                     )
1953    //                 })?
1954    //                 .await
1955    //                 .map(CreatedEntry::Included),
1956    //             None => {
1957    //                 let abs_path =
1958    //                     this.read_with(cx, |worktree, _| worktree.absolutize(&new_path))?;
1959    //                 Ok(CreatedEntry::Excluded { abs_path })
1960    //             }
1961    //         }
1962    //     })
1963    // }
1964
1965    fn copy_external_entries(
1966        &self,
1967        target_directory: Arc<RelPath>,
1968        paths_to_copy: Vec<Arc<Path>>,
1969        local_fs: Arc<dyn Fs>,
1970        cx: &Context<Worktree>,
1971    ) -> Task<Result<Vec<ProjectEntryId>>> {
1972        let client = self.client.clone();
1973        let worktree_id = self.id().to_proto();
1974        let project_id = self.project_id;
1975
1976        cx.background_spawn(async move {
1977            let mut requests = Vec::new();
1978            for root_path_to_copy in paths_to_copy {
1979                let Some(filename) = root_path_to_copy
1980                    .file_name()
1981                    .and_then(|name| name.to_str())
1982                    .and_then(|filename| RelPath::unix(filename).ok())
1983                else {
1984                    continue;
1985                };
1986                for (abs_path, is_directory) in
1987                    read_dir_items(local_fs.as_ref(), &root_path_to_copy).await?
1988                {
1989                    let Some(relative_path) = abs_path
1990                        .strip_prefix(&root_path_to_copy)
1991                        .map_err(|e| anyhow::Error::from(e))
1992                        .and_then(|relative_path| RelPath::new(relative_path, PathStyle::local()))
1993                        .log_err()
1994                    else {
1995                        continue;
1996                    };
1997                    let content = if is_directory {
1998                        None
1999                    } else {
2000                        Some(local_fs.load_bytes(&abs_path).await?)
2001                    };
2002
2003                    let mut target_path = target_directory.join(filename);
2004                    if relative_path.file_name().is_some() {
2005                        target_path = target_path.join(&relative_path);
2006                    }
2007
2008                    requests.push(proto::CreateProjectEntry {
2009                        project_id,
2010                        worktree_id,
2011                        path: target_path.to_proto(),
2012                        is_directory,
2013                        content,
2014                    });
2015                }
2016            }
2017            requests.sort_unstable_by(|a, b| a.path.cmp(&b.path));
2018            requests.dedup();
2019
2020            let mut copied_entry_ids = Vec::new();
2021            for request in requests {
2022                let response = client.request(request).await?;
2023                copied_entry_ids.extend(response.entry.map(|e| ProjectEntryId::from_proto(e.id)));
2024            }
2025
2026            Ok(copied_entry_ids)
2027        })
2028    }
2029
2030    fn load_binary_file(
2031        &self,
2032        path: &RelPath,
2033        cx: &Context<Worktree>,
2034    ) -> Task<Result<LoadedBinaryFile>> {
2035        let path = Arc::from(path);
2036        let abs_path = self.absolutize(&path);
2037        // let fs = self.fs.clone();
2038        // let entry = self.refresh_entry(path.clone(), None, cx);
2039        // let is_private = self.is_path_private(&path);
2040        let response = self.client.request(proto::LoadBinaryFile{
2041            path: path.to_proto(),
2042            project_id: self.project_id(),
2043            worktree_id: self.id().to_proto(),
2044        });
2045        let worktree = cx.weak_entity();
2046        cx.background_spawn(async move {
2047            let proto::BinaryFileResponse { entry, content } = response.await?;
2048            let worktree = worktree.upgrade().context("worktree was dropped")?;
2049            // TODO: check is_private
2050            Ok(LoadedBinaryFile {
2051                file: File::for_entry(entry.unwrap().into(), worktree),
2052                content,
2053            })
2054        })
2055    }
2056}
2057
2058impl Snapshot {
2059    pub fn new(
2060        id: u64,
2061        root_name: Arc<RelPath>,
2062        abs_path: Arc<Path>,
2063        path_style: PathStyle,
2064    ) -> Self {
2065        Snapshot {
2066            id: WorktreeId::from_usize(id as usize),
2067            abs_path: SanitizedPath::from_arc(abs_path),
2068            path_style,
2069            root_char_bag: root_name
2070                .as_unix_str()
2071                .chars()
2072                .map(|c| c.to_ascii_lowercase())
2073                .collect(),
2074            root_name,
2075            always_included_entries: Default::default(),
2076            entries_by_path: Default::default(),
2077            entries_by_id: Default::default(),
2078            scan_id: 1,
2079            completed_scan_id: 0,
2080        }
2081    }
2082
2083    pub fn id(&self) -> WorktreeId {
2084        self.id
2085    }
2086
2087    // TODO:
2088    // Consider the following:
2089    //
2090    // ```rust
2091    // let abs_path: Arc<Path> = snapshot.abs_path(); // e.g. "C:\Users\user\Desktop\project"
2092    // let some_non_trimmed_path = Path::new("\\\\?\\C:\\Users\\user\\Desktop\\project\\main.rs");
2093    // // The caller perform some actions here:
2094    // some_non_trimmed_path.strip_prefix(abs_path);  // This fails
2095    // some_non_trimmed_path.starts_with(abs_path);   // This fails too
2096    // ```
2097    //
2098    // This is definitely a bug, but it's not clear if we should handle it here or not.
2099    pub fn abs_path(&self) -> &Arc<Path> {
2100        SanitizedPath::cast_arc_ref(&self.abs_path)
2101    }
2102
2103    fn build_initial_update(&self, project_id: u64, worktree_id: u64) -> proto::UpdateWorktree {
2104        let mut updated_entries = self
2105            .entries_by_path
2106            .iter()
2107            .map(proto::Entry::from)
2108            .collect::<Vec<_>>();
2109        updated_entries.sort_unstable_by_key(|e| e.id);
2110
2111        proto::UpdateWorktree {
2112            project_id,
2113            worktree_id,
2114            abs_path: self.abs_path().to_string_lossy().into_owned(),
2115            root_name: self.root_name().to_proto(),
2116            updated_entries,
2117            removed_entries: Vec::new(),
2118            scan_id: self.scan_id as u64,
2119            is_last_update: self.completed_scan_id == self.scan_id,
2120            // Sent in separate messages.
2121            updated_repositories: Vec::new(),
2122            removed_repositories: Vec::new(),
2123        }
2124    }
2125
2126    pub fn work_directory_abs_path(&self, work_directory: &WorkDirectory) -> PathBuf {
2127        match work_directory {
2128            WorkDirectory::InProject { relative_path } => self.absolutize(relative_path),
2129            WorkDirectory::AboveProject { absolute_path, .. } => absolute_path.as_ref().to_owned(),
2130        }
2131    }
2132
2133    pub fn absolutize(&self, path: &RelPath) -> PathBuf {
2134        if path.file_name().is_some() {
2135            let mut abs_path = self.abs_path.to_string();
2136            for component in path.components() {
2137                if !abs_path.ends_with(self.path_style.separator()) {
2138                    abs_path.push_str(self.path_style.separator());
2139                }
2140                abs_path.push_str(component);
2141            }
2142            PathBuf::from(abs_path)
2143        } else {
2144            self.abs_path.as_path().to_path_buf()
2145        }
2146    }
2147
2148    pub fn contains_entry(&self, entry_id: ProjectEntryId) -> bool {
2149        self.entries_by_id.get(&entry_id, ()).is_some()
2150    }
2151
2152    fn insert_entry(
2153        &mut self,
2154        entry: proto::Entry,
2155        always_included_paths: &PathMatcher,
2156    ) -> Result<Entry> {
2157        let entry = Entry::try_from((&self.root_char_bag, always_included_paths, entry))?;
2158        let old_entry = self.entries_by_id.insert_or_replace(
2159            PathEntry {
2160                id: entry.id,
2161                path: entry.path.clone(),
2162                is_ignored: entry.is_ignored,
2163                scan_id: 0,
2164            },
2165            (),
2166        );
2167        if let Some(old_entry) = old_entry {
2168            self.entries_by_path.remove(&PathKey(old_entry.path), ());
2169        }
2170        self.entries_by_path.insert_or_replace(entry.clone(), ());
2171        Ok(entry)
2172    }
2173
2174    fn delete_entry(&mut self, entry_id: ProjectEntryId) -> Option<Arc<RelPath>> {
2175        let removed_entry = self.entries_by_id.remove(&entry_id, ())?;
2176        self.entries_by_path = {
2177            let mut cursor = self.entries_by_path.cursor::<TraversalProgress>(());
2178            let mut new_entries_by_path =
2179                cursor.slice(&TraversalTarget::path(&removed_entry.path), Bias::Left);
2180            while let Some(entry) = cursor.item() {
2181                if entry.path.starts_with(&removed_entry.path) {
2182                    self.entries_by_id.remove(&entry.id, ());
2183                    cursor.next();
2184                } else {
2185                    break;
2186                }
2187            }
2188            new_entries_by_path.append(cursor.suffix(), ());
2189            new_entries_by_path
2190        };
2191
2192        Some(removed_entry.path)
2193    }
2194
2195    fn update_abs_path(&mut self, abs_path: Arc<SanitizedPath>, root_name: Arc<RelPath>) {
2196        self.abs_path = abs_path;
2197        if root_name != self.root_name {
2198            self.root_char_bag = root_name
2199                .as_unix_str()
2200                .chars()
2201                .map(|c| c.to_ascii_lowercase())
2202                .collect();
2203            self.root_name = root_name;
2204        }
2205    }
2206
2207    fn apply_remote_update(
2208        &mut self,
2209        update: proto::UpdateWorktree,
2210        always_included_paths: &PathMatcher,
2211    ) {
2212        log::debug!(
2213            "applying remote worktree update. {} entries updated, {} removed",
2214            update.updated_entries.len(),
2215            update.removed_entries.len()
2216        );
2217        if let Some(root_name) = RelPath::from_proto(&update.root_name).log_err() {
2218            self.update_abs_path(
2219                SanitizedPath::new_arc(&Path::new(&update.abs_path)),
2220                root_name,
2221            );
2222        }
2223
2224        let mut entries_by_path_edits = Vec::new();
2225        let mut entries_by_id_edits = Vec::new();
2226
2227        for entry_id in update.removed_entries {
2228            let entry_id = ProjectEntryId::from_proto(entry_id);
2229            entries_by_id_edits.push(Edit::Remove(entry_id));
2230            if let Some(entry) = self.entry_for_id(entry_id) {
2231                entries_by_path_edits.push(Edit::Remove(PathKey(entry.path.clone())));
2232            }
2233        }
2234
2235        for entry in update.updated_entries {
2236            let Some(entry) =
2237                Entry::try_from((&self.root_char_bag, always_included_paths, entry)).log_err()
2238            else {
2239                continue;
2240            };
2241            if let Some(PathEntry { path, .. }) = self.entries_by_id.get(&entry.id, ()) {
2242                entries_by_path_edits.push(Edit::Remove(PathKey(path.clone())));
2243            }
2244            if let Some(old_entry) = self.entries_by_path.get(&PathKey(entry.path.clone()), ())
2245                && old_entry.id != entry.id
2246            {
2247                entries_by_id_edits.push(Edit::Remove(old_entry.id));
2248            }
2249            entries_by_id_edits.push(Edit::Insert(PathEntry {
2250                id: entry.id,
2251                path: entry.path.clone(),
2252                is_ignored: entry.is_ignored,
2253                scan_id: 0,
2254            }));
2255            entries_by_path_edits.push(Edit::Insert(entry));
2256        }
2257
2258        self.entries_by_path.edit(entries_by_path_edits, ());
2259        self.entries_by_id.edit(entries_by_id_edits, ());
2260
2261        self.scan_id = update.scan_id as usize;
2262        if update.is_last_update {
2263            self.completed_scan_id = update.scan_id as usize;
2264        }
2265    }
2266
2267    pub fn entry_count(&self) -> usize {
2268        self.entries_by_path.summary().count
2269    }
2270
2271    pub fn visible_entry_count(&self) -> usize {
2272        self.entries_by_path.summary().non_ignored_count
2273    }
2274
2275    pub fn dir_count(&self) -> usize {
2276        let summary = self.entries_by_path.summary();
2277        summary.count - summary.file_count
2278    }
2279
2280    pub fn visible_dir_count(&self) -> usize {
2281        let summary = self.entries_by_path.summary();
2282        summary.non_ignored_count - summary.non_ignored_file_count
2283    }
2284
2285    pub fn file_count(&self) -> usize {
2286        self.entries_by_path.summary().file_count
2287    }
2288
2289    pub fn visible_file_count(&self) -> usize {
2290        self.entries_by_path.summary().non_ignored_file_count
2291    }
2292
2293    fn traverse_from_offset(
2294        &self,
2295        include_files: bool,
2296        include_dirs: bool,
2297        include_ignored: bool,
2298        start_offset: usize,
2299    ) -> Traversal<'_> {
2300        let mut cursor = self.entries_by_path.cursor(());
2301        cursor.seek(
2302            &TraversalTarget::Count {
2303                count: start_offset,
2304                include_files,
2305                include_dirs,
2306                include_ignored,
2307            },
2308            Bias::Right,
2309        );
2310        Traversal {
2311            snapshot: self,
2312            cursor,
2313            include_files,
2314            include_dirs,
2315            include_ignored,
2316        }
2317    }
2318
2319    pub fn traverse_from_path(
2320        &self,
2321        include_files: bool,
2322        include_dirs: bool,
2323        include_ignored: bool,
2324        path: &RelPath,
2325    ) -> Traversal<'_> {
2326        Traversal::new(self, include_files, include_dirs, include_ignored, path)
2327    }
2328
2329    pub fn files(&self, include_ignored: bool, start: usize) -> Traversal<'_> {
2330        self.traverse_from_offset(true, false, include_ignored, start)
2331    }
2332
2333    pub fn directories(&self, include_ignored: bool, start: usize) -> Traversal<'_> {
2334        self.traverse_from_offset(false, true, include_ignored, start)
2335    }
2336
2337    pub fn entries(&self, include_ignored: bool, start: usize) -> Traversal<'_> {
2338        self.traverse_from_offset(true, true, include_ignored, start)
2339    }
2340
2341    pub fn paths(&self) -> impl Iterator<Item = &RelPath> {
2342        self.entries_by_path
2343            .cursor::<()>(())
2344            .filter(move |entry| !entry.path.is_empty())
2345            .map(|entry| entry.path.as_ref())
2346    }
2347
2348    pub fn child_entries<'a>(&'a self, parent_path: &'a RelPath) -> ChildEntriesIter<'a> {
2349        let options = ChildEntriesOptions {
2350            include_files: true,
2351            include_dirs: true,
2352            include_ignored: true,
2353        };
2354        self.child_entries_with_options(parent_path, options)
2355    }
2356
2357    pub fn child_entries_with_options<'a>(
2358        &'a self,
2359        parent_path: &'a RelPath,
2360        options: ChildEntriesOptions,
2361    ) -> ChildEntriesIter<'a> {
2362        let mut cursor = self.entries_by_path.cursor(());
2363        cursor.seek(&TraversalTarget::path(parent_path), Bias::Right);
2364        let traversal = Traversal {
2365            snapshot: self,
2366            cursor,
2367            include_files: options.include_files,
2368            include_dirs: options.include_dirs,
2369            include_ignored: options.include_ignored,
2370        };
2371        ChildEntriesIter {
2372            traversal,
2373            parent_path,
2374        }
2375    }
2376
2377    pub fn root_entry(&self) -> Option<&Entry> {
2378        self.entries_by_path.first()
2379    }
2380
2381    /// TODO: what's the difference between `root_dir` and `abs_path`?
2382    /// is there any? if so, document it.
2383    pub fn root_dir(&self) -> Option<Arc<Path>> {
2384        self.root_entry()
2385            .filter(|entry| entry.is_dir())
2386            .map(|_| self.abs_path().clone())
2387    }
2388
2389    pub fn root_name(&self) -> &RelPath {
2390        &self.root_name
2391    }
2392
2393    pub fn root_name_str(&self) -> &str {
2394        self.root_name.as_unix_str()
2395    }
2396
2397    pub fn scan_id(&self) -> usize {
2398        self.scan_id
2399    }
2400
2401    pub fn entry_for_path(&self, path: &RelPath) -> Option<&Entry> {
2402        self.traverse_from_path(true, true, true, path)
2403            .entry()
2404            .and_then(|entry| {
2405                if entry.path.as_ref() == path {
2406                    Some(entry)
2407                } else {
2408                    None
2409                }
2410            })
2411    }
2412
2413    pub fn entry_for_id(&self, id: ProjectEntryId) -> Option<&Entry> {
2414        let entry = self.entries_by_id.get(&id, ())?;
2415        self.entry_for_path(&entry.path)
2416    }
2417
2418    pub fn path_style(&self) -> PathStyle {
2419        self.path_style
2420    }
2421}
2422
2423impl LocalSnapshot {
2424    fn local_repo_for_work_directory_path(&self, path: &RelPath) -> Option<&LocalRepositoryEntry> {
2425        self.git_repositories
2426            .iter()
2427            .map(|(_, entry)| entry)
2428            .find(|entry| entry.work_directory.path_key() == PathKey(path.into()))
2429    }
2430
2431    fn build_update(
2432        &self,
2433        project_id: u64,
2434        worktree_id: u64,
2435        entry_changes: UpdatedEntriesSet,
2436    ) -> proto::UpdateWorktree {
2437        let mut updated_entries = Vec::new();
2438        let mut removed_entries = Vec::new();
2439
2440        for (_, entry_id, path_change) in entry_changes.iter() {
2441            if let PathChange::Removed = path_change {
2442                removed_entries.push(entry_id.0 as u64);
2443            } else if let Some(entry) = self.entry_for_id(*entry_id) {
2444                updated_entries.push(proto::Entry::from(entry));
2445            }
2446        }
2447
2448        removed_entries.sort_unstable();
2449        updated_entries.sort_unstable_by_key(|e| e.id);
2450
2451        // TODO - optimize, knowing that removed_entries are sorted.
2452        removed_entries.retain(|id| updated_entries.binary_search_by_key(id, |e| e.id).is_err());
2453
2454        proto::UpdateWorktree {
2455            project_id,
2456            worktree_id,
2457            abs_path: self.abs_path().to_string_lossy().into_owned(),
2458            root_name: self.root_name().to_proto(),
2459            updated_entries,
2460            removed_entries,
2461            scan_id: self.scan_id as u64,
2462            is_last_update: self.completed_scan_id == self.scan_id,
2463            // Sent in separate messages.
2464            updated_repositories: Vec::new(),
2465            removed_repositories: Vec::new(),
2466        }
2467    }
2468
2469    fn insert_entry(&mut self, mut entry: Entry, fs: &dyn Fs) -> Entry {
2470        log::trace!("insert entry {:?}", entry.path);
2471        if entry.is_file() && entry.path.file_name() == Some(&GITIGNORE) {
2472            let abs_path = self.absolutize(&entry.path);
2473            match self.executor.block(build_gitignore(&abs_path, fs)) {
2474                Ok(ignore) => {
2475                    self.ignores_by_parent_abs_path
2476                        .insert(abs_path.parent().unwrap().into(), (Arc::new(ignore), true));
2477                }
2478                Err(error) => {
2479                    log::error!(
2480                        "error loading .gitignore file {:?} - {:?}",
2481                        &entry.path,
2482                        error
2483                    );
2484                }
2485            }
2486        }
2487
2488        if entry.kind == EntryKind::PendingDir
2489            && let Some(existing_entry) = self.entries_by_path.get(&PathKey(entry.path.clone()), ())
2490        {
2491            entry.kind = existing_entry.kind;
2492        }
2493
2494        let scan_id = self.scan_id;
2495        let removed = self.entries_by_path.insert_or_replace(entry.clone(), ());
2496        if let Some(removed) = removed
2497            && removed.id != entry.id
2498        {
2499            self.entries_by_id.remove(&removed.id, ());
2500        }
2501        self.entries_by_id.insert_or_replace(
2502            PathEntry {
2503                id: entry.id,
2504                path: entry.path.clone(),
2505                is_ignored: entry.is_ignored,
2506                scan_id,
2507            },
2508            (),
2509        );
2510
2511        entry
2512    }
2513
2514    fn ancestor_inodes_for_path(&self, path: &RelPath) -> TreeSet<u64> {
2515        let mut inodes = TreeSet::default();
2516        for ancestor in path.ancestors().skip(1) {
2517            if let Some(entry) = self.entry_for_path(ancestor) {
2518                inodes.insert(entry.inode);
2519            }
2520        }
2521        inodes
2522    }
2523
2524    async fn ignore_stack_for_abs_path(
2525        &self,
2526        abs_path: &Path,
2527        is_dir: bool,
2528        fs: &dyn Fs,
2529    ) -> IgnoreStack {
2530        let mut new_ignores = Vec::new();
2531        let mut repo_root = None;
2532        for (index, ancestor) in abs_path.ancestors().enumerate() {
2533            if index > 0 {
2534                if let Some((ignore, _)) = self.ignores_by_parent_abs_path.get(ancestor) {
2535                    new_ignores.push((ancestor, Some(ignore.clone())));
2536                } else {
2537                    new_ignores.push((ancestor, None));
2538                }
2539            }
2540
2541            let metadata = fs.metadata(&ancestor.join(DOT_GIT)).await.ok().flatten();
2542            if metadata.is_some() {
2543                repo_root = Some(Arc::from(ancestor));
2544                break;
2545            }
2546        }
2547
2548        let mut ignore_stack = if let Some(global_gitignore) = self.global_gitignore.clone() {
2549            IgnoreStack::global(global_gitignore)
2550        } else {
2551            IgnoreStack::none()
2552        };
2553        ignore_stack.repo_root = repo_root;
2554        for (parent_abs_path, ignore) in new_ignores.into_iter().rev() {
2555            if ignore_stack.is_abs_path_ignored(parent_abs_path, true) {
2556                ignore_stack = IgnoreStack::all();
2557                break;
2558            } else if let Some(ignore) = ignore {
2559                ignore_stack = ignore_stack.append(parent_abs_path.into(), ignore);
2560            }
2561        }
2562
2563        if ignore_stack.is_abs_path_ignored(abs_path, is_dir) {
2564            ignore_stack = IgnoreStack::all();
2565        }
2566
2567        ignore_stack
2568    }
2569
2570    #[cfg(test)]
2571    fn expanded_entries(&self) -> impl Iterator<Item = &Entry> {
2572        self.entries_by_path
2573            .cursor::<()>(())
2574            .filter(|entry| entry.kind == EntryKind::Dir && (entry.is_external || entry.is_ignored))
2575    }
2576
2577    #[cfg(test)]
2578    pub fn check_invariants(&self, git_state: bool) {
2579        use pretty_assertions::assert_eq;
2580
2581        assert_eq!(
2582            self.entries_by_path
2583                .cursor::<()>(())
2584                .map(|e| (&e.path, e.id))
2585                .collect::<Vec<_>>(),
2586            self.entries_by_id
2587                .cursor::<()>(())
2588                .map(|e| (&e.path, e.id))
2589                .collect::<collections::BTreeSet<_>>()
2590                .into_iter()
2591                .collect::<Vec<_>>(),
2592            "entries_by_path and entries_by_id are inconsistent"
2593        );
2594
2595        let mut files = self.files(true, 0);
2596        let mut visible_files = self.files(false, 0);
2597        for entry in self.entries_by_path.cursor::<()>(()) {
2598            if entry.is_file() {
2599                assert_eq!(files.next().unwrap().inode, entry.inode);
2600                if (!entry.is_ignored && !entry.is_external) || entry.is_always_included {
2601                    assert_eq!(visible_files.next().unwrap().inode, entry.inode);
2602                }
2603            }
2604        }
2605
2606        assert!(files.next().is_none());
2607        assert!(visible_files.next().is_none());
2608
2609        let mut bfs_paths = Vec::new();
2610        let mut stack = self
2611            .root_entry()
2612            .map(|e| e.path.as_ref())
2613            .into_iter()
2614            .collect::<Vec<_>>();
2615        while let Some(path) = stack.pop() {
2616            bfs_paths.push(path);
2617            let ix = stack.len();
2618            for child_entry in self.child_entries(path) {
2619                stack.insert(ix, &child_entry.path);
2620            }
2621        }
2622
2623        let dfs_paths_via_iter = self
2624            .entries_by_path
2625            .cursor::<()>(())
2626            .map(|e| e.path.as_ref())
2627            .collect::<Vec<_>>();
2628        assert_eq!(bfs_paths, dfs_paths_via_iter);
2629
2630        let dfs_paths_via_traversal = self
2631            .entries(true, 0)
2632            .map(|e| e.path.as_ref())
2633            .collect::<Vec<_>>();
2634
2635        assert_eq!(dfs_paths_via_traversal, dfs_paths_via_iter);
2636
2637        if git_state {
2638            for ignore_parent_abs_path in self.ignores_by_parent_abs_path.keys() {
2639                let ignore_parent_path = &RelPath::new(
2640                    ignore_parent_abs_path
2641                        .strip_prefix(self.abs_path.as_path())
2642                        .unwrap(),
2643                    PathStyle::local(),
2644                )
2645                .unwrap();
2646                assert!(self.entry_for_path(ignore_parent_path).is_some());
2647                assert!(
2648                    self.entry_for_path(
2649                        &ignore_parent_path.join(RelPath::unix(GITIGNORE).unwrap())
2650                    )
2651                    .is_some()
2652                );
2653            }
2654        }
2655    }
2656
2657    #[cfg(test)]
2658    pub fn entries_without_ids(&self, include_ignored: bool) -> Vec<(&RelPath, u64, bool)> {
2659        let mut paths = Vec::new();
2660        for entry in self.entries_by_path.cursor::<()>(()) {
2661            if include_ignored || !entry.is_ignored {
2662                paths.push((entry.path.as_ref(), entry.inode, entry.is_ignored));
2663            }
2664        }
2665        paths.sort_by(|a, b| a.0.cmp(b.0));
2666        paths
2667    }
2668}
2669
2670impl BackgroundScannerState {
2671    fn should_scan_directory(&self, entry: &Entry) -> bool {
2672        (!entry.is_external && (!entry.is_ignored || entry.is_always_included))
2673            || entry.path.file_name() == Some(DOT_GIT)
2674            || entry.path.file_name() == Some(local_settings_folder_name())
2675            || entry.path.file_name() == Some(local_vscode_folder_name())
2676            || self.scanned_dirs.contains(&entry.id) // If we've ever scanned it, keep scanning
2677            || self
2678                .paths_to_scan
2679                .iter()
2680                .any(|p| p.starts_with(&entry.path))
2681            || self
2682                .path_prefixes_to_scan
2683                .iter()
2684                .any(|p| entry.path.starts_with(p))
2685    }
2686
2687    async fn enqueue_scan_dir(
2688        &self,
2689        abs_path: Arc<Path>,
2690        entry: &Entry,
2691        scan_job_tx: &Sender<ScanJob>,
2692        fs: &dyn Fs,
2693    ) {
2694        let path = entry.path.clone();
2695        let ignore_stack = self
2696            .snapshot
2697            .ignore_stack_for_abs_path(&abs_path, true, fs)
2698            .await;
2699        let mut ancestor_inodes = self.snapshot.ancestor_inodes_for_path(&path);
2700
2701        if !ancestor_inodes.contains(&entry.inode) {
2702            ancestor_inodes.insert(entry.inode);
2703            scan_job_tx
2704                .try_send(ScanJob {
2705                    abs_path,
2706                    path,
2707                    ignore_stack,
2708                    scan_queue: scan_job_tx.clone(),
2709                    ancestor_inodes,
2710                    is_external: entry.is_external,
2711                    is_hidden: entry.is_hidden,
2712                })
2713                .unwrap();
2714        }
2715    }
2716
2717    fn reuse_entry_id(&mut self, entry: &mut Entry) {
2718        if let Some(mtime) = entry.mtime {
2719            // If an entry with the same inode was removed from the worktree during this scan,
2720            // then it *might* represent the same file or directory. But the OS might also have
2721            // re-used the inode for a completely different file or directory.
2722            //
2723            // Conditionally reuse the old entry's id:
2724            // * if the mtime is the same, the file was probably been renamed.
2725            // * if the path is the same, the file may just have been updated
2726            if let Some(removed_entry) = self.removed_entries.remove(&entry.inode) {
2727                if removed_entry.mtime == Some(mtime) || removed_entry.path == entry.path {
2728                    entry.id = removed_entry.id;
2729                }
2730            } else if let Some(existing_entry) = self.snapshot.entry_for_path(&entry.path) {
2731                entry.id = existing_entry.id;
2732            }
2733        }
2734    }
2735
2736    async fn insert_entry(
2737        &mut self,
2738        mut entry: Entry,
2739        fs: &dyn Fs,
2740        watcher: &dyn Watcher,
2741    ) -> Entry {
2742        self.reuse_entry_id(&mut entry);
2743        let entry = self.snapshot.insert_entry(entry, fs);
2744        if entry.path.file_name() == Some(&DOT_GIT) {
2745            self.insert_git_repository(entry.path.clone(), fs, watcher)
2746                .await;
2747        }
2748
2749        #[cfg(test)]
2750        self.snapshot.check_invariants(false);
2751
2752        entry
2753    }
2754
2755    fn populate_dir(
2756        &mut self,
2757        parent_path: Arc<RelPath>,
2758        entries: impl IntoIterator<Item = Entry>,
2759        ignore: Option<Arc<Gitignore>>,
2760    ) {
2761        let mut parent_entry = if let Some(parent_entry) = self
2762            .snapshot
2763            .entries_by_path
2764            .get(&PathKey(parent_path.clone()), ())
2765        {
2766            parent_entry.clone()
2767        } else {
2768            log::warn!(
2769                "populating a directory {:?} that has been removed",
2770                parent_path
2771            );
2772            return;
2773        };
2774
2775        match parent_entry.kind {
2776            EntryKind::PendingDir | EntryKind::UnloadedDir => parent_entry.kind = EntryKind::Dir,
2777            EntryKind::Dir => {}
2778            _ => return,
2779        }
2780
2781        if let Some(ignore) = ignore {
2782            let abs_parent_path = self
2783                .snapshot
2784                .abs_path
2785                .as_path()
2786                .join(parent_path.as_std_path())
2787                .into();
2788            self.snapshot
2789                .ignores_by_parent_abs_path
2790                .insert(abs_parent_path, (ignore, false));
2791        }
2792
2793        let parent_entry_id = parent_entry.id;
2794        self.scanned_dirs.insert(parent_entry_id);
2795        let mut entries_by_path_edits = vec![Edit::Insert(parent_entry)];
2796        let mut entries_by_id_edits = Vec::new();
2797
2798        for entry in entries {
2799            entries_by_id_edits.push(Edit::Insert(PathEntry {
2800                id: entry.id,
2801                path: entry.path.clone(),
2802                is_ignored: entry.is_ignored,
2803                scan_id: self.snapshot.scan_id,
2804            }));
2805            entries_by_path_edits.push(Edit::Insert(entry));
2806        }
2807
2808        self.snapshot
2809            .entries_by_path
2810            .edit(entries_by_path_edits, ());
2811        self.snapshot.entries_by_id.edit(entries_by_id_edits, ());
2812
2813        if let Err(ix) = self.changed_paths.binary_search(&parent_path) {
2814            self.changed_paths.insert(ix, parent_path.clone());
2815        }
2816
2817        #[cfg(test)]
2818        self.snapshot.check_invariants(false);
2819    }
2820
2821    fn remove_path(&mut self, path: &RelPath) {
2822        log::trace!("background scanner removing path {path:?}");
2823        let mut new_entries;
2824        let removed_entries;
2825        {
2826            let mut cursor = self
2827                .snapshot
2828                .entries_by_path
2829                .cursor::<TraversalProgress>(());
2830            new_entries = cursor.slice(&TraversalTarget::path(path), Bias::Left);
2831            removed_entries = cursor.slice(&TraversalTarget::successor(path), Bias::Left);
2832            new_entries.append(cursor.suffix(), ());
2833        }
2834        self.snapshot.entries_by_path = new_entries;
2835
2836        let mut removed_ids = Vec::with_capacity(removed_entries.summary().count);
2837        for entry in removed_entries.cursor::<()>(()) {
2838            match self.removed_entries.entry(entry.inode) {
2839                hash_map::Entry::Occupied(mut e) => {
2840                    let prev_removed_entry = e.get_mut();
2841                    if entry.id > prev_removed_entry.id {
2842                        *prev_removed_entry = entry.clone();
2843                    }
2844                }
2845                hash_map::Entry::Vacant(e) => {
2846                    e.insert(entry.clone());
2847                }
2848            }
2849
2850            if entry.path.file_name() == Some(GITIGNORE) {
2851                let abs_parent_path = self.snapshot.absolutize(&entry.path.parent().unwrap());
2852                if let Some((_, needs_update)) = self
2853                    .snapshot
2854                    .ignores_by_parent_abs_path
2855                    .get_mut(abs_parent_path.as_path())
2856                {
2857                    *needs_update = true;
2858                }
2859            }
2860
2861            if let Err(ix) = removed_ids.binary_search(&entry.id) {
2862                removed_ids.insert(ix, entry.id);
2863            }
2864        }
2865
2866        self.snapshot
2867            .entries_by_id
2868            .edit(removed_ids.iter().map(|&id| Edit::Remove(id)).collect(), ());
2869        self.snapshot
2870            .git_repositories
2871            .retain(|id, _| removed_ids.binary_search(id).is_err());
2872
2873        #[cfg(test)]
2874        self.snapshot.check_invariants(false);
2875    }
2876
2877    async fn insert_git_repository(
2878        &mut self,
2879        dot_git_path: Arc<RelPath>,
2880        fs: &dyn Fs,
2881        watcher: &dyn Watcher,
2882    ) {
2883        let work_dir_path: Arc<RelPath> = match dot_git_path.parent() {
2884            Some(parent_dir) => {
2885                // Guard against repositories inside the repository metadata
2886                if parent_dir
2887                    .components()
2888                    .any(|component| component == DOT_GIT)
2889                {
2890                    log::debug!(
2891                        "not building git repository for nested `.git` directory, `.git` path in the worktree: {dot_git_path:?}"
2892                    );
2893                    return;
2894                };
2895
2896                parent_dir.into()
2897            }
2898            None => {
2899                // `dot_git_path.parent().is_none()` means `.git` directory is the opened worktree itself,
2900                // no files inside that directory are tracked by git, so no need to build the repo around it
2901                log::debug!(
2902                    "not building git repository for the worktree itself, `.git` path in the worktree: {dot_git_path:?}"
2903                );
2904                return;
2905            }
2906        };
2907
2908        let dot_git_abs_path = Arc::from(self.snapshot.absolutize(&dot_git_path).as_ref());
2909
2910        self.insert_git_repository_for_path(
2911            WorkDirectory::InProject {
2912                relative_path: work_dir_path,
2913            },
2914            dot_git_abs_path,
2915            fs,
2916            watcher,
2917        )
2918        .await
2919        .log_err();
2920    }
2921
2922    async fn insert_git_repository_for_path(
2923        &mut self,
2924        work_directory: WorkDirectory,
2925        dot_git_abs_path: Arc<Path>,
2926        fs: &dyn Fs,
2927        watcher: &dyn Watcher,
2928    ) -> Result<LocalRepositoryEntry> {
2929        let work_dir_entry = self
2930            .snapshot
2931            .entry_for_path(&work_directory.path_key().0)
2932            .with_context(|| {
2933                format!(
2934                    "working directory `{}` not indexed",
2935                    work_directory
2936                        .path_key()
2937                        .0
2938                        .display(self.snapshot.path_style)
2939                )
2940            })?;
2941        let work_directory_abs_path = self.snapshot.work_directory_abs_path(&work_directory);
2942
2943        let (repository_dir_abs_path, common_dir_abs_path) =
2944            discover_git_paths(&dot_git_abs_path, fs).await;
2945        watcher
2946            .add(&common_dir_abs_path)
2947            .context("failed to add common directory to watcher")
2948            .log_err();
2949        if !repository_dir_abs_path.starts_with(&common_dir_abs_path) {
2950            watcher
2951                .add(&repository_dir_abs_path)
2952                .context("failed to add repository directory to watcher")
2953                .log_err();
2954        }
2955
2956        let work_directory_id = work_dir_entry.id;
2957
2958        let local_repository = LocalRepositoryEntry {
2959            work_directory_id,
2960            work_directory,
2961            work_directory_abs_path: work_directory_abs_path.as_path().into(),
2962            git_dir_scan_id: 0,
2963            dot_git_abs_path,
2964            common_dir_abs_path,
2965            repository_dir_abs_path,
2966        };
2967
2968        self.snapshot
2969            .git_repositories
2970            .insert(work_directory_id, local_repository.clone());
2971
2972        log::trace!("inserting new local git repository");
2973        Ok(local_repository)
2974    }
2975}
2976
2977async fn is_git_dir(path: &Path, fs: &dyn Fs) -> bool {
2978    if let Some(file_name) = path.file_name()
2979        && file_name == DOT_GIT
2980    {
2981        return true;
2982    }
2983
2984    // If we're in a bare repository, we are not inside a `.git` folder. In a
2985    // bare repository, the root folder contains what would normally be in the
2986    // `.git` folder.
2987    let head_metadata = fs.metadata(&path.join("HEAD")).await;
2988    if !matches!(head_metadata, Ok(Some(_))) {
2989        return false;
2990    }
2991    let config_metadata = fs.metadata(&path.join("config")).await;
2992    matches!(config_metadata, Ok(Some(_)))
2993}
2994
2995async fn build_gitignore(abs_path: &Path, fs: &dyn Fs) -> Result<Gitignore> {
2996    let contents = fs
2997        .load(abs_path)
2998        .await
2999        .with_context(|| format!("failed to load gitignore file at {}", abs_path.display()))?;
3000    let parent = abs_path.parent().unwrap_or_else(|| Path::new("/"));
3001    let mut builder = GitignoreBuilder::new(parent);
3002    for line in contents.lines() {
3003        builder.add_line(Some(abs_path.into()), line)?;
3004    }
3005    Ok(builder.build()?)
3006}
3007
3008impl Deref for Worktree {
3009    type Target = Snapshot;
3010
3011    fn deref(&self) -> &Self::Target {
3012        match self {
3013            Worktree::Local(worktree) => &worktree.snapshot,
3014            Worktree::Remote(worktree) => &worktree.snapshot,
3015        }
3016    }
3017}
3018
3019impl Deref for LocalWorktree {
3020    type Target = LocalSnapshot;
3021
3022    fn deref(&self) -> &Self::Target {
3023        &self.snapshot
3024    }
3025}
3026
3027impl Deref for RemoteWorktree {
3028    type Target = Snapshot;
3029
3030    fn deref(&self) -> &Self::Target {
3031        &self.snapshot
3032    }
3033}
3034
3035impl fmt::Debug for LocalWorktree {
3036    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3037        self.snapshot.fmt(f)
3038    }
3039}
3040
3041impl fmt::Debug for Snapshot {
3042    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3043        struct EntriesById<'a>(&'a SumTree<PathEntry>);
3044        struct EntriesByPath<'a>(&'a SumTree<Entry>);
3045
3046        impl fmt::Debug for EntriesByPath<'_> {
3047            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3048                f.debug_map()
3049                    .entries(self.0.iter().map(|entry| (&entry.path, entry.id)))
3050                    .finish()
3051            }
3052        }
3053
3054        impl fmt::Debug for EntriesById<'_> {
3055            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3056                f.debug_list().entries(self.0.iter()).finish()
3057            }
3058        }
3059
3060        f.debug_struct("Snapshot")
3061            .field("id", &self.id)
3062            .field("root_name", &self.root_name)
3063            .field("entries_by_path", &EntriesByPath(&self.entries_by_path))
3064            .field("entries_by_id", &EntriesById(&self.entries_by_id))
3065            .finish()
3066    }
3067}
3068
3069#[derive(Debug, Clone, PartialEq)]
3070pub struct File {
3071    pub worktree: Entity<Worktree>,
3072    pub path: Arc<RelPath>,
3073    pub disk_state: DiskState,
3074    pub entry_id: Option<ProjectEntryId>,
3075    pub is_local: bool,
3076    pub is_private: bool,
3077}
3078
3079impl language::File for File {
3080    fn as_local(&self) -> Option<&dyn language::LocalFile> {
3081        if self.is_local { Some(self) } else { None }
3082    }
3083
3084    fn disk_state(&self) -> DiskState {
3085        self.disk_state
3086    }
3087
3088    fn path(&self) -> &Arc<RelPath> {
3089        &self.path
3090    }
3091
3092    fn full_path(&self, cx: &App) -> PathBuf {
3093        self.worktree.read(cx).full_path(&self.path)
3094    }
3095
3096    /// Returns the last component of this handle's absolute path. If this handle refers to the root
3097    /// of its worktree, then this method will return the name of the worktree itself.
3098    fn file_name<'a>(&'a self, cx: &'a App) -> &'a str {
3099        self.path
3100            .file_name()
3101            .unwrap_or_else(|| self.worktree.read(cx).root_name_str())
3102    }
3103
3104    fn worktree_id(&self, cx: &App) -> WorktreeId {
3105        self.worktree.read(cx).id()
3106    }
3107
3108    fn to_proto(&self, cx: &App) -> rpc::proto::File {
3109        rpc::proto::File {
3110            worktree_id: self.worktree.read(cx).id().to_proto(),
3111            entry_id: self.entry_id.map(|id| id.to_proto()),
3112            path: self.path.as_ref().to_proto(),
3113            mtime: self.disk_state.mtime().map(|time| time.into()),
3114            is_deleted: self.disk_state == DiskState::Deleted,
3115        }
3116    }
3117
3118    fn is_private(&self) -> bool {
3119        self.is_private
3120    }
3121
3122    fn path_style(&self, cx: &App) -> PathStyle {
3123        self.worktree.read(cx).path_style()
3124    }
3125}
3126
3127impl language::LocalFile for File {
3128    fn abs_path(&self, cx: &App) -> PathBuf {
3129        self.worktree.read(cx).absolutize(&self.path)
3130    }
3131
3132    fn load(&self, cx: &App) -> Task<Result<String>> {
3133        let worktree = self.worktree.read(cx).as_local().unwrap();
3134        let abs_path = worktree.absolutize(&self.path);
3135        let fs = worktree.fs.clone();
3136        cx.background_spawn(async move { fs.load(&abs_path).await })
3137    }
3138
3139    fn load_bytes(&self, cx: &App) -> Task<Result<Vec<u8>>> {
3140        let worktree = self.worktree.read(cx).as_local().unwrap();
3141        let abs_path = worktree.absolutize(&self.path);
3142        let fs = worktree.fs.clone();
3143        cx.background_spawn(async move { fs.load_bytes(&abs_path).await })
3144    }
3145}
3146
3147impl File {
3148    pub fn for_entry(entry: Entry, worktree: Entity<Worktree>) -> Arc<Self> {
3149        Arc::new(Self {
3150            worktree,
3151            path: entry.path.clone(),
3152            disk_state: if let Some(mtime) = entry.mtime {
3153                DiskState::Present { mtime }
3154            } else {
3155                DiskState::New
3156            },
3157            entry_id: Some(entry.id),
3158            is_local: true,
3159            is_private: entry.is_private,
3160        })
3161    }
3162
3163    pub fn from_proto(
3164        proto: rpc::proto::File,
3165        worktree: Entity<Worktree>,
3166        cx: &App,
3167    ) -> Result<Self> {
3168        let worktree_id = worktree.read(cx).as_remote().context("not remote")?.id();
3169
3170        anyhow::ensure!(
3171            worktree_id.to_proto() == proto.worktree_id,
3172            "worktree id does not match file"
3173        );
3174
3175        let disk_state = if proto.is_deleted {
3176            DiskState::Deleted
3177        } else if let Some(mtime) = proto.mtime.map(&Into::into) {
3178            DiskState::Present { mtime }
3179        } else {
3180            DiskState::New
3181        };
3182
3183        Ok(Self {
3184            worktree,
3185            path: RelPath::from_proto(&proto.path).context("invalid path in file protobuf")?,
3186            disk_state,
3187            entry_id: proto.entry_id.map(ProjectEntryId::from_proto),
3188            is_local: false,
3189            is_private: false,
3190        })
3191    }
3192
3193    pub fn from_dyn(file: Option<&Arc<dyn language::File>>) -> Option<&Self> {
3194        file.and_then(|f| {
3195            let f: &dyn language::File = f.borrow();
3196            let f: &dyn Any = f;
3197            f.downcast_ref()
3198        })
3199    }
3200
3201    pub fn worktree_id(&self, cx: &App) -> WorktreeId {
3202        self.worktree.read(cx).id()
3203    }
3204
3205    pub fn project_entry_id(&self) -> Option<ProjectEntryId> {
3206        match self.disk_state {
3207            DiskState::Deleted => None,
3208            _ => self.entry_id,
3209        }
3210    }
3211}
3212
3213#[derive(Clone, Debug, PartialEq, Eq)]
3214pub struct Entry {
3215    pub id: ProjectEntryId,
3216    pub kind: EntryKind,
3217    pub path: Arc<RelPath>,
3218    pub inode: u64,
3219    pub mtime: Option<MTime>,
3220
3221    pub canonical_path: Option<Arc<Path>>,
3222    /// Whether this entry is ignored by Git.
3223    ///
3224    /// We only scan ignored entries once the directory is expanded and
3225    /// exclude them from searches.
3226    pub is_ignored: bool,
3227
3228    /// Whether this entry is hidden or inside hidden directory.
3229    ///
3230    /// We only scan hidden entries once the directory is expanded.
3231    pub is_hidden: bool,
3232
3233    /// Whether this entry is always included in searches.
3234    ///
3235    /// This is used for entries that are always included in searches, even
3236    /// if they are ignored by git. Overridden by file_scan_exclusions.
3237    pub is_always_included: bool,
3238
3239    /// Whether this entry's canonical path is outside of the worktree.
3240    /// This means the entry is only accessible from the worktree root via a
3241    /// symlink.
3242    ///
3243    /// We only scan entries outside of the worktree once the symlinked
3244    /// directory is expanded. External entries are treated like gitignored
3245    /// entries in that they are not included in searches.
3246    pub is_external: bool,
3247
3248    /// Whether this entry is considered to be a `.env` file.
3249    pub is_private: bool,
3250    /// The entry's size on disk, in bytes.
3251    pub size: u64,
3252    pub char_bag: CharBag,
3253    pub is_fifo: bool,
3254}
3255
3256#[derive(Clone, Copy, Debug, PartialEq, Eq)]
3257pub enum EntryKind {
3258    UnloadedDir,
3259    PendingDir,
3260    Dir,
3261    File,
3262}
3263
3264#[derive(Clone, Copy, Debug, PartialEq)]
3265pub enum PathChange {
3266    /// A filesystem entry was was created.
3267    Added,
3268    /// A filesystem entry was removed.
3269    Removed,
3270    /// A filesystem entry was updated.
3271    Updated,
3272    /// A filesystem entry was either updated or added. We don't know
3273    /// whether or not it already existed, because the path had not
3274    /// been loaded before the event.
3275    AddedOrUpdated,
3276    /// A filesystem entry was found during the initial scan of the worktree.
3277    Loaded,
3278}
3279
3280#[derive(Clone, Debug, PartialEq, Eq)]
3281pub struct UpdatedGitRepository {
3282    /// ID of the repository's working directory.
3283    ///
3284    /// For a repo that's above the worktree root, this is the ID of the worktree root, and hence not unique.
3285    /// It's included here to aid the GitStore in detecting when a repository's working directory is renamed.
3286    pub work_directory_id: ProjectEntryId,
3287    pub old_work_directory_abs_path: Option<Arc<Path>>,
3288    pub new_work_directory_abs_path: Option<Arc<Path>>,
3289    /// For a normal git repository checkout, the absolute path to the .git directory.
3290    /// For a worktree, the absolute path to the worktree's subdirectory inside the .git directory.
3291    pub dot_git_abs_path: Option<Arc<Path>>,
3292    pub repository_dir_abs_path: Option<Arc<Path>>,
3293    pub common_dir_abs_path: Option<Arc<Path>>,
3294}
3295
3296pub type UpdatedEntriesSet = Arc<[(Arc<RelPath>, ProjectEntryId, PathChange)]>;
3297pub type UpdatedGitRepositoriesSet = Arc<[UpdatedGitRepository]>;
3298
3299#[derive(Clone, Debug)]
3300pub struct PathProgress<'a> {
3301    pub max_path: &'a RelPath,
3302}
3303
3304#[derive(Clone, Debug)]
3305pub struct PathSummary<S> {
3306    pub max_path: Arc<RelPath>,
3307    pub item_summary: S,
3308}
3309
3310impl<S: Summary> Summary for PathSummary<S> {
3311    type Context<'a> = S::Context<'a>;
3312
3313    fn zero(cx: Self::Context<'_>) -> Self {
3314        Self {
3315            max_path: RelPath::empty().into(),
3316            item_summary: S::zero(cx),
3317        }
3318    }
3319
3320    fn add_summary(&mut self, rhs: &Self, cx: Self::Context<'_>) {
3321        self.max_path = rhs.max_path.clone();
3322        self.item_summary.add_summary(&rhs.item_summary, cx);
3323    }
3324}
3325
3326impl<'a, S: Summary> sum_tree::Dimension<'a, PathSummary<S>> for PathProgress<'a> {
3327    fn zero(_: <PathSummary<S> as Summary>::Context<'_>) -> Self {
3328        Self {
3329            max_path: RelPath::empty(),
3330        }
3331    }
3332
3333    fn add_summary(
3334        &mut self,
3335        summary: &'a PathSummary<S>,
3336        _: <PathSummary<S> as Summary>::Context<'_>,
3337    ) {
3338        self.max_path = summary.max_path.as_ref()
3339    }
3340}
3341
3342impl<'a> sum_tree::Dimension<'a, PathSummary<GitSummary>> for GitSummary {
3343    fn zero(_cx: ()) -> Self {
3344        Default::default()
3345    }
3346
3347    fn add_summary(&mut self, summary: &'a PathSummary<GitSummary>, _: ()) {
3348        *self += summary.item_summary
3349    }
3350}
3351
3352impl<'a>
3353    sum_tree::SeekTarget<'a, PathSummary<GitSummary>, Dimensions<TraversalProgress<'a>, GitSummary>>
3354    for PathTarget<'_>
3355{
3356    fn cmp(
3357        &self,
3358        cursor_location: &Dimensions<TraversalProgress<'a>, GitSummary>,
3359        _: (),
3360    ) -> Ordering {
3361        self.cmp_path(cursor_location.0.max_path)
3362    }
3363}
3364
3365impl<'a, S: Summary> sum_tree::Dimension<'a, PathSummary<S>> for PathKey {
3366    fn zero(_: S::Context<'_>) -> Self {
3367        Default::default()
3368    }
3369
3370    fn add_summary(&mut self, summary: &'a PathSummary<S>, _: S::Context<'_>) {
3371        self.0 = summary.max_path.clone();
3372    }
3373}
3374
3375impl<'a, S: Summary> sum_tree::Dimension<'a, PathSummary<S>> for TraversalProgress<'a> {
3376    fn zero(_cx: S::Context<'_>) -> Self {
3377        Default::default()
3378    }
3379
3380    fn add_summary(&mut self, summary: &'a PathSummary<S>, _: S::Context<'_>) {
3381        self.max_path = summary.max_path.as_ref();
3382    }
3383}
3384
3385impl Entry {
3386    fn new(
3387        path: Arc<RelPath>,
3388        metadata: &fs::Metadata,
3389        next_entry_id: &AtomicUsize,
3390        root_char_bag: CharBag,
3391        canonical_path: Option<Arc<Path>>,
3392    ) -> Self {
3393        let char_bag = char_bag_for_path(root_char_bag, &path);
3394        Self {
3395            id: ProjectEntryId::new(next_entry_id),
3396            kind: if metadata.is_dir {
3397                EntryKind::PendingDir
3398            } else {
3399                EntryKind::File
3400            },
3401            path,
3402            inode: metadata.inode,
3403            mtime: Some(metadata.mtime),
3404            size: metadata.len,
3405            canonical_path,
3406            is_ignored: false,
3407            is_hidden: false,
3408            is_always_included: false,
3409            is_external: false,
3410            is_private: false,
3411            char_bag,
3412            is_fifo: metadata.is_fifo,
3413        }
3414    }
3415
3416    pub fn is_created(&self) -> bool {
3417        self.mtime.is_some()
3418    }
3419
3420    pub fn is_dir(&self) -> bool {
3421        self.kind.is_dir()
3422    }
3423
3424    pub fn is_file(&self) -> bool {
3425        self.kind.is_file()
3426    }
3427}
3428
3429impl EntryKind {
3430    pub fn is_dir(&self) -> bool {
3431        matches!(
3432            self,
3433            EntryKind::Dir | EntryKind::PendingDir | EntryKind::UnloadedDir
3434        )
3435    }
3436
3437    pub fn is_unloaded(&self) -> bool {
3438        matches!(self, EntryKind::UnloadedDir)
3439    }
3440
3441    pub fn is_file(&self) -> bool {
3442        matches!(self, EntryKind::File)
3443    }
3444}
3445
3446impl sum_tree::Item for Entry {
3447    type Summary = EntrySummary;
3448
3449    fn summary(&self, _cx: ()) -> Self::Summary {
3450        let non_ignored_count = if (self.is_ignored || self.is_external) && !self.is_always_included
3451        {
3452            0
3453        } else {
3454            1
3455        };
3456        let file_count;
3457        let non_ignored_file_count;
3458        if self.is_file() {
3459            file_count = 1;
3460            non_ignored_file_count = non_ignored_count;
3461        } else {
3462            file_count = 0;
3463            non_ignored_file_count = 0;
3464        }
3465
3466        EntrySummary {
3467            max_path: self.path.clone(),
3468            count: 1,
3469            non_ignored_count,
3470            file_count,
3471            non_ignored_file_count,
3472        }
3473    }
3474}
3475
3476impl sum_tree::KeyedItem for Entry {
3477    type Key = PathKey;
3478
3479    fn key(&self) -> Self::Key {
3480        PathKey(self.path.clone())
3481    }
3482}
3483
3484#[derive(Clone, Debug)]
3485pub struct EntrySummary {
3486    max_path: Arc<RelPath>,
3487    count: usize,
3488    non_ignored_count: usize,
3489    file_count: usize,
3490    non_ignored_file_count: usize,
3491}
3492
3493impl Default for EntrySummary {
3494    fn default() -> Self {
3495        Self {
3496            max_path: Arc::from(RelPath::empty()),
3497            count: 0,
3498            non_ignored_count: 0,
3499            file_count: 0,
3500            non_ignored_file_count: 0,
3501        }
3502    }
3503}
3504
3505impl sum_tree::ContextLessSummary for EntrySummary {
3506    fn zero() -> Self {
3507        Default::default()
3508    }
3509
3510    fn add_summary(&mut self, rhs: &Self) {
3511        self.max_path = rhs.max_path.clone();
3512        self.count += rhs.count;
3513        self.non_ignored_count += rhs.non_ignored_count;
3514        self.file_count += rhs.file_count;
3515        self.non_ignored_file_count += rhs.non_ignored_file_count;
3516    }
3517}
3518
3519#[derive(Clone, Debug)]
3520struct PathEntry {
3521    id: ProjectEntryId,
3522    path: Arc<RelPath>,
3523    is_ignored: bool,
3524    scan_id: usize,
3525}
3526
3527impl sum_tree::Item for PathEntry {
3528    type Summary = PathEntrySummary;
3529
3530    fn summary(&self, _cx: ()) -> Self::Summary {
3531        PathEntrySummary { max_id: self.id }
3532    }
3533}
3534
3535impl sum_tree::KeyedItem for PathEntry {
3536    type Key = ProjectEntryId;
3537
3538    fn key(&self) -> Self::Key {
3539        self.id
3540    }
3541}
3542
3543#[derive(Clone, Debug, Default)]
3544struct PathEntrySummary {
3545    max_id: ProjectEntryId,
3546}
3547
3548impl sum_tree::ContextLessSummary for PathEntrySummary {
3549    fn zero() -> Self {
3550        Default::default()
3551    }
3552
3553    fn add_summary(&mut self, summary: &Self) {
3554        self.max_id = summary.max_id;
3555    }
3556}
3557
3558impl<'a> sum_tree::Dimension<'a, PathEntrySummary> for ProjectEntryId {
3559    fn zero(_cx: ()) -> Self {
3560        Default::default()
3561    }
3562
3563    fn add_summary(&mut self, summary: &'a PathEntrySummary, _: ()) {
3564        *self = summary.max_id;
3565    }
3566}
3567
3568#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
3569pub struct PathKey(pub Arc<RelPath>);
3570
3571impl Default for PathKey {
3572    fn default() -> Self {
3573        Self(RelPath::empty().into())
3574    }
3575}
3576
3577impl<'a> sum_tree::Dimension<'a, EntrySummary> for PathKey {
3578    fn zero(_cx: ()) -> Self {
3579        Default::default()
3580    }
3581
3582    fn add_summary(&mut self, summary: &'a EntrySummary, _: ()) {
3583        self.0 = summary.max_path.clone();
3584    }
3585}
3586
3587struct BackgroundScanner {
3588    state: async_lock::Mutex<BackgroundScannerState>,
3589    fs: Arc<dyn Fs>,
3590    fs_case_sensitive: bool,
3591    status_updates_tx: UnboundedSender<ScanState>,
3592    executor: BackgroundExecutor,
3593    scan_requests_rx: channel::Receiver<ScanRequest>,
3594    path_prefixes_to_scan_rx: channel::Receiver<PathPrefixScanRequest>,
3595    next_entry_id: Arc<AtomicUsize>,
3596    phase: BackgroundScannerPhase,
3597    watcher: Arc<dyn Watcher>,
3598    settings: WorktreeSettings,
3599    share_private_files: bool,
3600}
3601
3602#[derive(Copy, Clone, PartialEq)]
3603enum BackgroundScannerPhase {
3604    InitialScan,
3605    EventsReceivedDuringInitialScan,
3606    Events,
3607}
3608
3609impl BackgroundScanner {
3610    async fn run(&mut self, mut fs_events_rx: Pin<Box<dyn Send + Stream<Item = Vec<PathEvent>>>>) {
3611        // If the worktree root does not contain a git repository, then find
3612        // the git repository in an ancestor directory. Find any gitignore files
3613        // in ancestor directories.
3614        let root_abs_path = self.state.lock().await.snapshot.abs_path.clone();
3615        let (ignores, repo) = discover_ancestor_git_repo(self.fs.clone(), &root_abs_path).await;
3616        self.state
3617            .lock()
3618            .await
3619            .snapshot
3620            .ignores_by_parent_abs_path
3621            .extend(ignores);
3622        let containing_git_repository = if let Some((ancestor_dot_git, work_directory)) = repo {
3623            maybe!(async {
3624                self.state
3625                    .lock()
3626                    .await
3627                    .insert_git_repository_for_path(
3628                        work_directory,
3629                        ancestor_dot_git.clone().into(),
3630                        self.fs.as_ref(),
3631                        self.watcher.as_ref(),
3632                    )
3633                    .await
3634                    .log_err()?;
3635                Some(ancestor_dot_git)
3636            })
3637            .await
3638        } else {
3639            None
3640        };
3641
3642        log::trace!("containing git repository: {containing_git_repository:?}");
3643
3644        let mut global_gitignore_events = if let Some(global_gitignore_path) =
3645            &paths::global_gitignore_path()
3646        {
3647            let is_file = self.fs.is_file(&global_gitignore_path).await;
3648            self.state.lock().await.snapshot.global_gitignore = if is_file {
3649                build_gitignore(global_gitignore_path, self.fs.as_ref())
3650                    .await
3651                    .ok()
3652                    .map(Arc::new)
3653            } else {
3654                None
3655            };
3656            if is_file
3657                || matches!(global_gitignore_path.parent(), Some(path) if self.fs.is_dir(path).await)
3658            {
3659                self.fs
3660                    .watch(global_gitignore_path, FS_WATCH_LATENCY)
3661                    .await
3662                    .0
3663            } else {
3664                Box::pin(futures::stream::pending())
3665            }
3666        } else {
3667            self.state.lock().await.snapshot.global_gitignore = None;
3668            Box::pin(futures::stream::pending())
3669        };
3670
3671        let (scan_job_tx, scan_job_rx) = channel::unbounded();
3672        {
3673            let mut state = self.state.lock().await;
3674            state.snapshot.scan_id += 1;
3675            if let Some(mut root_entry) = state.snapshot.root_entry().cloned() {
3676                let ignore_stack = state
3677                    .snapshot
3678                    .ignore_stack_for_abs_path(root_abs_path.as_path(), true, self.fs.as_ref())
3679                    .await;
3680                if ignore_stack.is_abs_path_ignored(root_abs_path.as_path(), true) {
3681                    root_entry.is_ignored = true;
3682                    state
3683                        .insert_entry(root_entry.clone(), self.fs.as_ref(), self.watcher.as_ref())
3684                        .await;
3685                }
3686                if root_entry.is_dir() {
3687                    state
3688                        .enqueue_scan_dir(
3689                            root_abs_path.as_path().into(),
3690                            &root_entry,
3691                            &scan_job_tx,
3692                            self.fs.as_ref(),
3693                        )
3694                        .await;
3695                }
3696            }
3697        };
3698
3699        // Perform an initial scan of the directory.
3700        drop(scan_job_tx);
3701        self.scan_dirs(true, scan_job_rx).await;
3702        {
3703            let mut state = self.state.lock().await;
3704            state.snapshot.completed_scan_id = state.snapshot.scan_id;
3705        }
3706
3707        self.send_status_update(false, SmallVec::new()).await;
3708
3709        // Process any any FS events that occurred while performing the initial scan.
3710        // For these events, update events cannot be as precise, because we didn't
3711        // have the previous state loaded yet.
3712        self.phase = BackgroundScannerPhase::EventsReceivedDuringInitialScan;
3713        if let Poll::Ready(Some(mut paths)) = futures::poll!(fs_events_rx.next()) {
3714            while let Poll::Ready(Some(more_paths)) = futures::poll!(fs_events_rx.next()) {
3715                paths.extend(more_paths);
3716            }
3717            self.process_events(
3718                paths
3719                    .into_iter()
3720                    .filter(|e| e.kind.is_some())
3721                    .map(Into::into)
3722                    .collect(),
3723            )
3724            .await;
3725        }
3726        if let Some(abs_path) = containing_git_repository {
3727            self.process_events(vec![abs_path]).await;
3728        }
3729
3730        // Continue processing events until the worktree is dropped.
3731        self.phase = BackgroundScannerPhase::Events;
3732
3733        loop {
3734            select_biased! {
3735                // Process any path refresh requests from the worktree. Prioritize
3736                // these before handling changes reported by the filesystem.
3737                request = self.next_scan_request().fuse() => {
3738                    let Ok(request) = request else { break };
3739                    if !self.process_scan_request(request, false).await {
3740                        return;
3741                    }
3742                }
3743
3744                path_prefix_request = self.path_prefixes_to_scan_rx.recv().fuse() => {
3745                    let Ok(request) = path_prefix_request else { break };
3746                    log::trace!("adding path prefix {:?}", request.path);
3747
3748                    let did_scan = self.forcibly_load_paths(std::slice::from_ref(&request.path)).await;
3749                    if did_scan {
3750                        let abs_path =
3751                        {
3752                            let mut state = self.state.lock().await;
3753                            state.path_prefixes_to_scan.insert(request.path.clone());
3754                            state.snapshot.absolutize(&request.path)
3755                        };
3756
3757                        if let Some(abs_path) = self.fs.canonicalize(&abs_path).await.log_err() {
3758                            self.process_events(vec![abs_path]).await;
3759                        }
3760                    }
3761                    self.send_status_update(false, request.done).await;
3762                }
3763
3764                paths = fs_events_rx.next().fuse() => {
3765                    let Some(mut paths) = paths else { break };
3766                    while let Poll::Ready(Some(more_paths)) = futures::poll!(fs_events_rx.next()) {
3767                        paths.extend(more_paths);
3768                    }
3769                    self.process_events(paths.into_iter().filter(|e| e.kind.is_some()).map(Into::into).collect()).await;
3770                }
3771
3772                paths = global_gitignore_events.next().fuse() => {
3773                    match paths.as_deref() {
3774                        Some([event, ..]) => {
3775                            self.update_global_gitignore(&event.path).await;
3776                        }
3777                        _ => (),
3778                    }
3779                }
3780            }
3781        }
3782    }
3783
3784    async fn process_scan_request(&self, mut request: ScanRequest, scanning: bool) -> bool {
3785        log::debug!("rescanning paths {:?}", request.relative_paths);
3786
3787        request.relative_paths.sort_unstable();
3788        self.forcibly_load_paths(&request.relative_paths).await;
3789
3790        let root_path = self.state.lock().await.snapshot.abs_path.clone();
3791        let root_canonical_path = self.fs.canonicalize(root_path.as_path()).await;
3792        let root_canonical_path = match &root_canonical_path {
3793            Ok(path) => SanitizedPath::new(path),
3794            Err(err) => {
3795                log::error!("failed to canonicalize root path {root_path:?}: {err}");
3796                return true;
3797            }
3798        };
3799        let abs_paths = request
3800            .relative_paths
3801            .iter()
3802            .map(|path| {
3803                if path.file_name().is_some() {
3804                    root_canonical_path.as_path().join(path.as_std_path())
3805                } else {
3806                    root_canonical_path.as_path().to_path_buf()
3807                }
3808            })
3809            .collect::<Vec<_>>();
3810
3811        {
3812            let mut state = self.state.lock().await;
3813            let is_idle = state.snapshot.completed_scan_id == state.snapshot.scan_id;
3814            state.snapshot.scan_id += 1;
3815            if is_idle {
3816                state.snapshot.completed_scan_id = state.snapshot.scan_id;
3817            }
3818        }
3819
3820        self.reload_entries_for_paths(
3821            &root_path,
3822            &root_canonical_path,
3823            &request.relative_paths,
3824            abs_paths,
3825            None,
3826        )
3827        .await;
3828
3829        self.send_status_update(scanning, request.done).await
3830    }
3831
3832    async fn process_events(&self, mut abs_paths: Vec<PathBuf>) {
3833        log::trace!("process events: {abs_paths:?}");
3834        let root_path = self.state.lock().await.snapshot.abs_path.clone();
3835        let root_canonical_path = self.fs.canonicalize(root_path.as_path()).await;
3836        let root_canonical_path = match &root_canonical_path {
3837            Ok(path) => SanitizedPath::new(path),
3838            Err(err) => {
3839                let new_path = self
3840                    .state
3841                    .lock()
3842                    .await
3843                    .snapshot
3844                    .root_file_handle
3845                    .clone()
3846                    .and_then(|handle| handle.current_path(&self.fs).log_err())
3847                    .map(|path| SanitizedPath::new_arc(&path))
3848                    .filter(|new_path| *new_path != root_path);
3849
3850                if let Some(new_path) = new_path {
3851                    log::info!(
3852                        "root renamed from {} to {}",
3853                        root_path.as_path().display(),
3854                        new_path.as_path().display()
3855                    );
3856                    self.status_updates_tx
3857                        .unbounded_send(ScanState::RootUpdated { new_path })
3858                        .ok();
3859                } else {
3860                    log::warn!("root path could not be canonicalized: {:#}", err);
3861                }
3862                return;
3863            }
3864        };
3865
3866        // Certain directories may have FS changes, but do not lead to git data changes that Zed cares about.
3867        // Ignore these, to avoid Zed unnecessarily rescanning git metadata.
3868        let skipped_files_in_dot_git = [COMMIT_MESSAGE, INDEX_LOCK];
3869        let skipped_dirs_in_dot_git = [FSMONITOR_DAEMON, LFS_DIR];
3870
3871        let mut relative_paths = Vec::with_capacity(abs_paths.len());
3872        let mut dot_git_abs_paths = Vec::new();
3873        abs_paths.sort_unstable();
3874        abs_paths.dedup_by(|a, b| a.starts_with(b));
3875        {
3876            let snapshot = &self.state.lock().await.snapshot;
3877            abs_paths.retain(|abs_path| {
3878            let abs_path = &SanitizedPath::new(abs_path);
3879
3880
3881            {
3882                let mut is_git_related = false;
3883
3884                let dot_git_paths = self.executor.block(maybe!(async  {
3885                    let mut path = None;
3886                    for ancestor in abs_path.as_path().ancestors() {
3887
3888                    if is_git_dir(ancestor, self.fs.as_ref()).await {
3889                        let path_in_git_dir = abs_path
3890                            .as_path()
3891                            .strip_prefix(ancestor)
3892                            .expect("stripping off the ancestor");
3893                       path = Some((ancestor.to_owned(), path_in_git_dir.to_owned()));
3894                       break;
3895                    }
3896                    }
3897                    path
3898
3899                }));
3900
3901                if let Some((dot_git_abs_path, path_in_git_dir)) = dot_git_paths {
3902                    if skipped_files_in_dot_git
3903                        .iter()
3904                        .any(|skipped| OsStr::new(skipped) == path_in_git_dir.as_path().as_os_str())
3905                        || skipped_dirs_in_dot_git.iter().any(|skipped_git_subdir| {
3906                            path_in_git_dir.starts_with(skipped_git_subdir)
3907                        })
3908                    {
3909                        log::debug!("ignoring event {abs_path:?} as it's in the .git directory among skipped files or directories");
3910                        return false;
3911                    }
3912
3913                    is_git_related = true;
3914                    if !dot_git_abs_paths.contains(&dot_git_abs_path) {
3915                        dot_git_abs_paths.push(dot_git_abs_path);
3916                    }
3917                }
3918
3919                let relative_path = if let Ok(path) =
3920                    abs_path.strip_prefix(&root_canonical_path)
3921                    && let Ok(path) = RelPath::new(path, PathStyle::local())
3922                {
3923                    path
3924                } else {
3925                    if is_git_related {
3926                        log::debug!(
3927                            "ignoring event {abs_path:?}, since it's in git dir outside of root path {root_canonical_path:?}",
3928                        );
3929                    } else {
3930                        log::error!(
3931                          "ignoring event {abs_path:?} outside of root path {root_canonical_path:?}",
3932                        );
3933                    }
3934                    return false;
3935                };
3936
3937                if abs_path.file_name() == Some(OsStr::new(GITIGNORE)) {
3938                    for (_, repo) in snapshot
3939                        .git_repositories
3940                        .iter()
3941                        .filter(|(_, repo)| repo.directory_contains(&relative_path))
3942                    {
3943                        if !dot_git_abs_paths.iter().any(|dot_git_abs_path| {
3944                            dot_git_abs_path == repo.common_dir_abs_path.as_ref()
3945                        }) {
3946                            dot_git_abs_paths.push(repo.common_dir_abs_path.to_path_buf());
3947                        }
3948                    }
3949                }
3950
3951                let parent_dir_is_loaded = relative_path.parent().is_none_or(|parent| {
3952                    snapshot
3953                        .entry_for_path(parent)
3954                        .is_some_and(|entry| entry.kind == EntryKind::Dir)
3955                });
3956                if !parent_dir_is_loaded {
3957                    log::debug!("ignoring event {relative_path:?} within unloaded directory");
3958                    return false;
3959                }
3960
3961                if self.settings.is_path_excluded(&relative_path) {
3962                    if !is_git_related {
3963                        log::debug!("ignoring FS event for excluded path {relative_path:?}");
3964                    }
3965                    return false;
3966                }
3967
3968                relative_paths.push(relative_path.into_arc());
3969                true
3970            }
3971        });
3972        }
3973        if relative_paths.is_empty() && dot_git_abs_paths.is_empty() {
3974            return;
3975        }
3976
3977        self.state.lock().await.snapshot.scan_id += 1;
3978
3979        let (scan_job_tx, scan_job_rx) = channel::unbounded();
3980        log::debug!("received fs events {:?}", relative_paths);
3981        self.reload_entries_for_paths(
3982            &root_path,
3983            &root_canonical_path,
3984            &relative_paths,
3985            abs_paths,
3986            Some(scan_job_tx.clone()),
3987        )
3988        .await;
3989
3990        let affected_repo_roots = if !dot_git_abs_paths.is_empty() {
3991            self.update_git_repositories(dot_git_abs_paths).await
3992        } else {
3993            Vec::new()
3994        };
3995
3996        {
3997            let mut ignores_to_update = self.ignores_needing_update().await;
3998            ignores_to_update.extend(affected_repo_roots);
3999            let ignores_to_update = self.order_ignores(ignores_to_update).await;
4000            let snapshot = self.state.lock().await.snapshot.clone();
4001            self.update_ignore_statuses_for_paths(scan_job_tx, snapshot, ignores_to_update)
4002                .await;
4003            self.scan_dirs(false, scan_job_rx).await;
4004        }
4005
4006        {
4007            let mut state = self.state.lock().await;
4008            state.snapshot.completed_scan_id = state.snapshot.scan_id;
4009            for (_, entry) in mem::take(&mut state.removed_entries) {
4010                state.scanned_dirs.remove(&entry.id);
4011            }
4012        }
4013        self.send_status_update(false, SmallVec::new()).await;
4014    }
4015
4016    async fn update_global_gitignore(&self, abs_path: &Path) {
4017        let ignore = build_gitignore(abs_path, self.fs.as_ref())
4018            .await
4019            .log_err()
4020            .map(Arc::new);
4021        let (prev_snapshot, ignore_stack, abs_path) = {
4022            let mut state = self.state.lock().await;
4023            state.snapshot.global_gitignore = ignore;
4024            let abs_path = state.snapshot.abs_path().clone();
4025            let ignore_stack = state
4026                .snapshot
4027                .ignore_stack_for_abs_path(&abs_path, true, self.fs.as_ref())
4028                .await;
4029            (state.snapshot.clone(), ignore_stack, abs_path)
4030        };
4031        let (scan_job_tx, scan_job_rx) = channel::unbounded();
4032        self.update_ignore_statuses_for_paths(
4033            scan_job_tx,
4034            prev_snapshot,
4035            vec![(abs_path, ignore_stack)],
4036        )
4037        .await;
4038        self.scan_dirs(false, scan_job_rx).await;
4039        self.send_status_update(false, SmallVec::new()).await;
4040    }
4041
4042    async fn forcibly_load_paths(&self, paths: &[Arc<RelPath>]) -> bool {
4043        let (scan_job_tx, scan_job_rx) = channel::unbounded();
4044        {
4045            let mut state = self.state.lock().await;
4046            let root_path = state.snapshot.abs_path.clone();
4047            for path in paths {
4048                for ancestor in path.ancestors() {
4049                    if let Some(entry) = state.snapshot.entry_for_path(ancestor)
4050                        && entry.kind == EntryKind::UnloadedDir
4051                    {
4052                        let abs_path = root_path.join(ancestor.as_std_path());
4053                        state
4054                            .enqueue_scan_dir(
4055                                abs_path.into(),
4056                                entry,
4057                                &scan_job_tx,
4058                                self.fs.as_ref(),
4059                            )
4060                            .await;
4061                        state.paths_to_scan.insert(path.clone());
4062                        break;
4063                    }
4064                }
4065            }
4066            drop(scan_job_tx);
4067        }
4068        while let Ok(job) = scan_job_rx.recv().await {
4069            self.scan_dir(&job).await.log_err();
4070        }
4071
4072        !mem::take(&mut self.state.lock().await.paths_to_scan).is_empty()
4073    }
4074
4075    async fn scan_dirs(
4076        &self,
4077        enable_progress_updates: bool,
4078        scan_jobs_rx: channel::Receiver<ScanJob>,
4079    ) {
4080        if self
4081            .status_updates_tx
4082            .unbounded_send(ScanState::Started)
4083            .is_err()
4084        {
4085            return;
4086        }
4087
4088        let progress_update_count = AtomicUsize::new(0);
4089        self.executor
4090            .scoped(|scope| {
4091                for _ in 0..self.executor.num_cpus() {
4092                    scope.spawn(async {
4093                        let mut last_progress_update_count = 0;
4094                        let progress_update_timer = self.progress_timer(enable_progress_updates).fuse();
4095                        futures::pin_mut!(progress_update_timer);
4096
4097                        loop {
4098                            select_biased! {
4099                                // Process any path refresh requests before moving on to process
4100                                // the scan queue, so that user operations are prioritized.
4101                                request = self.next_scan_request().fuse() => {
4102                                    let Ok(request) = request else { break };
4103                                    if !self.process_scan_request(request, true).await {
4104                                        return;
4105                                    }
4106                                }
4107
4108                                // Send periodic progress updates to the worktree. Use an atomic counter
4109                                // to ensure that only one of the workers sends a progress update after
4110                                // the update interval elapses.
4111                                _ = progress_update_timer => {
4112                                    match progress_update_count.compare_exchange(
4113                                        last_progress_update_count,
4114                                        last_progress_update_count + 1,
4115                                        SeqCst,
4116                                        SeqCst
4117                                    ) {
4118                                        Ok(_) => {
4119                                            last_progress_update_count += 1;
4120                                            self.send_status_update(true, SmallVec::new()).await;
4121                                        }
4122                                        Err(count) => {
4123                                            last_progress_update_count = count;
4124                                        }
4125                                    }
4126                                    progress_update_timer.set(self.progress_timer(enable_progress_updates).fuse());
4127                                }
4128
4129                                // Recursively load directories from the file system.
4130                                job = scan_jobs_rx.recv().fuse() => {
4131                                    let Ok(job) = job else { break };
4132                                    if let Err(err) = self.scan_dir(&job).await
4133                                        && job.path.is_empty() {
4134                                            log::error!("error scanning directory {:?}: {}", job.abs_path, err);
4135                                        }
4136                                }
4137                            }
4138                        }
4139                    });
4140                }
4141            })
4142            .await;
4143    }
4144
4145    async fn send_status_update(
4146        &self,
4147        scanning: bool,
4148        barrier: SmallVec<[barrier::Sender; 1]>,
4149    ) -> bool {
4150        let mut state = self.state.lock().await;
4151        if state.changed_paths.is_empty() && scanning {
4152            return true;
4153        }
4154
4155        let new_snapshot = state.snapshot.clone();
4156        let old_snapshot = mem::replace(&mut state.prev_snapshot, new_snapshot.snapshot.clone());
4157        let changes = build_diff(
4158            self.phase,
4159            &old_snapshot,
4160            &new_snapshot,
4161            &state.changed_paths,
4162        );
4163        state.changed_paths.clear();
4164
4165        self.status_updates_tx
4166            .unbounded_send(ScanState::Updated {
4167                snapshot: new_snapshot,
4168                changes,
4169                scanning,
4170                barrier,
4171            })
4172            .is_ok()
4173    }
4174
4175    async fn scan_dir(&self, job: &ScanJob) -> Result<()> {
4176        let root_abs_path;
4177        let root_char_bag;
4178        {
4179            let snapshot = &self.state.lock().await.snapshot;
4180            if self.settings.is_path_excluded(&job.path) {
4181                log::error!("skipping excluded directory {:?}", job.path);
4182                return Ok(());
4183            }
4184            log::trace!("scanning directory {:?}", job.path);
4185            root_abs_path = snapshot.abs_path().clone();
4186            root_char_bag = snapshot.root_char_bag;
4187        }
4188
4189        let next_entry_id = self.next_entry_id.clone();
4190        let mut ignore_stack = job.ignore_stack.clone();
4191        let mut new_ignore = None;
4192        let mut root_canonical_path = None;
4193        let mut new_entries: Vec<Entry> = Vec::new();
4194        let mut new_jobs: Vec<Option<ScanJob>> = Vec::new();
4195        let mut child_paths = self
4196            .fs
4197            .read_dir(&job.abs_path)
4198            .await?
4199            .filter_map(|entry| async {
4200                match entry {
4201                    Ok(entry) => Some(entry),
4202                    Err(error) => {
4203                        log::error!("error processing entry {:?}", error);
4204                        None
4205                    }
4206                }
4207            })
4208            .collect::<Vec<_>>()
4209            .await;
4210
4211        // Ensure that .git and .gitignore are processed first.
4212        swap_to_front(&mut child_paths, GITIGNORE);
4213        swap_to_front(&mut child_paths, DOT_GIT);
4214
4215        if let Some(path) = child_paths.first()
4216            && path.ends_with(DOT_GIT)
4217        {
4218            ignore_stack.repo_root = Some(job.abs_path.clone());
4219        }
4220
4221        for child_abs_path in child_paths {
4222            let child_abs_path: Arc<Path> = child_abs_path.into();
4223            let child_name = child_abs_path.file_name().unwrap();
4224            let Some(child_path) = child_name
4225                .to_str()
4226                .and_then(|name| Some(job.path.join(RelPath::unix(name).ok()?)))
4227            else {
4228                continue;
4229            };
4230
4231            if child_name == DOT_GIT {
4232                let mut state = self.state.lock().await;
4233                state
4234                    .insert_git_repository(
4235                        child_path.clone(),
4236                        self.fs.as_ref(),
4237                        self.watcher.as_ref(),
4238                    )
4239                    .await;
4240            } else if child_name == GITIGNORE {
4241                match build_gitignore(&child_abs_path, self.fs.as_ref()).await {
4242                    Ok(ignore) => {
4243                        let ignore = Arc::new(ignore);
4244                        ignore_stack = ignore_stack.append(job.abs_path.clone(), ignore.clone());
4245                        new_ignore = Some(ignore);
4246                    }
4247                    Err(error) => {
4248                        log::error!(
4249                            "error loading .gitignore file {:?} - {:?}",
4250                            child_name,
4251                            error
4252                        );
4253                    }
4254                }
4255            }
4256
4257            if self.settings.is_path_excluded(&child_path) {
4258                log::debug!("skipping excluded child entry {child_path:?}");
4259                self.state.lock().await.remove_path(&child_path);
4260                continue;
4261            }
4262
4263            let child_metadata = match self.fs.metadata(&child_abs_path).await {
4264                Ok(Some(metadata)) => metadata,
4265                Ok(None) => continue,
4266                Err(err) => {
4267                    log::error!("error processing {child_abs_path:?}: {err:?}");
4268                    continue;
4269                }
4270            };
4271
4272            let mut child_entry = Entry::new(
4273                child_path.clone(),
4274                &child_metadata,
4275                &next_entry_id,
4276                root_char_bag,
4277                None,
4278            );
4279
4280            if job.is_external {
4281                child_entry.is_external = true;
4282            } else if child_metadata.is_symlink {
4283                let canonical_path = match self.fs.canonicalize(&child_abs_path).await {
4284                    Ok(path) => path,
4285                    Err(err) => {
4286                        log::error!("error reading target of symlink {child_abs_path:?}: {err:#}",);
4287                        continue;
4288                    }
4289                };
4290
4291                // lazily canonicalize the root path in order to determine if
4292                // symlinks point outside of the worktree.
4293                let root_canonical_path = match &root_canonical_path {
4294                    Some(path) => path,
4295                    None => match self.fs.canonicalize(&root_abs_path).await {
4296                        Ok(path) => root_canonical_path.insert(path),
4297                        Err(err) => {
4298                            log::error!("error canonicalizing root {:?}: {:?}", root_abs_path, err);
4299                            continue;
4300                        }
4301                    },
4302                };
4303
4304                if !canonical_path.starts_with(root_canonical_path) {
4305                    child_entry.is_external = true;
4306                }
4307
4308                child_entry.canonical_path = Some(canonical_path.into());
4309            }
4310
4311            child_entry.is_hidden = job.is_hidden
4312                || child_name
4313                    .to_str()
4314                    .map_or(false, |name| is_path_hidden(name));
4315
4316            if child_entry.is_dir() {
4317                child_entry.is_ignored = ignore_stack.is_abs_path_ignored(&child_abs_path, true);
4318                child_entry.is_always_included = self.settings.is_path_always_included(&child_path);
4319
4320                // Avoid recursing until crash in the case of a recursive symlink
4321                if job.ancestor_inodes.contains(&child_entry.inode) {
4322                    new_jobs.push(None);
4323                } else {
4324                    let mut ancestor_inodes = job.ancestor_inodes.clone();
4325                    ancestor_inodes.insert(child_entry.inode);
4326
4327                    new_jobs.push(Some(ScanJob {
4328                        abs_path: child_abs_path.clone(),
4329                        path: child_path,
4330                        is_external: child_entry.is_external,
4331                        is_hidden: child_entry.is_hidden,
4332                        ignore_stack: if child_entry.is_ignored {
4333                            IgnoreStack::all()
4334                        } else {
4335                            ignore_stack.clone()
4336                        },
4337                        ancestor_inodes,
4338                        scan_queue: job.scan_queue.clone(),
4339                    }));
4340                }
4341            } else {
4342                child_entry.is_ignored = ignore_stack.is_abs_path_ignored(&child_abs_path, false);
4343                child_entry.is_always_included = self.settings.is_path_always_included(&child_path);
4344            }
4345
4346            {
4347                let relative_path = job
4348                    .path
4349                    .join(RelPath::unix(child_name.to_str().unwrap()).unwrap());
4350                if self.is_path_private(&relative_path) {
4351                    log::debug!("detected private file: {relative_path:?}");
4352                    child_entry.is_private = true;
4353                }
4354            }
4355
4356            new_entries.push(child_entry);
4357        }
4358
4359        let mut state = self.state.lock().await;
4360
4361        // Identify any subdirectories that should not be scanned.
4362        let mut job_ix = 0;
4363        for entry in &mut new_entries {
4364            state.reuse_entry_id(entry);
4365            if entry.is_dir() {
4366                if state.should_scan_directory(entry) {
4367                    job_ix += 1;
4368                } else {
4369                    log::debug!("defer scanning directory {:?}", entry.path);
4370                    entry.kind = EntryKind::UnloadedDir;
4371                    new_jobs.remove(job_ix);
4372                }
4373            }
4374            if entry.is_always_included {
4375                state
4376                    .snapshot
4377                    .always_included_entries
4378                    .push(entry.path.clone());
4379            }
4380        }
4381
4382        state.populate_dir(job.path.clone(), new_entries, new_ignore);
4383        self.watcher.add(job.abs_path.as_ref()).log_err();
4384
4385        for new_job in new_jobs.into_iter().flatten() {
4386            job.scan_queue
4387                .try_send(new_job)
4388                .expect("channel is unbounded");
4389        }
4390
4391        Ok(())
4392    }
4393
4394    /// All list arguments should be sorted before calling this function
4395    async fn reload_entries_for_paths(
4396        &self,
4397        root_abs_path: &SanitizedPath,
4398        root_canonical_path: &SanitizedPath,
4399        relative_paths: &[Arc<RelPath>],
4400        abs_paths: Vec<PathBuf>,
4401        scan_queue_tx: Option<Sender<ScanJob>>,
4402    ) {
4403        // grab metadata for all requested paths
4404        let metadata = futures::future::join_all(
4405            abs_paths
4406                .iter()
4407                .map(|abs_path| async move {
4408                    let metadata = self.fs.metadata(abs_path).await?;
4409                    if let Some(metadata) = metadata {
4410                        let canonical_path = self.fs.canonicalize(abs_path).await?;
4411
4412                        // If we're on a case-insensitive filesystem (default on macOS), we want
4413                        // to only ignore metadata for non-symlink files if their absolute-path matches
4414                        // the canonical-path.
4415                        // Because if not, this might be a case-only-renaming (`mv test.txt TEST.TXT`)
4416                        // and we want to ignore the metadata for the old path (`test.txt`) so it's
4417                        // treated as removed.
4418                        if !self.fs_case_sensitive && !metadata.is_symlink {
4419                            let canonical_file_name = canonical_path.file_name();
4420                            let file_name = abs_path.file_name();
4421                            if canonical_file_name != file_name {
4422                                return Ok(None);
4423                            }
4424                        }
4425
4426                        anyhow::Ok(Some((metadata, SanitizedPath::new_arc(&canonical_path))))
4427                    } else {
4428                        Ok(None)
4429                    }
4430                })
4431                .collect::<Vec<_>>(),
4432        )
4433        .await;
4434
4435        let mut new_ancestor_repo = if relative_paths.iter().any(|path| path.is_empty()) {
4436            Some(discover_ancestor_git_repo(self.fs.clone(), &root_abs_path).await)
4437        } else {
4438            None
4439        };
4440
4441        let mut state = self.state.lock().await;
4442        let doing_recursive_update = scan_queue_tx.is_some();
4443
4444        // Remove any entries for paths that no longer exist or are being recursively
4445        // refreshed. Do this before adding any new entries, so that renames can be
4446        // detected regardless of the order of the paths.
4447        for (path, metadata) in relative_paths.iter().zip(metadata.iter()) {
4448            if matches!(metadata, Ok(None)) || doing_recursive_update {
4449                state.remove_path(path);
4450            }
4451        }
4452
4453        for (path, metadata) in relative_paths.iter().zip(metadata.into_iter()) {
4454            let abs_path: Arc<Path> = root_abs_path.join(path.as_std_path()).into();
4455            match metadata {
4456                Ok(Some((metadata, canonical_path))) => {
4457                    let ignore_stack = state
4458                        .snapshot
4459                        .ignore_stack_for_abs_path(&abs_path, metadata.is_dir, self.fs.as_ref())
4460                        .await;
4461                    let is_external = !canonical_path.starts_with(&root_canonical_path);
4462                    let mut fs_entry = Entry::new(
4463                        path.clone(),
4464                        &metadata,
4465                        self.next_entry_id.as_ref(),
4466                        state.snapshot.root_char_bag,
4467                        if metadata.is_symlink {
4468                            Some(canonical_path.as_path().to_path_buf().into())
4469                        } else {
4470                            None
4471                        },
4472                    );
4473
4474                    let is_dir = fs_entry.is_dir();
4475                    fs_entry.is_ignored = ignore_stack.is_abs_path_ignored(&abs_path, is_dir);
4476                    fs_entry.is_external = is_external;
4477                    fs_entry.is_private = self.is_path_private(path);
4478                    fs_entry.is_always_included = self.settings.is_path_always_included(path);
4479
4480                    let parent_is_hidden = path
4481                        .parent()
4482                        .and_then(|parent| state.snapshot.entry_for_path(parent))
4483                        .map_or(false, |parent_entry| parent_entry.is_hidden);
4484                    fs_entry.is_hidden = parent_is_hidden
4485                        || path.file_name().map_or(false, |name| is_path_hidden(name));
4486
4487                    if let (Some(scan_queue_tx), true) = (&scan_queue_tx, is_dir) {
4488                        if state.should_scan_directory(&fs_entry)
4489                            || (fs_entry.path.is_empty()
4490                                && abs_path.file_name() == Some(OsStr::new(DOT_GIT)))
4491                        {
4492                            state
4493                                .enqueue_scan_dir(
4494                                    abs_path,
4495                                    &fs_entry,
4496                                    scan_queue_tx,
4497                                    self.fs.as_ref(),
4498                                )
4499                                .await;
4500                        } else {
4501                            fs_entry.kind = EntryKind::UnloadedDir;
4502                        }
4503                    }
4504
4505                    state
4506                        .insert_entry(fs_entry.clone(), self.fs.as_ref(), self.watcher.as_ref())
4507                        .await;
4508
4509                    if path.is_empty()
4510                        && let Some((ignores, repo)) = new_ancestor_repo.take()
4511                    {
4512                        log::trace!("updating ancestor git repository");
4513                        state.snapshot.ignores_by_parent_abs_path.extend(ignores);
4514                        if let Some((ancestor_dot_git, work_directory)) = repo {
4515                            state
4516                                .insert_git_repository_for_path(
4517                                    work_directory,
4518                                    ancestor_dot_git.into(),
4519                                    self.fs.as_ref(),
4520                                    self.watcher.as_ref(),
4521                                )
4522                                .await
4523                                .log_err();
4524                        }
4525                    }
4526                }
4527                Ok(None) => {
4528                    self.remove_repo_path(path.clone(), &mut state.snapshot);
4529                }
4530                Err(err) => {
4531                    log::error!("error reading file {abs_path:?} on event: {err:#}");
4532                }
4533            }
4534        }
4535
4536        util::extend_sorted(
4537            &mut state.changed_paths,
4538            relative_paths.iter().cloned(),
4539            usize::MAX,
4540            Ord::cmp,
4541        );
4542    }
4543
4544    fn remove_repo_path(&self, path: Arc<RelPath>, snapshot: &mut LocalSnapshot) -> Option<()> {
4545        if !path.components().any(|component| component == DOT_GIT)
4546            && let Some(local_repo) = snapshot.local_repo_for_work_directory_path(&path)
4547        {
4548            let id = local_repo.work_directory_id;
4549            log::debug!("remove repo path: {:?}", path);
4550            snapshot.git_repositories.remove(&id);
4551            return Some(());
4552        }
4553
4554        Some(())
4555    }
4556
4557    async fn update_ignore_statuses_for_paths(
4558        &self,
4559        scan_job_tx: Sender<ScanJob>,
4560        prev_snapshot: LocalSnapshot,
4561        ignores_to_update: Vec<(Arc<Path>, IgnoreStack)>,
4562    ) {
4563        let (ignore_queue_tx, ignore_queue_rx) = channel::unbounded();
4564        {
4565            for (parent_abs_path, ignore_stack) in ignores_to_update {
4566                ignore_queue_tx
4567                    .send_blocking(UpdateIgnoreStatusJob {
4568                        abs_path: parent_abs_path,
4569                        ignore_stack,
4570                        ignore_queue: ignore_queue_tx.clone(),
4571                        scan_queue: scan_job_tx.clone(),
4572                    })
4573                    .unwrap();
4574            }
4575        }
4576        drop(ignore_queue_tx);
4577
4578        self.executor
4579            .scoped(|scope| {
4580                for _ in 0..self.executor.num_cpus() {
4581                    scope.spawn(async {
4582                        loop {
4583                            select_biased! {
4584                                // Process any path refresh requests before moving on to process
4585                                // the queue of ignore statuses.
4586                                request = self.next_scan_request().fuse() => {
4587                                    let Ok(request) = request else { break };
4588                                    if !self.process_scan_request(request, true).await {
4589                                        return;
4590                                    }
4591                                }
4592
4593                                // Recursively process directories whose ignores have changed.
4594                                job = ignore_queue_rx.recv().fuse() => {
4595                                    let Ok(job) = job else { break };
4596                                    self.update_ignore_status(job, &prev_snapshot).await;
4597                                }
4598                            }
4599                        }
4600                    });
4601                }
4602            })
4603            .await;
4604    }
4605
4606    async fn ignores_needing_update(&self) -> Vec<Arc<Path>> {
4607        let mut ignores_to_update = Vec::new();
4608
4609        {
4610            let snapshot = &mut self.state.lock().await.snapshot;
4611            let abs_path = snapshot.abs_path.clone();
4612            snapshot
4613                .ignores_by_parent_abs_path
4614                .retain(|parent_abs_path, (_, needs_update)| {
4615                    if let Ok(parent_path) = parent_abs_path.strip_prefix(abs_path.as_path())
4616                        && let Some(parent_path) =
4617                            RelPath::new(&parent_path, PathStyle::local()).log_err()
4618                    {
4619                        if *needs_update {
4620                            *needs_update = false;
4621                            if snapshot.snapshot.entry_for_path(&parent_path).is_some() {
4622                                ignores_to_update.push(parent_abs_path.clone());
4623                            }
4624                        }
4625
4626                        let ignore_path = parent_path.join(RelPath::unix(GITIGNORE).unwrap());
4627                        if snapshot.snapshot.entry_for_path(&ignore_path).is_none() {
4628                            return false;
4629                        }
4630                    }
4631                    true
4632                });
4633        }
4634
4635        ignores_to_update
4636    }
4637
4638    async fn order_ignores(&self, mut ignores: Vec<Arc<Path>>) -> Vec<(Arc<Path>, IgnoreStack)> {
4639        let fs = self.fs.clone();
4640        let snapshot = self.state.lock().await.snapshot.clone();
4641        ignores.sort_unstable();
4642        let mut ignores_to_update = ignores.into_iter().peekable();
4643
4644        let mut result = vec![];
4645        while let Some(parent_abs_path) = ignores_to_update.next() {
4646            while ignores_to_update
4647                .peek()
4648                .map_or(false, |p| p.starts_with(&parent_abs_path))
4649            {
4650                ignores_to_update.next().unwrap();
4651            }
4652            let ignore_stack = snapshot
4653                .ignore_stack_for_abs_path(&parent_abs_path, true, fs.as_ref())
4654                .await;
4655            result.push((parent_abs_path, ignore_stack));
4656        }
4657
4658        result
4659    }
4660
4661    async fn update_ignore_status(&self, job: UpdateIgnoreStatusJob, snapshot: &LocalSnapshot) {
4662        log::trace!("update ignore status {:?}", job.abs_path);
4663
4664        let mut ignore_stack = job.ignore_stack;
4665        if let Some((ignore, _)) = snapshot.ignores_by_parent_abs_path.get(&job.abs_path) {
4666            ignore_stack = ignore_stack.append(job.abs_path.clone(), ignore.clone());
4667        }
4668
4669        let mut entries_by_id_edits = Vec::new();
4670        let mut entries_by_path_edits = Vec::new();
4671        let Some(path) = job
4672            .abs_path
4673            .strip_prefix(snapshot.abs_path.as_path())
4674            .map_err(|_| {
4675                anyhow::anyhow!(
4676                    "Failed to strip prefix '{}' from path '{}'",
4677                    snapshot.abs_path.as_path().display(),
4678                    job.abs_path.display()
4679                )
4680            })
4681            .log_err()
4682        else {
4683            return;
4684        };
4685
4686        let Some(path) = RelPath::new(&path, PathStyle::local()).log_err() else {
4687            return;
4688        };
4689
4690        if let Ok(Some(metadata)) = self.fs.metadata(&job.abs_path.join(DOT_GIT)).await
4691            && metadata.is_dir
4692        {
4693            ignore_stack.repo_root = Some(job.abs_path.clone());
4694        }
4695
4696        for mut entry in snapshot.child_entries(&path).cloned() {
4697            let was_ignored = entry.is_ignored;
4698            let abs_path: Arc<Path> = snapshot.absolutize(&entry.path).into();
4699            entry.is_ignored = ignore_stack.is_abs_path_ignored(&abs_path, entry.is_dir());
4700
4701            if entry.is_dir() {
4702                let child_ignore_stack = if entry.is_ignored {
4703                    IgnoreStack::all()
4704                } else {
4705                    ignore_stack.clone()
4706                };
4707
4708                // Scan any directories that were previously ignored and weren't previously scanned.
4709                if was_ignored && !entry.is_ignored && entry.kind.is_unloaded() {
4710                    let state = self.state.lock().await;
4711                    if state.should_scan_directory(&entry) {
4712                        state
4713                            .enqueue_scan_dir(
4714                                abs_path.clone(),
4715                                &entry,
4716                                &job.scan_queue,
4717                                self.fs.as_ref(),
4718                            )
4719                            .await;
4720                    }
4721                }
4722
4723                job.ignore_queue
4724                    .send(UpdateIgnoreStatusJob {
4725                        abs_path: abs_path.clone(),
4726                        ignore_stack: child_ignore_stack,
4727                        ignore_queue: job.ignore_queue.clone(),
4728                        scan_queue: job.scan_queue.clone(),
4729                    })
4730                    .await
4731                    .unwrap();
4732            }
4733
4734            if entry.is_ignored != was_ignored {
4735                let mut path_entry = snapshot.entries_by_id.get(&entry.id, ()).unwrap().clone();
4736                path_entry.scan_id = snapshot.scan_id;
4737                path_entry.is_ignored = entry.is_ignored;
4738                entries_by_id_edits.push(Edit::Insert(path_entry));
4739                entries_by_path_edits.push(Edit::Insert(entry));
4740            }
4741        }
4742
4743        let state = &mut self.state.lock().await;
4744        for edit in &entries_by_path_edits {
4745            if let Edit::Insert(entry) = edit
4746                && let Err(ix) = state.changed_paths.binary_search(&entry.path)
4747            {
4748                state.changed_paths.insert(ix, entry.path.clone());
4749            }
4750        }
4751
4752        state
4753            .snapshot
4754            .entries_by_path
4755            .edit(entries_by_path_edits, ());
4756        state.snapshot.entries_by_id.edit(entries_by_id_edits, ());
4757    }
4758
4759    async fn update_git_repositories(&self, dot_git_paths: Vec<PathBuf>) -> Vec<Arc<Path>> {
4760        log::trace!("reloading repositories: {dot_git_paths:?}");
4761        let mut state = self.state.lock().await;
4762        let scan_id = state.snapshot.scan_id;
4763        let mut affected_repo_roots = Vec::new();
4764        for dot_git_dir in dot_git_paths {
4765            let existing_repository_entry =
4766                state
4767                    .snapshot
4768                    .git_repositories
4769                    .iter()
4770                    .find_map(|(_, repo)| {
4771                        let dot_git_dir = SanitizedPath::new(&dot_git_dir);
4772                        if SanitizedPath::new(repo.common_dir_abs_path.as_ref()) == dot_git_dir
4773                            || SanitizedPath::new(repo.repository_dir_abs_path.as_ref())
4774                                == dot_git_dir
4775                        {
4776                            Some(repo.clone())
4777                        } else {
4778                            None
4779                        }
4780                    });
4781
4782            match existing_repository_entry {
4783                None => {
4784                    let Ok(relative) = dot_git_dir.strip_prefix(state.snapshot.abs_path()) else {
4785                        debug_panic!(
4786                            "update_git_repositories called with .git directory outside the worktree root"
4787                        );
4788                        return Vec::new();
4789                    };
4790                    affected_repo_roots.push(dot_git_dir.parent().unwrap().into());
4791                    state
4792                        .insert_git_repository(
4793                            RelPath::new(relative, PathStyle::local())
4794                                .unwrap()
4795                                .into_arc(),
4796                            self.fs.as_ref(),
4797                            self.watcher.as_ref(),
4798                        )
4799                        .await;
4800                }
4801                Some(local_repository) => {
4802                    state.snapshot.git_repositories.update(
4803                        &local_repository.work_directory_id,
4804                        |entry| {
4805                            entry.git_dir_scan_id = scan_id;
4806                        },
4807                    );
4808                }
4809            };
4810        }
4811
4812        // Remove any git repositories whose .git entry no longer exists.
4813        let snapshot = &mut state.snapshot;
4814        let mut ids_to_preserve = HashSet::default();
4815        for (&work_directory_id, entry) in snapshot.git_repositories.iter() {
4816            let exists_in_snapshot =
4817                snapshot
4818                    .entry_for_id(work_directory_id)
4819                    .is_some_and(|entry| {
4820                        snapshot
4821                            .entry_for_path(&entry.path.join(RelPath::unix(DOT_GIT).unwrap()))
4822                            .is_some()
4823                    });
4824
4825            if exists_in_snapshot
4826                || matches!(
4827                    self.fs.metadata(&entry.common_dir_abs_path).await,
4828                    Ok(Some(_))
4829                )
4830            {
4831                ids_to_preserve.insert(work_directory_id);
4832            }
4833        }
4834
4835        snapshot
4836            .git_repositories
4837            .retain(|work_directory_id, entry| {
4838                let preserve = ids_to_preserve.contains(work_directory_id);
4839                if !preserve {
4840                    affected_repo_roots.push(entry.dot_git_abs_path.parent().unwrap().into());
4841                }
4842                preserve
4843            });
4844
4845        affected_repo_roots
4846    }
4847
4848    async fn progress_timer(&self, running: bool) {
4849        if !running {
4850            return futures::future::pending().await;
4851        }
4852
4853        #[cfg(any(test, feature = "test-support"))]
4854        if self.fs.is_fake() {
4855            return self.executor.simulate_random_delay().await;
4856        }
4857
4858        smol::Timer::after(FS_WATCH_LATENCY).await;
4859    }
4860
4861    fn is_path_private(&self, path: &RelPath) -> bool {
4862        !self.share_private_files && self.settings.is_path_private(path)
4863    }
4864
4865    async fn next_scan_request(&self) -> Result<ScanRequest> {
4866        let mut request = self.scan_requests_rx.recv().await?;
4867        while let Ok(next_request) = self.scan_requests_rx.try_recv() {
4868            request.relative_paths.extend(next_request.relative_paths);
4869            request.done.extend(next_request.done);
4870        }
4871        Ok(request)
4872    }
4873}
4874
4875async fn discover_ancestor_git_repo(
4876    fs: Arc<dyn Fs>,
4877    root_abs_path: &SanitizedPath,
4878) -> (
4879    HashMap<Arc<Path>, (Arc<Gitignore>, bool)>,
4880    Option<(PathBuf, WorkDirectory)>,
4881) {
4882    let mut ignores = HashMap::default();
4883    for (index, ancestor) in root_abs_path.as_path().ancestors().enumerate() {
4884        if index != 0 {
4885            if ancestor == paths::home_dir() {
4886                // Unless $HOME is itself the worktree root, don't consider it as a
4887                // containing git repository---expensive and likely unwanted.
4888                break;
4889            } else if let Ok(ignore) = build_gitignore(&ancestor.join(GITIGNORE), fs.as_ref()).await
4890            {
4891                ignores.insert(ancestor.into(), (ignore.into(), false));
4892            }
4893        }
4894
4895        let ancestor_dot_git = ancestor.join(DOT_GIT);
4896        log::trace!("considering ancestor: {ancestor_dot_git:?}");
4897        // Check whether the directory or file called `.git` exists (in the
4898        // case of worktrees it's a file.)
4899        if fs
4900            .metadata(&ancestor_dot_git)
4901            .await
4902            .is_ok_and(|metadata| metadata.is_some())
4903        {
4904            if index != 0 {
4905                // We canonicalize, since the FS events use the canonicalized path.
4906                if let Some(ancestor_dot_git) = fs.canonicalize(&ancestor_dot_git).await.log_err() {
4907                    let location_in_repo = root_abs_path
4908                        .as_path()
4909                        .strip_prefix(ancestor)
4910                        .unwrap()
4911                        .into();
4912                    log::info!("inserting parent git repo for this worktree: {location_in_repo:?}");
4913                    // We associate the external git repo with our root folder and
4914                    // also mark where in the git repo the root folder is located.
4915                    return (
4916                        ignores,
4917                        Some((
4918                            ancestor_dot_git,
4919                            WorkDirectory::AboveProject {
4920                                absolute_path: ancestor.into(),
4921                                location_in_repo,
4922                            },
4923                        )),
4924                    );
4925                };
4926            }
4927
4928            // Reached root of git repository.
4929            break;
4930        }
4931    }
4932
4933    (ignores, None)
4934}
4935
4936fn build_diff(
4937    phase: BackgroundScannerPhase,
4938    old_snapshot: &Snapshot,
4939    new_snapshot: &Snapshot,
4940    event_paths: &[Arc<RelPath>],
4941) -> UpdatedEntriesSet {
4942    use BackgroundScannerPhase::*;
4943    use PathChange::{Added, AddedOrUpdated, Loaded, Removed, Updated};
4944
4945    // Identify which paths have changed. Use the known set of changed
4946    // parent paths to optimize the search.
4947    let mut changes = Vec::new();
4948    let mut old_paths = old_snapshot.entries_by_path.cursor::<PathKey>(());
4949    let mut new_paths = new_snapshot.entries_by_path.cursor::<PathKey>(());
4950    let mut last_newly_loaded_dir_path = None;
4951    old_paths.next();
4952    new_paths.next();
4953    for path in event_paths {
4954        let path = PathKey(path.clone());
4955        if old_paths.item().is_some_and(|e| e.path < path.0) {
4956            old_paths.seek_forward(&path, Bias::Left);
4957        }
4958        if new_paths.item().is_some_and(|e| e.path < path.0) {
4959            new_paths.seek_forward(&path, Bias::Left);
4960        }
4961        loop {
4962            match (old_paths.item(), new_paths.item()) {
4963                (Some(old_entry), Some(new_entry)) => {
4964                    if old_entry.path > path.0
4965                        && new_entry.path > path.0
4966                        && !old_entry.path.starts_with(&path.0)
4967                        && !new_entry.path.starts_with(&path.0)
4968                    {
4969                        break;
4970                    }
4971
4972                    match Ord::cmp(&old_entry.path, &new_entry.path) {
4973                        Ordering::Less => {
4974                            changes.push((old_entry.path.clone(), old_entry.id, Removed));
4975                            old_paths.next();
4976                        }
4977                        Ordering::Equal => {
4978                            if phase == EventsReceivedDuringInitialScan {
4979                                if old_entry.id != new_entry.id {
4980                                    changes.push((old_entry.path.clone(), old_entry.id, Removed));
4981                                }
4982                                // If the worktree was not fully initialized when this event was generated,
4983                                // we can't know whether this entry was added during the scan or whether
4984                                // it was merely updated.
4985                                changes.push((
4986                                    new_entry.path.clone(),
4987                                    new_entry.id,
4988                                    AddedOrUpdated,
4989                                ));
4990                            } else if old_entry.id != new_entry.id {
4991                                changes.push((old_entry.path.clone(), old_entry.id, Removed));
4992                                changes.push((new_entry.path.clone(), new_entry.id, Added));
4993                            } else if old_entry != new_entry {
4994                                if old_entry.kind.is_unloaded() {
4995                                    last_newly_loaded_dir_path = Some(&new_entry.path);
4996                                    changes.push((new_entry.path.clone(), new_entry.id, Loaded));
4997                                } else {
4998                                    changes.push((new_entry.path.clone(), new_entry.id, Updated));
4999                                }
5000                            }
5001                            old_paths.next();
5002                            new_paths.next();
5003                        }
5004                        Ordering::Greater => {
5005                            let is_newly_loaded = phase == InitialScan
5006                                || last_newly_loaded_dir_path
5007                                    .as_ref()
5008                                    .is_some_and(|dir| new_entry.path.starts_with(dir));
5009                            changes.push((
5010                                new_entry.path.clone(),
5011                                new_entry.id,
5012                                if is_newly_loaded { Loaded } else { Added },
5013                            ));
5014                            new_paths.next();
5015                        }
5016                    }
5017                }
5018                (Some(old_entry), None) => {
5019                    changes.push((old_entry.path.clone(), old_entry.id, Removed));
5020                    old_paths.next();
5021                }
5022                (None, Some(new_entry)) => {
5023                    let is_newly_loaded = phase == InitialScan
5024                        || last_newly_loaded_dir_path
5025                            .as_ref()
5026                            .is_some_and(|dir| new_entry.path.starts_with(dir));
5027                    changes.push((
5028                        new_entry.path.clone(),
5029                        new_entry.id,
5030                        if is_newly_loaded { Loaded } else { Added },
5031                    ));
5032                    new_paths.next();
5033                }
5034                (None, None) => break,
5035            }
5036        }
5037    }
5038
5039    changes.into()
5040}
5041
5042fn swap_to_front(child_paths: &mut Vec<PathBuf>, file: &str) {
5043    let position = child_paths
5044        .iter()
5045        .position(|path| path.file_name().unwrap() == file);
5046    if let Some(position) = position {
5047        let temp = child_paths.remove(position);
5048        child_paths.insert(0, temp);
5049    }
5050}
5051
5052fn char_bag_for_path(root_char_bag: CharBag, path: &RelPath) -> CharBag {
5053    let mut result = root_char_bag;
5054    result.extend(path.as_unix_str().chars().map(|c| c.to_ascii_lowercase()));
5055    result
5056}
5057
5058fn is_path_hidden(name: &str) -> bool {
5059    name.starts_with('.')
5060}
5061
5062#[derive(Debug)]
5063struct ScanJob {
5064    abs_path: Arc<Path>,
5065    path: Arc<RelPath>,
5066    ignore_stack: IgnoreStack,
5067    scan_queue: Sender<ScanJob>,
5068    ancestor_inodes: TreeSet<u64>,
5069    is_external: bool,
5070    is_hidden: bool,
5071}
5072
5073struct UpdateIgnoreStatusJob {
5074    abs_path: Arc<Path>,
5075    ignore_stack: IgnoreStack,
5076    ignore_queue: Sender<UpdateIgnoreStatusJob>,
5077    scan_queue: Sender<ScanJob>,
5078}
5079
5080pub trait WorktreeModelHandle {
5081    #[cfg(any(test, feature = "test-support"))]
5082    fn flush_fs_events<'a>(
5083        &self,
5084        cx: &'a mut gpui::TestAppContext,
5085    ) -> futures::future::LocalBoxFuture<'a, ()>;
5086
5087    #[cfg(any(test, feature = "test-support"))]
5088    fn flush_fs_events_in_root_git_repository<'a>(
5089        &self,
5090        cx: &'a mut gpui::TestAppContext,
5091    ) -> futures::future::LocalBoxFuture<'a, ()>;
5092}
5093
5094impl WorktreeModelHandle for Entity<Worktree> {
5095    // When the worktree's FS event stream sometimes delivers "redundant" events for FS changes that
5096    // occurred before the worktree was constructed. These events can cause the worktree to perform
5097    // extra directory scans, and emit extra scan-state notifications.
5098    //
5099    // This function mutates the worktree's directory and waits for those mutations to be picked up,
5100    // to ensure that all redundant FS events have already been processed.
5101    #[cfg(any(test, feature = "test-support"))]
5102    fn flush_fs_events<'a>(
5103        &self,
5104        cx: &'a mut gpui::TestAppContext,
5105    ) -> futures::future::LocalBoxFuture<'a, ()> {
5106        let file_name = "fs-event-sentinel";
5107
5108        let tree = self.clone();
5109        let (fs, root_path) = self.read_with(cx, |tree, _| {
5110            let tree = tree.as_local().unwrap();
5111            (tree.fs.clone(), tree.abs_path.clone())
5112        });
5113
5114        async move {
5115            fs.create_file(&root_path.join(file_name), Default::default())
5116                .await
5117                .unwrap();
5118
5119            let mut events = cx.events(&tree);
5120            while events.next().await.is_some() {
5121                if tree.read_with(cx, |tree, _| {
5122                    tree.entry_for_path(RelPath::unix(file_name).unwrap())
5123                        .is_some()
5124                }) {
5125                    break;
5126                }
5127            }
5128
5129            fs.remove_file(&root_path.join(file_name), Default::default())
5130                .await
5131                .unwrap();
5132            while events.next().await.is_some() {
5133                if tree.read_with(cx, |tree, _| {
5134                    tree.entry_for_path(RelPath::unix(file_name).unwrap())
5135                        .is_none()
5136                }) {
5137                    break;
5138                }
5139            }
5140
5141            cx.update(|cx| tree.read(cx).as_local().unwrap().scan_complete())
5142                .await;
5143        }
5144        .boxed_local()
5145    }
5146
5147    // This function is similar to flush_fs_events, except that it waits for events to be flushed in
5148    // the .git folder of the root repository.
5149    // The reason for its existence is that a repository's .git folder might live *outside* of the
5150    // worktree and thus its FS events might go through a different path.
5151    // In order to flush those, we need to create artificial events in the .git folder and wait
5152    // for the repository to be reloaded.
5153    #[cfg(any(test, feature = "test-support"))]
5154    fn flush_fs_events_in_root_git_repository<'a>(
5155        &self,
5156        cx: &'a mut gpui::TestAppContext,
5157    ) -> futures::future::LocalBoxFuture<'a, ()> {
5158        let file_name = "fs-event-sentinel";
5159
5160        let tree = self.clone();
5161        let (fs, root_path, mut git_dir_scan_id) = self.read_with(cx, |tree, _| {
5162            let tree = tree.as_local().unwrap();
5163            let local_repo_entry = tree
5164                .git_repositories
5165                .values()
5166                .min_by_key(|local_repo_entry| local_repo_entry.work_directory.clone())
5167                .unwrap();
5168            (
5169                tree.fs.clone(),
5170                local_repo_entry.common_dir_abs_path.clone(),
5171                local_repo_entry.git_dir_scan_id,
5172            )
5173        });
5174
5175        let scan_id_increased = |tree: &mut Worktree, git_dir_scan_id: &mut usize| {
5176            let tree = tree.as_local().unwrap();
5177            // let repository = tree.repositories.first().unwrap();
5178            let local_repo_entry = tree
5179                .git_repositories
5180                .values()
5181                .min_by_key(|local_repo_entry| local_repo_entry.work_directory.clone())
5182                .unwrap();
5183
5184            if local_repo_entry.git_dir_scan_id > *git_dir_scan_id {
5185                *git_dir_scan_id = local_repo_entry.git_dir_scan_id;
5186                true
5187            } else {
5188                false
5189            }
5190        };
5191
5192        async move {
5193            fs.create_file(&root_path.join(file_name), Default::default())
5194                .await
5195                .unwrap();
5196
5197            let mut events = cx.events(&tree);
5198            while events.next().await.is_some() {
5199                if tree.update(cx, |tree, _| scan_id_increased(tree, &mut git_dir_scan_id)) {
5200                    break;
5201                }
5202            }
5203
5204            fs.remove_file(&root_path.join(file_name), Default::default())
5205                .await
5206                .unwrap();
5207
5208            while events.next().await.is_some() {
5209                if tree.update(cx, |tree, _| scan_id_increased(tree, &mut git_dir_scan_id)) {
5210                    break;
5211                }
5212            }
5213
5214            cx.update(|cx| tree.read(cx).as_local().unwrap().scan_complete())
5215                .await;
5216        }
5217        .boxed_local()
5218    }
5219}
5220
5221#[derive(Clone, Debug)]
5222struct TraversalProgress<'a> {
5223    max_path: &'a RelPath,
5224    count: usize,
5225    non_ignored_count: usize,
5226    file_count: usize,
5227    non_ignored_file_count: usize,
5228}
5229
5230impl TraversalProgress<'_> {
5231    fn count(&self, include_files: bool, include_dirs: bool, include_ignored: bool) -> usize {
5232        match (include_files, include_dirs, include_ignored) {
5233            (true, true, true) => self.count,
5234            (true, true, false) => self.non_ignored_count,
5235            (true, false, true) => self.file_count,
5236            (true, false, false) => self.non_ignored_file_count,
5237            (false, true, true) => self.count - self.file_count,
5238            (false, true, false) => self.non_ignored_count - self.non_ignored_file_count,
5239            (false, false, _) => 0,
5240        }
5241    }
5242}
5243
5244impl<'a> sum_tree::Dimension<'a, EntrySummary> for TraversalProgress<'a> {
5245    fn zero(_cx: ()) -> Self {
5246        Default::default()
5247    }
5248
5249    fn add_summary(&mut self, summary: &'a EntrySummary, _: ()) {
5250        self.max_path = summary.max_path.as_ref();
5251        self.count += summary.count;
5252        self.non_ignored_count += summary.non_ignored_count;
5253        self.file_count += summary.file_count;
5254        self.non_ignored_file_count += summary.non_ignored_file_count;
5255    }
5256}
5257
5258impl Default for TraversalProgress<'_> {
5259    fn default() -> Self {
5260        Self {
5261            max_path: RelPath::empty(),
5262            count: 0,
5263            non_ignored_count: 0,
5264            file_count: 0,
5265            non_ignored_file_count: 0,
5266        }
5267    }
5268}
5269
5270#[derive(Debug)]
5271pub struct Traversal<'a> {
5272    snapshot: &'a Snapshot,
5273    cursor: sum_tree::Cursor<'a, 'static, Entry, TraversalProgress<'a>>,
5274    include_ignored: bool,
5275    include_files: bool,
5276    include_dirs: bool,
5277}
5278
5279impl<'a> Traversal<'a> {
5280    fn new(
5281        snapshot: &'a Snapshot,
5282        include_files: bool,
5283        include_dirs: bool,
5284        include_ignored: bool,
5285        start_path: &RelPath,
5286    ) -> Self {
5287        let mut cursor = snapshot.entries_by_path.cursor(());
5288        cursor.seek(&TraversalTarget::path(start_path), Bias::Left);
5289        let mut traversal = Self {
5290            snapshot,
5291            cursor,
5292            include_files,
5293            include_dirs,
5294            include_ignored,
5295        };
5296        if traversal.end_offset() == traversal.start_offset() {
5297            traversal.next();
5298        }
5299        traversal
5300    }
5301
5302    pub fn advance(&mut self) -> bool {
5303        self.advance_by(1)
5304    }
5305
5306    pub fn advance_by(&mut self, count: usize) -> bool {
5307        self.cursor.seek_forward(
5308            &TraversalTarget::Count {
5309                count: self.end_offset() + count,
5310                include_dirs: self.include_dirs,
5311                include_files: self.include_files,
5312                include_ignored: self.include_ignored,
5313            },
5314            Bias::Left,
5315        )
5316    }
5317
5318    pub fn advance_to_sibling(&mut self) -> bool {
5319        while let Some(entry) = self.cursor.item() {
5320            self.cursor
5321                .seek_forward(&TraversalTarget::successor(&entry.path), Bias::Left);
5322            if let Some(entry) = self.cursor.item()
5323                && (self.include_files || !entry.is_file())
5324                && (self.include_dirs || !entry.is_dir())
5325                && (self.include_ignored || !entry.is_ignored || entry.is_always_included)
5326            {
5327                return true;
5328            }
5329        }
5330        false
5331    }
5332
5333    pub fn back_to_parent(&mut self) -> bool {
5334        let Some(parent_path) = self.cursor.item().and_then(|entry| entry.path.parent()) else {
5335            return false;
5336        };
5337        self.cursor
5338            .seek(&TraversalTarget::path(parent_path), Bias::Left)
5339    }
5340
5341    pub fn entry(&self) -> Option<&'a Entry> {
5342        self.cursor.item()
5343    }
5344
5345    pub fn snapshot(&self) -> &'a Snapshot {
5346        self.snapshot
5347    }
5348
5349    pub fn start_offset(&self) -> usize {
5350        self.cursor
5351            .start()
5352            .count(self.include_files, self.include_dirs, self.include_ignored)
5353    }
5354
5355    pub fn end_offset(&self) -> usize {
5356        self.cursor
5357            .end()
5358            .count(self.include_files, self.include_dirs, self.include_ignored)
5359    }
5360}
5361
5362impl<'a> Iterator for Traversal<'a> {
5363    type Item = &'a Entry;
5364
5365    fn next(&mut self) -> Option<Self::Item> {
5366        if let Some(item) = self.entry() {
5367            self.advance();
5368            Some(item)
5369        } else {
5370            None
5371        }
5372    }
5373}
5374
5375#[derive(Debug, Clone, Copy)]
5376pub enum PathTarget<'a> {
5377    Path(&'a RelPath),
5378    Successor(&'a RelPath),
5379}
5380
5381impl PathTarget<'_> {
5382    fn cmp_path(&self, other: &RelPath) -> Ordering {
5383        match self {
5384            PathTarget::Path(path) => path.cmp(&other),
5385            PathTarget::Successor(path) => {
5386                if other.starts_with(path) {
5387                    Ordering::Greater
5388                } else {
5389                    Ordering::Equal
5390                }
5391            }
5392        }
5393    }
5394}
5395
5396impl<'a, S: Summary> SeekTarget<'a, PathSummary<S>, PathProgress<'a>> for PathTarget<'_> {
5397    fn cmp(&self, cursor_location: &PathProgress<'a>, _: S::Context<'_>) -> Ordering {
5398        self.cmp_path(cursor_location.max_path)
5399    }
5400}
5401
5402impl<'a, S: Summary> SeekTarget<'a, PathSummary<S>, TraversalProgress<'a>> for PathTarget<'_> {
5403    fn cmp(&self, cursor_location: &TraversalProgress<'a>, _: S::Context<'_>) -> Ordering {
5404        self.cmp_path(cursor_location.max_path)
5405    }
5406}
5407
5408#[derive(Debug)]
5409enum TraversalTarget<'a> {
5410    Path(PathTarget<'a>),
5411    Count {
5412        count: usize,
5413        include_files: bool,
5414        include_ignored: bool,
5415        include_dirs: bool,
5416    },
5417}
5418
5419impl<'a> TraversalTarget<'a> {
5420    fn path(path: &'a RelPath) -> Self {
5421        Self::Path(PathTarget::Path(path))
5422    }
5423
5424    fn successor(path: &'a RelPath) -> Self {
5425        Self::Path(PathTarget::Successor(path))
5426    }
5427
5428    fn cmp_progress(&self, progress: &TraversalProgress) -> Ordering {
5429        match self {
5430            TraversalTarget::Path(path) => path.cmp_path(progress.max_path),
5431            TraversalTarget::Count {
5432                count,
5433                include_files,
5434                include_dirs,
5435                include_ignored,
5436            } => Ord::cmp(
5437                count,
5438                &progress.count(*include_files, *include_dirs, *include_ignored),
5439            ),
5440        }
5441    }
5442}
5443
5444impl<'a> SeekTarget<'a, EntrySummary, TraversalProgress<'a>> for TraversalTarget<'_> {
5445    fn cmp(&self, cursor_location: &TraversalProgress<'a>, _: ()) -> Ordering {
5446        self.cmp_progress(cursor_location)
5447    }
5448}
5449
5450impl<'a> SeekTarget<'a, PathSummary<sum_tree::NoSummary>, TraversalProgress<'a>>
5451    for TraversalTarget<'_>
5452{
5453    fn cmp(&self, cursor_location: &TraversalProgress<'a>, _: ()) -> Ordering {
5454        self.cmp_progress(cursor_location)
5455    }
5456}
5457
5458pub struct ChildEntriesOptions {
5459    pub include_files: bool,
5460    pub include_dirs: bool,
5461    pub include_ignored: bool,
5462}
5463
5464pub struct ChildEntriesIter<'a> {
5465    parent_path: &'a RelPath,
5466    traversal: Traversal<'a>,
5467}
5468
5469impl<'a> Iterator for ChildEntriesIter<'a> {
5470    type Item = &'a Entry;
5471
5472    fn next(&mut self) -> Option<Self::Item> {
5473        if let Some(item) = self.traversal.entry()
5474            && item.path.starts_with(self.parent_path)
5475        {
5476            self.traversal.advance_to_sibling();
5477            return Some(item);
5478        }
5479        None
5480    }
5481}
5482
5483impl<'a> From<&'a Entry> for proto::Entry {
5484    fn from(entry: &'a Entry) -> Self {
5485        Self {
5486            id: entry.id.to_proto(),
5487            is_dir: entry.is_dir(),
5488            path: entry.path.as_ref().to_proto(),
5489            inode: entry.inode,
5490            mtime: entry.mtime.map(|time| time.into()),
5491            is_ignored: entry.is_ignored,
5492            is_hidden: entry.is_hidden,
5493            is_external: entry.is_external,
5494            is_fifo: entry.is_fifo,
5495            size: Some(entry.size),
5496            canonical_path: entry
5497                .canonical_path
5498                .as_ref()
5499                .map(|path| path.to_string_lossy().into_owned()),
5500        }
5501    }
5502}
5503
5504impl TryFrom<(&CharBag, &PathMatcher, proto::Entry)> for Entry {
5505    type Error = anyhow::Error;
5506
5507    fn try_from(
5508        (root_char_bag, always_included, entry): (&CharBag, &PathMatcher, proto::Entry),
5509    ) -> Result<Self> {
5510        let kind = if entry.is_dir {
5511            EntryKind::Dir
5512        } else {
5513            EntryKind::File
5514        };
5515
5516        let path =
5517            RelPath::from_proto(&entry.path).context("invalid relative path in proto message")?;
5518        let char_bag = char_bag_for_path(*root_char_bag, &path);
5519        let is_always_included = always_included.is_match(path.as_std_path());
5520        Ok(Entry {
5521            id: ProjectEntryId::from_proto(entry.id),
5522            kind,
5523            path,
5524            inode: entry.inode,
5525            mtime: entry.mtime.map(|time| time.into()),
5526            size: entry.size.unwrap_or(0),
5527            canonical_path: entry
5528                .canonical_path
5529                .map(|path_string| Arc::from(PathBuf::from(path_string))),
5530            is_ignored: entry.is_ignored,
5531            is_hidden: entry.is_hidden,
5532            is_always_included,
5533            is_external: entry.is_external,
5534            is_private: false,
5535            char_bag,
5536            is_fifo: entry.is_fifo,
5537        })
5538    }
5539}
5540
5541#[derive(Clone, Copy, Debug, Default, Hash, PartialEq, Eq, PartialOrd, Ord)]
5542pub struct ProjectEntryId(usize);
5543
5544impl ProjectEntryId {
5545    pub const MAX: Self = Self(usize::MAX);
5546    pub const MIN: Self = Self(usize::MIN);
5547
5548    pub fn new(counter: &AtomicUsize) -> Self {
5549        Self(counter.fetch_add(1, SeqCst))
5550    }
5551
5552    pub fn from_proto(id: u64) -> Self {
5553        Self(id as usize)
5554    }
5555
5556    pub fn to_proto(self) -> u64 {
5557        self.0 as u64
5558    }
5559
5560    pub fn from_usize(id: usize) -> Self {
5561        ProjectEntryId(id)
5562    }
5563
5564    pub fn to_usize(self) -> usize {
5565        self.0
5566    }
5567}
5568
5569#[cfg(any(test, feature = "test-support"))]
5570impl CreatedEntry {
5571    pub fn into_included(self) -> Option<Entry> {
5572        match self {
5573            CreatedEntry::Included(entry) => Some(entry),
5574            CreatedEntry::Excluded { .. } => None,
5575        }
5576    }
5577}
5578
5579fn parse_gitfile(content: &str) -> Result<&Path> {
5580    let path = content
5581        .strip_prefix("gitdir:")
5582        .with_context(|| format!("parsing gitfile content {content:?}"))?;
5583    Ok(Path::new(path.trim()))
5584}
5585
5586async fn discover_git_paths(dot_git_abs_path: &Arc<Path>, fs: &dyn Fs) -> (Arc<Path>, Arc<Path>) {
5587    let mut repository_dir_abs_path = dot_git_abs_path.clone();
5588    let mut common_dir_abs_path = dot_git_abs_path.clone();
5589
5590    if let Some(path) = fs
5591        .load(dot_git_abs_path)
5592        .await
5593        .ok()
5594        .as_ref()
5595        .and_then(|contents| parse_gitfile(contents).log_err())
5596    {
5597        let path = dot_git_abs_path
5598            .parent()
5599            .unwrap_or(Path::new(""))
5600            .join(path);
5601        if let Some(path) = fs.canonicalize(&path).await.log_err() {
5602            repository_dir_abs_path = Path::new(&path).into();
5603            common_dir_abs_path = repository_dir_abs_path.clone();
5604
5605            if let Some(commondir_contents) = fs.load(&path.join("commondir")).await.ok()
5606                && let Some(commondir_path) = fs
5607                    .canonicalize(&path.join(commondir_contents.trim()))
5608                    .await
5609                    .log_err()
5610            {
5611                common_dir_abs_path = commondir_path.as_path().into();
5612            }
5613        }
5614    };
5615    (repository_dir_abs_path, common_dir_abs_path)
5616}