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