squigit-rs 0.1.2

Public Rust facade for Squigit application services
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
// Copyright 2026 a7mddra
// SPDX-License-Identifier: Apache-2.0

use fsindex::{Config as FsIndexConfig, EventKind, FileIndexer};
use nucleo_matcher::{
    pattern::{AtomKind, CaseMatching, Normalization, Pattern},
    Config as MatcherConfig, Matcher, Utf32Str,
};
use std::{
    collections::{HashMap, HashSet},
    fs,
    path::{Path, PathBuf},
    sync::{
        atomic::{AtomicBool, Ordering},
        Arc, RwLock,
    },
    thread,
    time::Duration,
};
use thiserror::Error;

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum FileIndexEntryKind {
    Directory,
    File,
}

#[derive(Clone, Debug)]
pub struct FileIndexEntry {
    pub name: String,
    pub path: PathBuf,
    pub kind: FileIndexEntryKind,
    pub extension: Option<String>,
}

#[derive(Clone, Debug)]
pub struct FileSearchMatch {
    pub entry: FileIndexEntry,
    pub score: u32,
}

#[derive(Clone, Debug)]
pub struct FileIndexOptions {
    pub extensions: Vec<String>,
    pub include_hidden: bool,
    pub respect_gitignore: bool,
    pub follow_symlinks: bool,
}

impl Default for FileIndexOptions {
    fn default() -> Self {
        Self {
            extensions: Vec::new(),
            include_hidden: false,
            respect_gitignore: true,
            follow_symlinks: false,
        }
    }
}

#[derive(Debug, Error)]
pub enum FileIndexError {
    #[error("The index root is not an absolute directory: {0}")]
    InvalidRoot(String),
    #[error("The path is not absolute: {0}")]
    RelativePath(String),
    #[error("The path does not exist: {0}")]
    MissingPath(String),
    #[error("The path is not a file or directory: {0}")]
    UnsupportedPath(String),
    #[error("Filesystem operation failed: {0}")]
    Io(#[from] std::io::Error),
}

#[derive(Debug)]
struct FileSearchIndexInner {
    root: PathBuf,
    options: FileIndexOptions,
    entries: RwLock<Vec<FileIndexEntry>>,
    stopped: AtomicBool,
}

#[derive(Clone, Debug)]
pub struct FileSearchIndex {
    inner: Arc<FileSearchIndexInner>,
}

impl FileSearchIndex {
    pub fn new(root: impl AsRef<Path>, options: FileIndexOptions) -> Result<Self, FileIndexError> {
        let root = root.as_ref();
        if !root.is_absolute() || !root.is_dir() {
            return Err(FileIndexError::InvalidRoot(root.display().to_string()));
        }
        let root = root.canonicalize()?;
        let entries = build_entries(&root, &options)?;
        let inner = Arc::new(FileSearchIndexInner {
            root,
            options,
            entries: RwLock::new(entries),
            stopped: AtomicBool::new(false),
        });
        start_watcher(&inner);
        Ok(Self { inner })
    }

    pub fn len(&self) -> usize {
        self.inner
            .entries
            .read()
            .map(|entries| entries.len())
            .unwrap_or_default()
    }

    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    pub fn search(&self, query: &str, limit: usize) -> Vec<FileSearchMatch> {
        if limit == 0 {
            return Vec::new();
        }
        let query = query.trim();
        let candidates = self
            .inner
            .entries
            .read()
            .map(|entries| entries.clone())
            .unwrap_or_default();
        let (direct_candidates, direct_fragment) =
            direct_path_candidates(query, &self.inner.root, &self.inner.options);

        let direct_pattern = Pattern::new(
            &direct_fragment,
            CaseMatching::Ignore,
            Normalization::Smart,
            AtomKind::Fuzzy,
        );
        let mut direct_matcher = Matcher::new(MatcherConfig::DEFAULT);
        let mut direct_utf32_buffer = Vec::new();
        let mut direct_matches = direct_candidates
            .into_iter()
            .filter_map(|entry| {
                let score = if direct_fragment.is_empty() {
                    1
                } else {
                    direct_pattern.score(
                        Utf32Str::new(&entry.name, &mut direct_utf32_buffer),
                        &mut direct_matcher,
                    )?
                };
                Some(FileSearchMatch { entry, score })
            })
            .collect::<Vec<_>>();
        direct_matches.sort_by(|left, right| {
            kind_rank(left.entry.kind)
                .cmp(&kind_rank(right.entry.kind))
                .then_with(|| right.score.cmp(&left.score))
                .then_with(|| left.entry.path.cmp(&right.entry.path))
        });

        let mut seen = HashSet::new();
        let mut matches = Vec::with_capacity(limit);
        for direct_match in direct_matches.into_iter().take(limit) {
            seen.insert(direct_match.entry.path.clone());
            matches.push(direct_match);
        }
        if matches.len() == limit {
            return matches;
        }

        let mut unique = HashMap::<PathBuf, FileIndexEntry>::new();
        for entry in candidates {
            unique.entry(entry.path.clone()).or_insert(entry);
        }

        let normalized_query = query
            .strip_prefix(self.inner.root.to_string_lossy().as_ref())
            .unwrap_or(query)
            .trim_matches(['/', '\\'])
            .to_string();
        let pattern = Pattern::new(
            &normalized_query,
            CaseMatching::Ignore,
            Normalization::Smart,
            AtomKind::Fuzzy,
        );
        let mut matcher = Matcher::new(MatcherConfig::DEFAULT.match_paths());
        let mut utf32_buffer = Vec::new();
        let mut fuzzy_matches = unique
            .into_values()
            .filter(|entry| !seen.contains(&entry.path))
            .filter_map(|entry| {
                let relative = entry
                    .path
                    .strip_prefix(&self.inner.root)
                    .unwrap_or(&entry.path)
                    .to_string_lossy();
                let score = if normalized_query.is_empty() {
                    1
                } else {
                    pattern.score(
                        Utf32Str::new(relative.as_ref(), &mut utf32_buffer),
                        &mut matcher,
                    )?
                };
                Some(FileSearchMatch { entry, score })
            })
            .collect::<Vec<_>>();
        fuzzy_matches.sort_by(|left, right| {
            right
                .score
                .cmp(&left.score)
                .then_with(|| kind_rank(left.entry.kind).cmp(&kind_rank(right.entry.kind)))
                .then_with(|| left.entry.path.cmp(&right.entry.path))
        });
        matches.extend(fuzzy_matches.into_iter().take(limit - matches.len()));
        matches
    }

    pub fn resolve(path: impl AsRef<Path>) -> Result<FileIndexEntry, FileIndexError> {
        let path = path.as_ref();
        if !path.is_absolute() {
            return Err(FileIndexError::RelativePath(path.display().to_string()));
        }
        if !path.exists() {
            return Err(FileIndexError::MissingPath(path.display().to_string()));
        }
        let path = path.canonicalize()?;
        entry_for_path(&path)
            .ok_or_else(|| FileIndexError::UnsupportedPath(path.display().to_string()))
    }
}

impl Drop for FileSearchIndexInner {
    fn drop(&mut self) {
        self.stopped.store(true, Ordering::Release);
    }
}

fn kind_rank(kind: FileIndexEntryKind) -> u8 {
    match kind {
        FileIndexEntryKind::Directory => 0,
        FileIndexEntryKind::File => 1,
    }
}

fn normalized_extensions(options: &FileIndexOptions) -> HashSet<String> {
    options
        .extensions
        .iter()
        .map(|extension| extension.trim_start_matches('.').to_lowercase())
        .filter(|extension| !extension.is_empty())
        .collect()
}

fn is_supported_file(path: &Path, extensions: &HashSet<String>) -> bool {
    extensions.is_empty()
        || path
            .extension()
            .and_then(|extension| extension.to_str())
            .map(|extension| extensions.contains(&extension.to_lowercase()))
            .unwrap_or(false)
}

fn is_hidden(path: &Path) -> bool {
    path.file_name()
        .and_then(|name| name.to_str())
        .map(|name| name.starts_with('.'))
        .unwrap_or(false)
}

fn entry_for_path(path: &Path) -> Option<FileIndexEntry> {
    let metadata = fs::metadata(path).ok()?;
    let kind = if metadata.is_dir() {
        FileIndexEntryKind::Directory
    } else if metadata.is_file() {
        FileIndexEntryKind::File
    } else {
        return None;
    };
    Some(FileIndexEntry {
        name: path
            .file_name()
            .map(|name| name.to_string_lossy().into_owned())
            .filter(|name| !name.is_empty())
            .unwrap_or_else(|| path.display().to_string()),
        path: path.to_path_buf(),
        kind,
        extension: path
            .extension()
            .and_then(|extension| extension.to_str())
            .map(str::to_lowercase),
    })
}

fn build_config(options: &FileIndexOptions, extensions: &[String]) -> FsIndexConfig {
    FsIndexConfig::builder()
        .respect_gitignore(options.respect_gitignore)
        .include_hidden(options.include_hidden)
        .follow_symlinks(options.follow_symlinks)
        .extensions(extensions)
        .read_contents(false)
        .parse_structure(false)
        .build()
}

fn build_entries(
    root: &Path,
    options: &FileIndexOptions,
) -> Result<Vec<FileIndexEntry>, FileIndexError> {
    let extensions = normalized_extensions(options)
        .into_iter()
        .collect::<Vec<_>>();
    let config = build_config(options, &extensions);
    let indexer = FileIndexer::with_config(root, config);
    let mut entries = HashMap::<PathBuf, FileIndexEntry>::new();

    for file in indexer.files_parallel() {
        if let Some(entry) = entry_for_path(&file.path) {
            entries.insert(entry.path.clone(), entry);
        }
        let mut ancestor = file.path.parent();
        while let Some(directory) = ancestor {
            if !directory.starts_with(root) {
                break;
            }
            if let Some(entry) = entry_for_path(directory) {
                entries.entry(entry.path.clone()).or_insert(entry);
            }
            if directory == root {
                break;
            }
            ancestor = directory.parent();
        }
    }

    Ok(entries.into_values().collect())
}

fn direct_path_candidates(
    query: &str,
    root: &Path,
    options: &FileIndexOptions,
) -> (Vec<FileIndexEntry>, String) {
    let candidate = Path::new(query);
    let resolved = if query.is_empty() {
        root.to_path_buf()
    } else if candidate.is_absolute() {
        candidate.to_path_buf()
    } else {
        root.join(candidate)
    };
    let (directory, fragment) = if resolved.is_dir() {
        (resolved, String::new())
    } else {
        (
            resolved
                .parent()
                .filter(|parent| parent.is_dir())
                .unwrap_or(root)
                .to_path_buf(),
            resolved
                .file_name()
                .map(|name| name.to_string_lossy().into_owned())
                .unwrap_or_default(),
        )
    };
    let extensions = normalized_extensions(options);
    let Ok(children) = fs::read_dir(&directory) else {
        return (Vec::new(), fragment);
    };
    let entries = children
        .filter_map(Result::ok)
        .filter_map(|child| {
            let path = child.path();
            if !options.include_hidden && is_hidden(&path) {
                return None;
            }
            let entry = entry_for_path(&path)?;
            if entry.kind == FileIndexEntryKind::File && !is_supported_file(&path, &extensions) {
                return None;
            }
            Some(entry)
        })
        .collect();
    (entries, fragment)
}

fn start_watcher(inner: &Arc<FileSearchIndexInner>) {
    let weak = Arc::downgrade(inner);
    let root = inner.root.clone();
    let options = inner.options.clone();
    thread::spawn(move || {
        let watcher_config = build_config(&options, &[]);
        let watcher = match fsindex::FileWatcher::new(&root, watcher_config) {
            Ok(watcher) => watcher,
            Err(_) => return,
        };
        while let Some(inner) = weak.upgrade() {
            if inner.stopped.load(Ordering::Acquire) {
                break;
            }
            let Some(event) = watcher.next_timeout(Duration::from_millis(500)) else {
                continue;
            };
            let Ok(event) = event else {
                continue;
            };
            if event.kind == EventKind::Accessed {
                continue;
            }
            thread::sleep(Duration::from_millis(180));
            if let Ok(entries) = build_entries(&root, &options) {
                if let Ok(mut current) = inner.entries.write() {
                    *current = entries;
                }
            }
        }
    });
}