worktree.rs

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