sift-core 0.2.0

Indexed regex search over codebases (library + grep-like CLI)
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
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
use std::path::{Path, PathBuf};

use serde::{Deserialize, Serialize};

use super::meta::StoreMeta;
use super::snapshot::{self, SnapshotStore};
use super::{CorpusKind, IndexError};

const MANIFEST_FILE: &str = "manifest.json";

/// Manifest written into each snapshot directory listing the indexes it
/// contains.
#[derive(Debug, Serialize, Deserialize)]
struct SnapshotManifest {
    id: String,
    indexes: Vec<String>,
}

/// Index lifecycle orchestrator backed by a [`SnapshotStore`] for atomic
/// persistence and [`StoreMeta`] for corpus configuration.
pub struct IndexStore {
    snapshots: SnapshotStore,
    sift_dir: PathBuf,
}

impl IndexStore {
    /// Open an existing store at `sift_dir`.
    ///
    /// # Errors
    ///
    /// Returns an error if `CURRENT` exists but cannot be read.
    pub fn open(sift_dir: &Path) -> crate::Result<Self> {
        let snapshots = SnapshotStore::open(sift_dir)?;
        Ok(Self {
            snapshots,
            sift_dir: sift_dir.to_path_buf(),
        })
    }

    /// Open an existing store or create a new one at `sift_dir`.
    ///
    /// # Errors
    ///
    /// Returns an error if the store directory cannot be created or metadata
    /// cannot be written.
    pub fn open_or_create(
        sift_dir: &Path,
        root: &Path,
        corpus_kind: CorpusKind,
        follow_links: bool,
        indexes: &[super::IndexKind],
    ) -> crate::Result<Self> {
        std::fs::create_dir_all(sift_dir)?;

        if !StoreMeta::path(sift_dir).exists() {
            let canonical_root = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
            let meta = StoreMeta::new(canonical_root, corpus_kind, follow_links, indexes.to_vec());
            meta.write(sift_dir)?;
        }

        Self::open(sift_dir)
    }

    #[must_use]
    pub fn current_id(&self) -> Option<&str> {
        self.snapshots.current_id()
    }

    #[must_use]
    pub fn snapshot_dir(&self, id: &str) -> PathBuf {
        self.snapshots.current_dir().map_or_else(
            || self.sift_dir.join("snapshots").join(id),
            |d| {
                let parent = d.parent().unwrap_or(&self.sift_dir);
                parent.join(id)
            },
        )
    }

    /// Build a new snapshot using the given index kinds.
    ///
    /// Returns the snapshot id.
    ///
    /// # Errors
    ///
    /// Returns an error if the index build fails, the manifest cannot be
    /// written, or snapshot commit fails.
    pub fn build(
        &mut self,
        kinds: &[super::IndexKind],
        config: &super::IndexConfig<'_>,
    ) -> crate::Result<String> {
        let snapshot = self.snapshots.begin()?;

        for kind in kinds {
            let index_dir = snapshot.dir().join(kind.as_str());
            std::fs::create_dir_all(&index_dir)?;
            kind.build(config, &index_dir)?;
        }

        Self::write_manifest(&snapshot, kinds)?;
        let id = snapshot.id().to_string();
        self.snapshots.commit(snapshot)?;
        Ok(id)
    }

    /// Update the current snapshot, rebuilding only indexes whose corpus
    /// changed.
    ///
    /// Returns the snapshot id if a new snapshot was published, or `None` if
    /// no index changed.
    ///
    /// # Errors
    ///
    /// Returns an error if the current snapshot cannot be opened, the update
    /// check fails, or publishing the new snapshot fails.
    pub fn update(
        &mut self,
        kinds: &[super::IndexKind],
        config: &super::IndexConfig<'_>,
    ) -> crate::Result<Option<String>> {
        let Some(current_dir) = self.snapshots.current_dir() else {
            let id = self.build(kinds, config)?;
            return Ok(Some(id));
        };

        let snapshot = self.snapshots.begin()?;

        let changed: Vec<bool> = kinds
            .iter()
            .map(|kind| kind.update(&current_dir, config, &snapshot.dir().join(kind.as_str())))
            .collect::<crate::Result<_>>()?;

        if !changed.iter().any(|&c| c) {
            return Ok(None);
        }

        for (kind, did_change) in kinds.iter().zip(&changed) {
            if !did_change {
                let src = current_dir.join(kind.as_str());
                if src.exists() {
                    snapshot::copy_dir_contents(&src, &snapshot.dir().join(kind.as_str()))?;
                }
            }
        }

        Self::write_manifest(&snapshot, kinds)?;
        let id = snapshot.id().to_string();
        self.snapshots.commit(snapshot)?;
        Ok(Some(id))
    }

    /// Open all indexes in the current snapshot.
    ///
    /// Returns an empty vector if no snapshot exists.
    ///
    /// # Errors
    ///
    /// Returns an error if the manifest is malformed or an index kind is
    /// unknown.
    pub fn open_current(&self) -> crate::Result<Vec<super::Index>> {
        let Some(snapshot_dir) = self.snapshots.current_dir() else {
            return Ok(Vec::new());
        };

        let manifest_path = snapshot_dir.join(MANIFEST_FILE);
        let manifest_raw = std::fs::read_to_string(&manifest_path)?;
        let manifest: SnapshotManifest = serde_json::from_str(&manifest_raw).map_err(|e| {
            crate::Error::Index(IndexError::InvalidManifest {
                path: manifest_path.clone(),
                source: e,
            })
        })?;

        let meta = StoreMeta::read(&self.sift_dir)?;

        let mut indexes = Vec::new();
        for name in &manifest.indexes {
            let kind: super::IndexKind = name
                .parse()
                .map_err(|_| crate::Error::Index(IndexError::UnknownIndexKind(name.clone())))?;
            let index_dir = snapshot_dir.join(name);
            indexes.push(kind.open_from_dir(&index_dir, &meta.root, meta.corpus_kind)?);
        }

        Ok(indexes)
    }

    fn write_manifest(
        snapshot: &super::snapshot::Snapshot,
        kinds: &[super::IndexKind],
    ) -> crate::Result<()> {
        let manifest = SnapshotManifest {
            id: snapshot.id().to_string(),
            indexes: kinds.iter().map(|k| k.as_str().to_string()).collect(),
        };
        let json = serde_json::to_vec_pretty(&manifest).map_err(|e| {
            crate::Error::Index(IndexError::InvalidManifest {
                path: snapshot.dir().join(MANIFEST_FILE),
                source: e,
            })
        })?;
        std::fs::write(snapshot.dir().join(MANIFEST_FILE), json)?;
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::index::{CorpusKind, CorpusSpec, IndexConfig, IndexKind};
    use crate::search::filter::VisibilityConfig;
    use std::fs;
    use tempfile::TempDir;

    #[test]
    fn build_creates_store_layout() {
        let tmp = TempDir::new().expect("create temp dir");
        let corpus = tmp.path().join("corpus");
        fs::create_dir_all(&corpus).expect("create corpus");
        fs::write(corpus.join("f.txt"), "hello world\n").expect("write file");

        let sift_dir = tmp.path().join(".sift");
        let mut store = IndexStore::open_or_create(
            &sift_dir,
            &corpus,
            CorpusKind::Directory,
            false,
            &[IndexKind::Trigram],
        )
        .expect("open store");

        store
            .build(
                &[IndexKind::Trigram],
                &IndexConfig {
                    corpus: CorpusSpec {
                        root: &corpus,
                        kind: CorpusKind::Directory,
                        follow_links: false,
                        include_paths: &[],
                        exclude_paths: &[],
                    },
                    visibility: VisibilityConfig::default(),
                },
            )
            .expect("build");

        assert!(StoreMeta::path(&sift_dir).exists());

        let id = store.current_id().expect("has current id");
        let snapshot_dir = store.snapshots.current_dir().expect("has snapshot dir");
        assert!(snapshot_dir.exists());
        assert!(snapshot_dir.join(MANIFEST_FILE).exists());
        assert!(snapshot_dir.join("trigram").exists());
        assert!(snapshot_dir.join("trigram").join("files.bin").exists());
        assert!(snapshot_dir.join("trigram").join("lexicon.bin").exists());
        assert!(snapshot_dir.join("trigram").join("postings.bin").exists());
        assert!(snapshot_dir.join("trigram").join("trigrams.bin").exists());

        assert!(!id.is_empty());
    }

    #[test]
    fn open_current_returns_indexes() {
        let tmp = TempDir::new().expect("create temp dir");
        let corpus = tmp.path().join("corpus");
        fs::create_dir_all(&corpus).expect("create corpus");
        fs::write(corpus.join("f.txt"), "hello world\n").expect("write file");

        let sift_dir = tmp.path().join(".sift");
        let mut store = IndexStore::open_or_create(
            &sift_dir,
            &corpus,
            CorpusKind::Directory,
            false,
            &[IndexKind::Trigram],
        )
        .expect("open store");

        store
            .build(
                &[IndexKind::Trigram],
                &IndexConfig {
                    corpus: CorpusSpec {
                        root: &corpus,
                        kind: CorpusKind::Directory,
                        follow_links: false,
                        include_paths: &[],
                        exclude_paths: &[],
                    },
                    visibility: VisibilityConfig::default(),
                },
            )
            .expect("build");

        drop(store);
        let store = IndexStore::open(&sift_dir).expect("reopen store");
        let indexes = store.open_current().expect("open current");
        assert_eq!(indexes.len(), 1);
        let canon_corpus = corpus.canonicalize().unwrap();
        assert_eq!(indexes[0].root(), &canon_corpus);
    }

    #[test]
    fn open_returns_empty_when_no_current() {
        let tmp = TempDir::new().expect("create temp dir");
        let sift_dir = tmp.path().join(".sift");
        std::fs::create_dir_all(&sift_dir).expect("create sift dir");

        let store = IndexStore::open(&sift_dir).expect("open store");
        assert!(store.current_id().is_none());
        let indexes = store.open_current().expect("open current");
        assert!(indexes.is_empty());
    }

    #[test]
    fn open_without_sift_dir_returns_empty() {
        let tmp = TempDir::new().expect("create temp dir");
        let store = IndexStore::open(&tmp.path().join(".sift")).expect("open store");
        assert!(store.current_id().is_none());
    }

    #[test]
    fn update_skips_rebuild_when_unchanged() {
        let tmp = TempDir::new().expect("create temp dir");
        let corpus = tmp.path().join("corpus");
        fs::create_dir_all(&corpus).expect("create corpus");
        fs::write(corpus.join("f.txt"), "hello world\n").expect("write file");

        let sift_dir = tmp.path().join(".sift");
        let config = IndexConfig {
            corpus: CorpusSpec {
                root: &corpus,
                kind: CorpusKind::Directory,
                follow_links: false,
                include_paths: &[],
                exclude_paths: &[],
            },
            visibility: VisibilityConfig::default(),
        };

        let mut store = IndexStore::open_or_create(
            &sift_dir,
            &corpus,
            CorpusKind::Directory,
            false,
            &[IndexKind::Trigram],
        )
        .expect("open store");
        store.build(&[IndexKind::Trigram], &config).expect("build");

        let id_after_build = store.current_id().expect("has id").to_string();

        let changed = store
            .update(&[IndexKind::Trigram], &config)
            .expect("update");
        assert_eq!(changed, None, "expected no rebuild when corpus unchanged");
        assert_eq!(store.current_id().unwrap(), id_after_build);
    }

    #[test]
    fn update_rebuilds_when_file_added() {
        let tmp = TempDir::new().expect("create temp dir");
        let corpus = tmp.path().join("corpus");
        fs::create_dir_all(&corpus).expect("create corpus");
        fs::write(corpus.join("f.txt"), "hello world\n").expect("write file");

        let sift_dir = tmp.path().join(".sift");
        let config = IndexConfig {
            corpus: CorpusSpec {
                root: &corpus,
                kind: CorpusKind::Directory,
                follow_links: false,
                include_paths: &[],
                exclude_paths: &[],
            },
            visibility: VisibilityConfig::default(),
        };

        let mut store = IndexStore::open_or_create(
            &sift_dir,
            &corpus,
            CorpusKind::Directory,
            false,
            &[IndexKind::Trigram],
        )
        .expect("open store");
        store.build(&[IndexKind::Trigram], &config).expect("build");

        let id_after_build = store.current_id().expect("has id").to_string();

        fs::write(corpus.join("g.txt"), "new file\n").expect("write new file");

        let changed = store
            .update(&[IndexKind::Trigram], &config)
            .expect("update");
        assert!(changed.is_some(), "expected rebuild when file added");
        assert_ne!(store.current_id().unwrap(), id_after_build);
    }

    #[test]
    fn update_builds_when_no_current_snapshot() {
        let tmp = TempDir::new().expect("create temp dir");
        let corpus = tmp.path().join("corpus");
        fs::create_dir_all(&corpus).expect("create corpus");
        fs::write(corpus.join("f.txt"), "hello\n").expect("write file");

        let sift_dir = tmp.path().join(".sift");
        let config = IndexConfig {
            corpus: CorpusSpec {
                root: &corpus,
                kind: CorpusKind::Directory,
                follow_links: false,
                include_paths: &[],
                exclude_paths: &[],
            },
            visibility: VisibilityConfig::default(),
        };

        let mut store = IndexStore::open_or_create(
            &sift_dir,
            &corpus,
            CorpusKind::Directory,
            false,
            &[IndexKind::Trigram],
        )
        .expect("open store");

        let changed = store
            .update(&[IndexKind::Trigram], &config)
            .expect("update");
        assert!(changed.is_some(), "expected build when no snapshot exists");
        assert!(store.current_id().is_some());
    }
}