project_search.rs

   1use std::{
   2    cell::LazyCell,
   3    collections::BTreeSet,
   4    io::{BufRead, BufReader},
   5    ops::Range,
   6    path::{Path, PathBuf},
   7    pin::pin,
   8    sync::Arc,
   9};
  10
  11use anyhow::Context;
  12use collections::HashSet;
  13use fs::Fs;
  14use futures::{SinkExt, StreamExt, select_biased, stream::FuturesOrdered};
  15use gpui::{App, AppContext, AsyncApp, Entity, Task};
  16use language::{Buffer, BufferSnapshot};
  17use parking_lot::Mutex;
  18use postage::oneshot;
  19use rpc::{AnyProtoClient, proto};
  20use smol::{
  21    channel::{Receiver, Sender, bounded, unbounded},
  22    future::FutureExt,
  23};
  24
  25use text::BufferId;
  26use util::{ResultExt, maybe, paths::compare_rel_paths};
  27use worktree::{Entry, ProjectEntryId, Snapshot, Worktree, WorktreeSettings};
  28
  29use crate::{
  30    Project, ProjectItem, ProjectPath, RemotelyCreatedModels,
  31    buffer_store::BufferStore,
  32    search::{SearchQuery, SearchResult},
  33    worktree_store::WorktreeStore,
  34};
  35
  36pub struct Search {
  37    buffer_store: Entity<BufferStore>,
  38    worktree_store: Entity<WorktreeStore>,
  39    limit: usize,
  40    kind: SearchKind,
  41}
  42
  43/// Represents search setup, before it is actually kicked off with Search::into_results
  44enum SearchKind {
  45    /// Search for candidates by inspecting file contents on file system, avoiding loading the buffer unless we know that a given file contains a match.
  46    Local {
  47        fs: Arc<dyn Fs>,
  48        worktrees: Vec<Entity<Worktree>>,
  49    },
  50    /// Query remote host for candidates. As of writing, the host runs a local search in "buffers with matches only" mode.
  51    Remote {
  52        client: AnyProtoClient,
  53        remote_id: u64,
  54        models: Arc<Mutex<RemotelyCreatedModels>>,
  55    },
  56    /// Run search against a known set of candidates. Even when working with a remote host, this won't round-trip to host.
  57    OpenBuffersOnly,
  58}
  59
  60/// Represents results of project search and allows one to either obtain match positions OR
  61/// just the handles to buffers that may match the search. Grabbing the handles is cheaper than obtaining full match positions, because in that case we'll look for
  62/// at most one match in each file.
  63#[must_use]
  64pub struct SearchResultsHandle {
  65    results: Receiver<SearchResult>,
  66    matching_buffers: Receiver<Entity<Buffer>>,
  67    trigger_search: Box<dyn FnOnce(&mut App) -> Task<()> + Send + Sync>,
  68}
  69
  70impl SearchResultsHandle {
  71    pub fn results(self, cx: &mut App) -> Receiver<SearchResult> {
  72        (self.trigger_search)(cx).detach();
  73        self.results
  74    }
  75    pub fn matching_buffers(self, cx: &mut App) -> Receiver<Entity<Buffer>> {
  76        (self.trigger_search)(cx).detach();
  77        self.matching_buffers
  78    }
  79}
  80
  81#[derive(Clone)]
  82enum FindSearchCandidates {
  83    Local {
  84        fs: Arc<dyn Fs>,
  85        /// Start off with all paths in project and filter them based on:
  86        /// - Include filters
  87        /// - Exclude filters
  88        /// - Only open buffers
  89        /// - Scan ignored files
  90        /// Put another way: filter out files that can't match (without looking at file contents)
  91        input_paths_rx: Receiver<InputPath>,
  92        /// After that, if the buffer is not yet loaded, we'll figure out if it contains at least one match
  93        /// based on disk contents of a buffer. This step is not performed for buffers we already have in memory.
  94        confirm_contents_will_match_tx: Sender<MatchingEntry>,
  95        confirm_contents_will_match_rx: Receiver<MatchingEntry>,
  96        /// Of those that contain at least one match (or are already in memory), look for rest of matches (and figure out their ranges).
  97        /// But wait - first, we need to go back to the main thread to open a buffer (& create an entity for it).
  98        get_buffer_for_full_scan_tx: Sender<ProjectPath>,
  99    },
 100    Remote,
 101    OpenBuffersOnly,
 102}
 103
 104impl Search {
 105    pub fn local(
 106        fs: Arc<dyn Fs>,
 107        buffer_store: Entity<BufferStore>,
 108        worktree_store: Entity<WorktreeStore>,
 109        limit: usize,
 110        cx: &mut App,
 111    ) -> Self {
 112        let worktrees = worktree_store.read(cx).visible_worktrees(cx).collect();
 113        Self {
 114            kind: SearchKind::Local { fs, worktrees },
 115            buffer_store,
 116            worktree_store,
 117            limit,
 118        }
 119    }
 120
 121    pub(crate) fn remote(
 122        buffer_store: Entity<BufferStore>,
 123        worktree_store: Entity<WorktreeStore>,
 124        limit: usize,
 125        client_state: (AnyProtoClient, u64, Arc<Mutex<RemotelyCreatedModels>>),
 126    ) -> Self {
 127        Self {
 128            kind: SearchKind::Remote {
 129                client: client_state.0,
 130                remote_id: client_state.1,
 131                models: client_state.2,
 132            },
 133            buffer_store,
 134            worktree_store,
 135            limit,
 136        }
 137    }
 138    pub(crate) fn open_buffers_only(
 139        buffer_store: Entity<BufferStore>,
 140        worktree_store: Entity<WorktreeStore>,
 141        limit: usize,
 142    ) -> Self {
 143        Self {
 144            kind: SearchKind::OpenBuffersOnly,
 145            buffer_store,
 146            worktree_store,
 147            limit,
 148        }
 149    }
 150
 151    pub(crate) const MAX_SEARCH_RESULT_FILES: usize = 5_000;
 152    pub(crate) const MAX_SEARCH_RESULT_RANGES: usize = 10_000;
 153    /// Prepares a project search run. The resulting [`SearchResultsHandle`] has to be used to specify whether you're interested in matching buffers
 154    /// or full search results.
 155    pub fn into_handle(mut self, query: SearchQuery, cx: &mut App) -> SearchResultsHandle {
 156        let mut open_buffers = HashSet::default();
 157        let mut unnamed_buffers = Vec::new();
 158        const MAX_CONCURRENT_BUFFER_OPENS: usize = 64;
 159        let buffers = self.buffer_store.read(cx);
 160        for handle in buffers.buffers() {
 161            let buffer = handle.read(cx);
 162            if !buffers.is_searchable(&buffer.remote_id()) {
 163                continue;
 164            } else if let Some(entry_id) = buffer.entry_id(cx) {
 165                open_buffers.insert(entry_id);
 166            } else {
 167                self.limit = self.limit.saturating_sub(1);
 168                unnamed_buffers.push(handle)
 169            };
 170        }
 171        let executor = cx.background_executor().clone();
 172        let (tx, rx) = unbounded();
 173        let (grab_buffer_snapshot_tx, grab_buffer_snapshot_rx) = unbounded();
 174        let matching_buffers = grab_buffer_snapshot_rx.clone();
 175        let trigger_search = Box::new(move |cx: &mut App| {
 176            cx.spawn(async move |cx| {
 177                for buffer in unnamed_buffers {
 178                    _ = grab_buffer_snapshot_tx.send(buffer).await;
 179                }
 180
 181                let (find_all_matches_tx, find_all_matches_rx) =
 182                    bounded(MAX_CONCURRENT_BUFFER_OPENS);
 183                let query = Arc::new(query);
 184                let (candidate_searcher, tasks) = match self.kind {
 185                    SearchKind::OpenBuffersOnly => {
 186                        let Ok(open_buffers) = cx.update(|cx| self.all_loaded_buffers(&query, cx))
 187                        else {
 188                            return;
 189                        };
 190                        let fill_requests = cx
 191                            .background_spawn(async move {
 192                                for buffer in open_buffers {
 193                                    if let Err(_) = grab_buffer_snapshot_tx.send(buffer).await {
 194                                        return;
 195                                    }
 196                                }
 197                            })
 198                            .boxed_local();
 199                        (FindSearchCandidates::OpenBuffersOnly, vec![fill_requests])
 200                    }
 201                    SearchKind::Local {
 202                        fs,
 203                        ref mut worktrees,
 204                    } => {
 205                        let (get_buffer_for_full_scan_tx, get_buffer_for_full_scan_rx) =
 206                            unbounded();
 207                        let (confirm_contents_will_match_tx, confirm_contents_will_match_rx) =
 208                            bounded(64);
 209                        let (sorted_search_results_tx, sorted_search_results_rx) = unbounded();
 210
 211                        let (input_paths_tx, input_paths_rx) = unbounded();
 212                        let tasks = vec![
 213                            cx.spawn(Self::provide_search_paths(
 214                                std::mem::take(worktrees),
 215                                query.clone(),
 216                                input_paths_tx,
 217                                sorted_search_results_tx,
 218                            ))
 219                            .boxed_local(),
 220                            Self::open_buffers(
 221                                &self.buffer_store,
 222                                get_buffer_for_full_scan_rx,
 223                                grab_buffer_snapshot_tx,
 224                                cx.clone(),
 225                            )
 226                            .boxed_local(),
 227                            cx.background_spawn(Self::maintain_sorted_search_results(
 228                                sorted_search_results_rx,
 229                                get_buffer_for_full_scan_tx.clone(),
 230                                self.limit,
 231                            ))
 232                            .boxed_local(),
 233                        ];
 234                        (
 235                            FindSearchCandidates::Local {
 236                                fs,
 237                                get_buffer_for_full_scan_tx,
 238                                confirm_contents_will_match_tx,
 239                                confirm_contents_will_match_rx,
 240                                input_paths_rx,
 241                            },
 242                            tasks,
 243                        )
 244                    }
 245                    SearchKind::Remote {
 246                        client,
 247                        remote_id,
 248                        models,
 249                    } => {
 250                        let request = client.request(proto::FindSearchCandidates {
 251                            project_id: remote_id,
 252                            query: Some(query.to_proto()),
 253                            limit: self.limit as _,
 254                        });
 255                        let Ok(guard) = cx.update(|cx| {
 256                            Project::retain_remotely_created_models_impl(
 257                                &models,
 258                                &self.buffer_store,
 259                                &self.worktree_store,
 260                                cx,
 261                            )
 262                        }) else {
 263                            return;
 264                        };
 265                        let buffer_store = self.buffer_store.downgrade();
 266                        let issue_remote_buffers_request = cx
 267                            .spawn(async move |cx| {
 268                                let _ = maybe!(async move {
 269                                    let response = request.await?;
 270                                    log::error!(
 271                                        "Received {} match candidates for a project search",
 272                                        response.buffer_ids.len()
 273                                    );
 274                                    for buffer_id in response.buffer_ids {
 275                                        let buffer_id = BufferId::new(buffer_id)?;
 276                                        let buffer = buffer_store
 277                                            .update(cx, |buffer_store, cx| {
 278                                                buffer_store.wait_for_remote_buffer(buffer_id, cx)
 279                                            })?
 280                                            .await?;
 281                                        let _ = grab_buffer_snapshot_tx.send(buffer).await;
 282                                    }
 283
 284                                    drop(guard);
 285                                    anyhow::Ok(())
 286                                })
 287                                .await
 288                                .log_err();
 289                            })
 290                            .boxed_local();
 291                        (
 292                            FindSearchCandidates::Remote,
 293                            vec![issue_remote_buffers_request],
 294                        )
 295                    }
 296                };
 297
 298                let should_find_all_matches = !tx.is_closed();
 299
 300                let worker_pool = executor.scoped(|scope| {
 301                    let num_cpus = executor.num_cpus();
 302
 303                    assert!(num_cpus > 0);
 304                    for _ in 0..executor.num_cpus() - 1 {
 305                        let worker = Worker {
 306                            query: &query,
 307                            open_buffers: &open_buffers,
 308                            candidates: candidate_searcher.clone(),
 309                            find_all_matches_rx: find_all_matches_rx.clone(),
 310                        };
 311                        scope.spawn(worker.run());
 312                    }
 313
 314                    drop(find_all_matches_rx);
 315                    drop(candidate_searcher);
 316                });
 317
 318                let (sorted_matches_tx, sorted_matches_rx) = unbounded();
 319                // The caller of `into_handle` decides whether they're interested in all matches (files that matched + all matching ranges) or
 320                // just the files. *They are using the same stream as the guts of the project search do*.
 321                // This means that we cannot grab values off of that stream unless it's strictly needed for making a progress in project search.
 322                //
 323                // Grabbing buffer snapshots is only necessary when we're looking for all matches. If the caller decided that they're not interested
 324                // in all matches, running that task unconditionally would hinder caller's ability to observe all matching file paths.
 325                let buffer_snapshots = if should_find_all_matches {
 326                    Some(
 327                        Self::grab_buffer_snapshots(
 328                            grab_buffer_snapshot_rx,
 329                            find_all_matches_tx,
 330                            sorted_matches_tx,
 331                            cx.clone(),
 332                        )
 333                        .boxed_local(),
 334                    )
 335                } else {
 336                    drop(find_all_matches_tx);
 337
 338                    None
 339                };
 340                let ensure_matches_are_reported_in_order = if should_find_all_matches {
 341                    Some(
 342                        Self::ensure_matched_ranges_are_reported_in_order(sorted_matches_rx, tx)
 343                            .boxed_local(),
 344                    )
 345                } else {
 346                    drop(tx);
 347                    None
 348                };
 349
 350                futures::future::join_all(
 351                    [worker_pool.boxed_local()]
 352                        .into_iter()
 353                        .chain(buffer_snapshots)
 354                        .chain(ensure_matches_are_reported_in_order)
 355                        .chain(tasks),
 356                )
 357                .await;
 358            })
 359        });
 360
 361        SearchResultsHandle {
 362            results: rx,
 363            matching_buffers,
 364            trigger_search,
 365        }
 366    }
 367
 368    fn provide_search_paths(
 369        worktrees: Vec<Entity<Worktree>>,
 370        query: Arc<SearchQuery>,
 371        tx: Sender<InputPath>,
 372        results: Sender<oneshot::Receiver<ProjectPath>>,
 373    ) -> impl AsyncFnOnce(&mut AsyncApp) {
 374        async move |cx| {
 375            _ = maybe!(async move {
 376                let gitignored_tracker = PathInclusionMatcher::new(query.clone());
 377                for worktree in worktrees {
 378                    let (mut snapshot, worktree_settings) = worktree
 379                        .read_with(cx, |this, _| {
 380                            Some((this.snapshot(), this.as_local()?.settings()))
 381                        })?
 382                        .context("The worktree is not local")?;
 383                    if query.include_ignored() {
 384                        // Pre-fetch all of the ignored directories as they're going to be searched.
 385                        let mut entries_to_refresh = vec![];
 386
 387                        for entry in snapshot.entries(query.include_ignored(), 0) {
 388                            if gitignored_tracker.should_scan_gitignored_dir(
 389                                entry,
 390                                &snapshot,
 391                                &worktree_settings,
 392                            ) {
 393                                entries_to_refresh.push(entry.path.clone());
 394                            }
 395                        }
 396                        let barrier = worktree.update(cx, |this, _| {
 397                            let local = this.as_local_mut()?;
 398                            let barrier = entries_to_refresh
 399                                .into_iter()
 400                                .map(|path| local.add_path_prefix_to_scan(path).into_future())
 401                                .collect::<Vec<_>>();
 402                            Some(barrier)
 403                        })?;
 404                        if let Some(barriers) = barrier {
 405                            futures::future::join_all(barriers).await;
 406                        }
 407                        snapshot = worktree.read_with(cx, |this, _| this.snapshot())?;
 408                    }
 409                    cx.background_executor()
 410                        .scoped(|scope| {
 411                            scope.spawn(async {
 412                                for entry in snapshot.files(query.include_ignored(), 0) {
 413                                    let (should_scan_tx, should_scan_rx) = oneshot::channel();
 414
 415                                    let Ok(_) = tx
 416                                        .send(InputPath {
 417                                            entry: entry.clone(),
 418                                            snapshot: snapshot.clone(),
 419                                            should_scan_tx,
 420                                        })
 421                                        .await
 422                                    else {
 423                                        return;
 424                                    };
 425                                    if results.send(should_scan_rx).await.is_err() {
 426                                        return;
 427                                    };
 428                                }
 429                            })
 430                        })
 431                        .await;
 432                }
 433                anyhow::Ok(())
 434            })
 435            .await;
 436        }
 437    }
 438
 439    async fn maintain_sorted_search_results(
 440        rx: Receiver<oneshot::Receiver<ProjectPath>>,
 441        paths_for_full_scan: Sender<ProjectPath>,
 442        limit: usize,
 443    ) {
 444        let mut rx = pin!(rx);
 445        let mut matched = 0;
 446        while let Some(mut next_path_result) = rx.next().await {
 447            let Some(successful_path) = next_path_result.next().await else {
 448                // This file did not produce a match, hence skip it.
 449                continue;
 450            };
 451            if paths_for_full_scan.send(successful_path).await.is_err() {
 452                return;
 453            };
 454            matched += 1;
 455            if matched >= limit {
 456                break;
 457            }
 458        }
 459    }
 460
 461    /// Background workers cannot open buffers by themselves, hence main thread will do it on their behalf.
 462    async fn open_buffers(
 463        buffer_store: &Entity<BufferStore>,
 464        rx: Receiver<ProjectPath>,
 465        find_all_matches_tx: Sender<Entity<Buffer>>,
 466        mut cx: AsyncApp,
 467    ) {
 468        let mut rx = pin!(rx.ready_chunks(64));
 469        _ = maybe!(async move {
 470            while let Some(requested_paths) = rx.next().await {
 471                let mut buffers = buffer_store.update(&mut cx, |this, cx| {
 472                    requested_paths
 473                        .into_iter()
 474                        .map(|path| this.open_buffer(path, cx))
 475                        .collect::<FuturesOrdered<_>>()
 476                })?;
 477
 478                while let Some(buffer) = buffers.next().await {
 479                    if let Some(buffer) = buffer.log_err() {
 480                        find_all_matches_tx.send(buffer).await?;
 481                    }
 482                }
 483            }
 484            Result::<_, anyhow::Error>::Ok(())
 485        })
 486        .await;
 487    }
 488
 489    async fn grab_buffer_snapshots(
 490        rx: Receiver<Entity<Buffer>>,
 491        find_all_matches_tx: Sender<(
 492            Entity<Buffer>,
 493            BufferSnapshot,
 494            oneshot::Sender<(Entity<Buffer>, Vec<Range<language::Anchor>>)>,
 495        )>,
 496        results: Sender<oneshot::Receiver<(Entity<Buffer>, Vec<Range<language::Anchor>>)>>,
 497        mut cx: AsyncApp,
 498    ) {
 499        _ = maybe!(async move {
 500            while let Ok(buffer) = rx.recv().await {
 501                let snapshot = buffer.read_with(&mut cx, |this, _| this.snapshot())?;
 502                let (tx, rx) = oneshot::channel();
 503                find_all_matches_tx.send((buffer, snapshot, tx)).await?;
 504                results.send(rx).await?;
 505            }
 506            debug_assert!(rx.is_empty());
 507            Result::<_, anyhow::Error>::Ok(())
 508        })
 509        .await;
 510    }
 511
 512    async fn ensure_matched_ranges_are_reported_in_order(
 513        rx: Receiver<oneshot::Receiver<(Entity<Buffer>, Vec<Range<language::Anchor>>)>>,
 514        tx: Sender<SearchResult>,
 515    ) {
 516        use postage::stream::Stream;
 517        _ = maybe!(async move {
 518            let mut matched_buffers = 0;
 519            let mut matches = 0;
 520            while let Ok(mut next_buffer_matches) = rx.recv().await {
 521                let Some((buffer, ranges)) = next_buffer_matches.recv().await else {
 522                    continue;
 523                };
 524
 525                if matched_buffers > Search::MAX_SEARCH_RESULT_FILES
 526                    || matches > Search::MAX_SEARCH_RESULT_RANGES
 527                {
 528                    _ = tx.send(SearchResult::LimitReached).await;
 529                    break;
 530                }
 531                matched_buffers += 1;
 532                matches += ranges.len();
 533
 534                _ = tx.send(SearchResult::Buffer { buffer, ranges }).await?;
 535            }
 536            anyhow::Ok(())
 537        })
 538        .await;
 539    }
 540
 541    fn all_loaded_buffers(&self, search_query: &SearchQuery, cx: &App) -> Vec<Entity<Buffer>> {
 542        let worktree_store = self.worktree_store.read(cx);
 543        let mut buffers = search_query
 544            .buffers()
 545            .into_iter()
 546            .flatten()
 547            .filter(|buffer| {
 548                let b = buffer.read(cx);
 549                if let Some(file) = b.file() {
 550                    if !search_query.match_path(file.path().as_std_path()) {
 551                        return false;
 552                    }
 553                    if !search_query.include_ignored()
 554                        && let Some(entry) = b
 555                            .entry_id(cx)
 556                            .and_then(|entry_id| worktree_store.entry_for_id(entry_id, cx))
 557                        && entry.is_ignored
 558                    {
 559                        return false;
 560                    }
 561                }
 562                true
 563            })
 564            .cloned()
 565            .collect::<Vec<_>>();
 566        buffers.sort_by(|a, b| {
 567            let a = a.read(cx);
 568            let b = b.read(cx);
 569            match (a.file(), b.file()) {
 570                (None, None) => a.remote_id().cmp(&b.remote_id()),
 571                (None, Some(_)) => std::cmp::Ordering::Less,
 572                (Some(_), None) => std::cmp::Ordering::Greater,
 573                (Some(a), Some(b)) => compare_rel_paths((a.path(), true), (b.path(), true)),
 574            }
 575        });
 576
 577        buffers
 578    }
 579}
 580
 581struct Worker<'search> {
 582    query: &'search SearchQuery,
 583    open_buffers: &'search HashSet<ProjectEntryId>,
 584    candidates: FindSearchCandidates,
 585    /// Ok, we're back in background: run full scan & find all matches in a given buffer snapshot.
 586    /// Then, when you're done, share them via the channel you were given.
 587    find_all_matches_rx: Receiver<(
 588        Entity<Buffer>,
 589        BufferSnapshot,
 590        oneshot::Sender<(Entity<Buffer>, Vec<Range<language::Anchor>>)>,
 591    )>,
 592}
 593
 594impl Worker<'_> {
 595    async fn run(self) {
 596        let (
 597            input_paths_rx,
 598            confirm_contents_will_match_rx,
 599            mut confirm_contents_will_match_tx,
 600            mut get_buffer_for_full_scan_tx,
 601            fs,
 602        ) = match self.candidates {
 603            FindSearchCandidates::Local {
 604                fs,
 605                input_paths_rx,
 606                confirm_contents_will_match_rx,
 607                confirm_contents_will_match_tx,
 608                get_buffer_for_full_scan_tx,
 609            } => (
 610                input_paths_rx,
 611                confirm_contents_will_match_rx,
 612                confirm_contents_will_match_tx,
 613                get_buffer_for_full_scan_tx,
 614                Some(fs),
 615            ),
 616            FindSearchCandidates::Remote | FindSearchCandidates::OpenBuffersOnly => (
 617                unbounded().1,
 618                unbounded().1,
 619                unbounded().0,
 620                unbounded().0,
 621                None,
 622            ),
 623        };
 624        // WorkerA: grabs a request for "find all matches in file/a" <- takes 5 minutes
 625        // right after: WorkerB: grabs a request for "find all matches in file/b" <- takes 5 seconds
 626        let mut find_all_matches = pin!(self.find_all_matches_rx.fuse());
 627        let mut find_first_match = pin!(confirm_contents_will_match_rx.fuse());
 628        let mut scan_path = pin!(input_paths_rx.fuse());
 629
 630        loop {
 631            let handler = RequestHandler {
 632                query: self.query,
 633                open_entries: &self.open_buffers,
 634                fs: fs.as_deref(),
 635                confirm_contents_will_match_tx: &confirm_contents_will_match_tx,
 636                get_buffer_for_full_scan_tx: &get_buffer_for_full_scan_tx,
 637            };
 638            // Whenever we notice that some step of a pipeline is closed, we don't want to close subsequent
 639            // steps straight away. Another worker might be about to produce a value that will
 640            // be pushed there, thus we'll replace current worker's pipe with a dummy one.
 641            // That way, we'll only ever close a next-stage channel when ALL workers do so.
 642            select_biased! {
 643                find_all_matches = find_all_matches.next() => {
 644                    let Some(matches) = find_all_matches else {
 645                        continue;
 646                    };
 647                    handler.handle_find_all_matches(matches).await;
 648                },
 649                find_first_match = find_first_match.next() => {
 650                    if let Some(buffer_with_at_least_one_match) = find_first_match {
 651                        handler.handle_find_first_match(buffer_with_at_least_one_match).await;
 652                    } else {
 653                        get_buffer_for_full_scan_tx = bounded(1).0;
 654                    }
 655
 656                },
 657                scan_path = scan_path.next() => {
 658                    if let Some(path_to_scan) = scan_path {
 659                        handler.handle_scan_path(path_to_scan).await;
 660                    } else {
 661                        // If we're the last worker to notice that this is not producing values, close the upstream.
 662                        confirm_contents_will_match_tx = bounded(1).0;
 663                    }
 664
 665                 }
 666                 complete => {
 667                     break
 668                },
 669
 670            }
 671        }
 672    }
 673}
 674
 675struct RequestHandler<'worker> {
 676    query: &'worker SearchQuery,
 677    fs: Option<&'worker dyn Fs>,
 678    open_entries: &'worker HashSet<ProjectEntryId>,
 679    confirm_contents_will_match_tx: &'worker Sender<MatchingEntry>,
 680    get_buffer_for_full_scan_tx: &'worker Sender<ProjectPath>,
 681}
 682
 683impl RequestHandler<'_> {
 684    async fn handle_find_all_matches(
 685        &self,
 686        (buffer, snapshot, mut report_matches): (
 687            Entity<Buffer>,
 688            BufferSnapshot,
 689            oneshot::Sender<(Entity<Buffer>, Vec<Range<language::Anchor>>)>,
 690        ),
 691    ) {
 692        let ranges = self
 693            .query
 694            .search(&snapshot, None)
 695            .await
 696            .iter()
 697            .map(|range| snapshot.anchor_before(range.start)..snapshot.anchor_after(range.end))
 698            .collect::<Vec<_>>();
 699
 700        _ = report_matches.send((buffer, ranges)).await;
 701    }
 702
 703    async fn handle_find_first_match(&self, mut entry: MatchingEntry) {
 704        _=maybe!(async move {
 705            let abs_path = entry.worktree_root.join(entry.path.path.as_std_path());
 706            let Some(file) = self.fs.context("Trying to query filesystem in remote project search")?.open_sync(&abs_path).await.log_err() else {
 707                return anyhow::Ok(());
 708            };
 709
 710            let mut file = BufReader::new(file);
 711            let file_start = file.fill_buf()?;
 712
 713            if let Err(Some(starting_position)) =
 714            std::str::from_utf8(file_start).map_err(|e| e.error_len())
 715            {
 716                // Before attempting to match the file content, throw away files that have invalid UTF-8 sequences early on;
 717                // That way we can still match files in a streaming fashion without having look at "obviously binary" files.
 718                log::debug!(
 719                    "Invalid UTF-8 sequence in file {abs_path:?} at byte position {starting_position}"
 720                );
 721                return Ok(());
 722            }
 723
 724            if self.query.detect(file).unwrap_or(false) {
 725                // Yes, we should scan the whole file.
 726                entry.should_scan_tx.send(entry.path).await?;
 727            }
 728            Ok(())
 729        }).await;
 730    }
 731
 732    async fn handle_scan_path(&self, req: InputPath) {
 733        _ = maybe!(async move {
 734            let InputPath {
 735                entry,
 736
 737                snapshot,
 738                should_scan_tx,
 739            } = req;
 740
 741            if entry.is_fifo || !entry.is_file() {
 742                return Ok(());
 743            }
 744
 745            if self.query.filters_path() {
 746                let matched_path = if self.query.match_full_paths() {
 747                    let mut full_path = snapshot.root_name().as_std_path().to_owned();
 748                    full_path.push(entry.path.as_std_path());
 749                    self.query.match_path(&full_path)
 750                } else {
 751                    self.query.match_path(entry.path.as_std_path())
 752                };
 753                if !matched_path {
 754                    return Ok(());
 755                }
 756            }
 757
 758            if self.open_entries.contains(&entry.id) {
 759                // The buffer is already in memory and that's the version we want to scan;
 760                // hence skip the dilly-dally and look for all matches straight away.
 761                self.get_buffer_for_full_scan_tx
 762                    .send(ProjectPath {
 763                        worktree_id: snapshot.id(),
 764                        path: entry.path.clone(),
 765                    })
 766                    .await?;
 767            } else {
 768                self.confirm_contents_will_match_tx
 769                    .send(MatchingEntry {
 770                        should_scan_tx: should_scan_tx,
 771                        worktree_root: snapshot.abs_path().clone(),
 772                        path: ProjectPath {
 773                            worktree_id: snapshot.id(),
 774                            path: entry.path.clone(),
 775                        },
 776                    })
 777                    .await?;
 778            }
 779
 780            anyhow::Ok(())
 781        })
 782        .await;
 783    }
 784}
 785
 786struct InputPath {
 787    entry: Entry,
 788    snapshot: Snapshot,
 789    should_scan_tx: oneshot::Sender<ProjectPath>,
 790}
 791
 792struct MatchingEntry {
 793    worktree_root: Arc<Path>,
 794    path: ProjectPath,
 795    should_scan_tx: oneshot::Sender<ProjectPath>,
 796}
 797
 798/// This struct encapsulates the logic to decide whether a given gitignored directory should be
 799/// scanned based on include/exclude patterns of a search query (as include/exclude parameters may match paths inside it).
 800/// It is kind-of doing an inverse of glob. Given a glob pattern like `src/**/` and a parent path like `src`, we need to decide whether the parent
 801/// may contain glob hits.
 802struct PathInclusionMatcher {
 803    included: BTreeSet<PathBuf>,
 804    query: Arc<SearchQuery>,
 805}
 806
 807impl PathInclusionMatcher {
 808    fn new(query: Arc<SearchQuery>) -> Self {
 809        let mut included = BTreeSet::new();
 810        // To do an inverse glob match, we split each glob into it's prefix and the glob part.
 811        // For example, `src/**/*.rs` becomes `src/` and `**/*.rs`. The glob part gets dropped.
 812        // Then, when checking whether a given directory should be scanned, we check whether it is a non-empty substring of any glob prefix.
 813        if query.filters_path() {
 814            included.extend(
 815                query
 816                    .files_to_include()
 817                    .sources()
 818                    .iter()
 819                    .flat_map(|glob| Some(wax::Glob::new(glob).ok()?.partition().0)),
 820            );
 821        }
 822        Self { included, query }
 823    }
 824
 825    fn should_scan_gitignored_dir(
 826        &self,
 827        entry: &Entry,
 828        snapshot: &Snapshot,
 829        worktree_settings: &WorktreeSettings,
 830    ) -> bool {
 831        if !entry.is_ignored || !entry.kind.is_unloaded() {
 832            return false;
 833        }
 834        if !self.query.include_ignored() {
 835            return false;
 836        }
 837        if worktree_settings.is_path_excluded(&entry.path) {
 838            return false;
 839        }
 840        if !self.query.filters_path() {
 841            return true;
 842        }
 843
 844        let as_abs_path = LazyCell::new(move || snapshot.absolutize(&entry.path));
 845        let entry_path = entry.path.as_std_path();
 846        // 3. Check Exclusions (Pruning)
 847        // If the current path is a child of an excluded path, we stop.
 848        let is_excluded = self.path_is_definitely_excluded(entry_path, snapshot);
 849
 850        if is_excluded {
 851            return false;
 852        }
 853
 854        // 4. Check Inclusions (Traversal)
 855        if self.included.is_empty() {
 856            return true;
 857        }
 858
 859        // We scan if the current path is a descendant of an include prefix
 860        // OR if the current path is an ancestor of an include prefix (we need to go deeper to find it).
 861        let is_included = self.included.iter().any(|prefix| {
 862            let (prefix_matches_entry, entry_matches_prefix) = if prefix.is_absolute() {
 863                (
 864                    prefix.starts_with(&**as_abs_path),
 865                    as_abs_path.starts_with(prefix),
 866                )
 867            } else {
 868                (
 869                    prefix.starts_with(entry_path),
 870                    entry_path.starts_with(prefix),
 871                )
 872            };
 873
 874            // Logic:
 875            // 1. entry_matches_prefix: We are inside the target zone (e.g. glob: src/, current: src/lib/). Keep scanning.
 876            // 2. prefix_matches_entry: We are above the target zone (e.g. glob: src/foo/, current: src/). Keep scanning to reach foo.
 877            prefix_matches_entry || entry_matches_prefix
 878        });
 879
 880        is_included
 881    }
 882    fn path_is_definitely_excluded(&self, path: &Path, snapshot: &Snapshot) -> bool {
 883        if !self.query.files_to_exclude().sources().is_empty() {
 884            let mut path = if self.query.match_full_paths() {
 885                let mut full_path = snapshot.root_name().as_std_path().to_owned();
 886                full_path.push(path);
 887                full_path
 888            } else {
 889                path.to_owned()
 890            };
 891            loop {
 892                if self.query.files_to_exclude().is_match(&path) {
 893                    return true;
 894                } else if !path.pop() {
 895                    return false;
 896                }
 897            }
 898        } else {
 899            false
 900        }
 901    }
 902}
 903
 904#[cfg(test)]
 905mod tests {
 906    use super::*;
 907    use fs::FakeFs;
 908    use serde_json::json;
 909    use settings::Settings;
 910    use util::{
 911        path,
 912        paths::{PathMatcher, PathStyle},
 913        rel_path::RelPath,
 914    };
 915    use worktree::{Entry, EntryKind, WorktreeSettings};
 916
 917    use crate::{
 918        Project, project_search::PathInclusionMatcher, project_tests::init_test,
 919        search::SearchQuery,
 920    };
 921
 922    #[gpui::test]
 923    async fn test_path_inclusion_matcher(cx: &mut gpui::TestAppContext) {
 924        init_test(cx);
 925
 926        let fs = FakeFs::new(cx.background_executor.clone());
 927        fs.insert_tree(
 928            "/root",
 929            json!({
 930                ".gitignore": "src/data/\n",
 931                "src": {
 932                    "data": {
 933                        "main.csv": "field_1,field_2,field_3",
 934                    },
 935                    "lib": {
 936                        "main.txt": "Are you familiar with fields?",
 937                    },
 938                },
 939            }),
 940        )
 941        .await;
 942
 943        let project = Project::test(fs.clone(), [path!("/root").as_ref()], cx).await;
 944        let worktree = project.update(cx, |project, cx| project.worktrees(cx).next().unwrap());
 945        let (worktree_settings, worktree_snapshot) = worktree.update(cx, |worktree, cx| {
 946            let settings_location = worktree.settings_location(cx);
 947            return (
 948                WorktreeSettings::get(Some(settings_location), cx).clone(),
 949                worktree.snapshot(),
 950            );
 951        });
 952
 953        // Manually create a test entry for the gitignored directory since it won't
 954        // be loaded by the worktree
 955        let entry = Entry {
 956            id: ProjectEntryId::from_proto(1),
 957            kind: EntryKind::UnloadedDir,
 958            path: Arc::from(RelPath::unix(Path::new("src/data")).unwrap()),
 959            inode: 0,
 960            mtime: None,
 961            canonical_path: None,
 962            is_ignored: true,
 963            is_hidden: false,
 964            is_always_included: false,
 965            is_external: false,
 966            is_private: false,
 967            size: 0,
 968            char_bag: Default::default(),
 969            is_fifo: false,
 970        };
 971
 972        // 1. Test searching for `field`, including ignored files without any
 973        // inclusion and exclusion filters.
 974        let include_ignored = true;
 975        let files_to_include = PathMatcher::default();
 976        let files_to_exclude = PathMatcher::default();
 977        let match_full_paths = false;
 978        let search_query = SearchQuery::text(
 979            "field",
 980            false,
 981            false,
 982            include_ignored,
 983            files_to_include,
 984            files_to_exclude,
 985            match_full_paths,
 986            None,
 987        )
 988        .unwrap();
 989
 990        let path_matcher = PathInclusionMatcher::new(Arc::new(search_query));
 991        assert!(path_matcher.should_scan_gitignored_dir(
 992            &entry,
 993            &worktree_snapshot,
 994            &worktree_settings
 995        ));
 996
 997        // 2. Test searching for `field`, including ignored files but updating
 998        // `files_to_include` to only include files under `src/lib`.
 999        let include_ignored = true;
1000        let files_to_include = PathMatcher::new(vec!["src/lib"], PathStyle::Posix).unwrap();
1001        let files_to_exclude = PathMatcher::default();
1002        let match_full_paths = false;
1003        let search_query = SearchQuery::text(
1004            "field",
1005            false,
1006            false,
1007            include_ignored,
1008            files_to_include,
1009            files_to_exclude,
1010            match_full_paths,
1011            None,
1012        )
1013        .unwrap();
1014
1015        let path_matcher = PathInclusionMatcher::new(Arc::new(search_query));
1016        assert!(!path_matcher.should_scan_gitignored_dir(
1017            &entry,
1018            &worktree_snapshot,
1019            &worktree_settings
1020        ));
1021    }
1022}