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