Skip to main content

sift_core/search/candidates/
walk.rs

1use std::collections::HashSet;
2use std::path::{Path, PathBuf};
3use std::sync::{Arc, Mutex};
4
5use ignore::{DirEntry, Error as IgnoreError, WalkBuilder, WalkState};
6
7use crate::Candidate;
8use crate::search::filter::{CandidateFilter, HiddenMode, IgnoreSources};
9use crate::search::request::{LinkTraversal, WalkOptions};
10
11/// Per-scope parallel walk that produces candidates.
12///
13/// Also serves as [`ignore::ParallelVisitorBuilder`] — each worker thread
14/// receives a thread-local [`CandidateCollector`].
15struct CandidateWalk<'a> {
16    filter: &'a CandidateFilter,
17    root: PathBuf,
18    filter_root: PathBuf,
19    walk_error: Arc<Mutex<Option<crate::Error>>>,
20    consolidated: Arc<Mutex<Vec<Candidate>>>,
21}
22
23impl<'a> CandidateWalk<'a> {
24    fn new(root: &Path, filter: &'a CandidateFilter) -> crate::Result<Self> {
25        let root = root.canonicalize()?;
26        let filter_root = filter
27            .root()
28            .canonicalize()
29            .unwrap_or_else(|_| filter.root().to_path_buf());
30        Ok(Self {
31            filter,
32            root,
33            filter_root,
34            walk_error: Arc::new(Mutex::new(None)),
35            consolidated: Arc::new(Mutex::new(Vec::new())),
36        })
37    }
38
39    fn walk_builder(&self) -> WalkBuilder {
40        let visibility = self.filter.visibility();
41        let sources = visibility.ignore.sources;
42        let mut builder = WalkBuilder::new(&self.root);
43        builder
44            .follow_links(self.filter.follow_links())
45            .same_file_system(self.filter.one_file_system())
46            .hidden(matches!(visibility.hidden, HiddenMode::Respect))
47            .parents(sources.contains(IgnoreSources::PARENT))
48            .ignore(sources.contains(IgnoreSources::DOT))
49            .git_ignore(sources.contains(IgnoreSources::VCS))
50            .git_exclude(sources.contains(IgnoreSources::EXCLUDE))
51            .git_global(sources.contains(IgnoreSources::GLOBAL))
52            .require_git(visibility.ignore.require_git);
53        if let Some(d) = self.filter.max_depth() {
54            builder.max_depth(Some(d + 1));
55        }
56        builder
57    }
58
59    fn collect(&mut self) -> crate::Result<Vec<Candidate>> {
60        self.walk_builder().build_parallel().visit(self);
61
62        {
63            let mut guard = self.walk_error.lock().expect("walk error lock");
64            if let Some(err) = guard.take() {
65                return Err(err);
66            }
67        }
68
69        Ok(std::mem::take(
70            &mut *self.consolidated.lock().expect("candidate lock"),
71        ))
72    }
73}
74
75impl<'a> ignore::ParallelVisitorBuilder<'a> for CandidateWalk<'_> {
76    fn build(&mut self) -> Box<dyn ignore::ParallelVisitor + 'a> {
77        Box::new(CandidateCollector {
78            filter_root: self.filter_root.clone(),
79            max_filesize: self.filter.max_filesize(),
80            thread_candidates: Vec::new(),
81            walk_error: Arc::clone(&self.walk_error),
82            consolidated: Arc::clone(&self.consolidated),
83        })
84    }
85}
86
87/// Per-thread collector for the parallel walk.
88struct CandidateCollector {
89    filter_root: PathBuf,
90    max_filesize: Option<u64>,
91    thread_candidates: Vec<Candidate>,
92    walk_error: Arc<Mutex<Option<crate::Error>>>,
93    consolidated: Arc<Mutex<Vec<Candidate>>>,
94}
95
96impl Drop for CandidateCollector {
97    fn drop(&mut self) {
98        if self.thread_candidates.is_empty() {
99            return;
100        }
101        let mut guard = self.consolidated.lock().expect("candidate lock");
102        guard.append(&mut self.thread_candidates);
103    }
104}
105
106impl ignore::ParallelVisitor for CandidateCollector {
107    fn visit(&mut self, entry: Result<DirEntry, IgnoreError>) -> WalkState {
108        let entry = match entry {
109            Ok(e) => e,
110            Err(err) => {
111                let mut guard = self.walk_error.lock().expect("walk error lock");
112                if guard.is_none() {
113                    *guard = Some(crate::Error::Ignore(err));
114                }
115                drop(guard);
116                return WalkState::Quit;
117            }
118        };
119        if !entry.file_type().is_some_and(|ft| ft.is_file()) {
120            return WalkState::Continue;
121        }
122        if let Some(limit) = self.max_filesize
123            && entry.metadata().is_ok_and(|m| m.len() > limit)
124        {
125            return WalkState::Continue;
126        }
127        let abs_path = entry.path().to_path_buf();
128        let rel_path = abs_path
129            .strip_prefix(&self.filter_root)
130            .unwrap_or(&abs_path)
131            .to_path_buf();
132        self.thread_candidates
133            .push(Candidate::new(rel_path, abs_path));
134        WalkState::Continue
135    }
136}
137
138/// Collect candidate files across all scopes by walking the filesystem.
139impl CandidateFilter {
140    /// # Errors
141    ///
142    /// Returns an error if walking the corpus fails.
143    pub fn collect(&self) -> crate::Result<Vec<Candidate>> {
144        let filter_root = self
145            .root()
146            .canonicalize()
147            .unwrap_or_else(|_| self.root().to_path_buf());
148        let mut out = Vec::new();
149        for scope in self.scopes() {
150            let path = if scope.as_os_str().is_empty() {
151                filter_root.clone()
152            } else {
153                filter_root.join(scope)
154            };
155            if !path.exists() {
156                continue;
157            }
158            let path = path.canonicalize().unwrap_or(path);
159            if path.is_file() {
160                let rel_path = path
161                    .strip_prefix(&filter_root)
162                    .unwrap_or(&path)
163                    .to_path_buf();
164                out.push(Candidate::new(rel_path, path));
165            } else if path.is_dir() {
166                let mut walk = CandidateWalk::new(&path, self)?;
167                out.extend(walk.collect()?);
168            }
169        }
170        out.sort_by(|a, b| a.rel_path().cmp(b.rel_path()));
171        out.dedup();
172        Ok(out)
173    }
174}
175
176impl WalkOptions {
177    /// Discovers files under the given root matching these walk options.
178    ///
179    /// # Errors
180    ///
181    /// Returns an error if the root path cannot be canonicalized or
182    /// the walk encounters an inaccessible directory.
183    pub fn discover_files(&self, root: &Path) -> crate::Result<HashSet<PathBuf>> {
184        let root = root.canonicalize()?;
185        let mut set = HashSet::new();
186        let follow = matches!(self.links, LinkTraversal::Follow);
187        let mut builder = ignore::WalkBuilder::new(&root);
188        builder.follow_links(follow);
189        if let Some(depth) = self.max_depth {
190            builder.max_depth(Some(depth + 1));
191        }
192        builder.same_file_system(self.one_file_system);
193        let walker = builder.build();
194        for entry in walker {
195            let entry = entry.map_err(crate::Error::Ignore)?;
196            if !entry.file_type().is_some_and(|ft| ft.is_file()) {
197                continue;
198            }
199            let path = entry.path();
200            if self
201                .max_filesize
202                .is_some_and(|limit| std::fs::metadata(path).is_ok_and(|m| m.len() > limit))
203            {
204                continue;
205            }
206            let display = path.strip_prefix(&root).unwrap_or(path).to_path_buf();
207            set.insert(display);
208        }
209        Ok(set)
210    }
211}