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