lanekeep-core 0.11.0

Core types and execution engine for lanekeep.
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
437
438
439
440
441
442
443
444
445
446
447
448
449
//! Finding the files to check.
//!
//! Discovery is gitignore-aware, so build output and vendored dependencies are skipped
//! without every project having to exclude them by hand.
//!
//! The returned order is sorted. Nothing downstream depends on it — violations are sorted
//! before reporting — but discovery feeding files to workers in filesystem order would make
//! the *work distribution* vary between runs on identical input, which turns a timing
//! difference into something that looks like nondeterminism when a run breaches a budget.

use std::path::{Path, PathBuf};

use globset::{Glob, GlobSet, GlobSetBuilder};
use thiserror::Error;

use crate::location::FilePath;

/// Why discovery could not run.
#[derive(Debug, Clone, PartialEq, Eq, Error)]
pub enum DiscoveryError {
    /// A glob in `include` or `exclude` is malformed.
    #[error("invalid {field} pattern `{pattern}`: {detail}")]
    InvalidGlob {
        /// Which config field it came from.
        field: &'static str,
        /// The pattern as written.
        pattern: String,
        /// What is wrong with it.
        detail: String,
    },

    /// The project root cannot be walked.
    #[error("cannot read project root `{path}`: {detail}")]
    Unreadable {
        /// The root as given.
        path: String,
        /// What went wrong.
        detail: String,
    },
}

/// Why discovery would not take a file, asked without walking.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Rejection {
    /// It is inside lanekeep's own directory, which no configuration includes.
    Lanekeep,
    /// An `exclude` glob matched it.
    Excluded {
        /// The pattern that matched, as the config wrote it.
        pattern: String,
    },
    /// `include` is non-empty and no pattern in it matched.
    NotIncluded,
}

/// Which files a run considers.
#[derive(Debug)]
pub struct Discovery {
    root: PathBuf,
    include: GlobSet,
    exclude: GlobSet,
    has_include: bool,
    exclude_patterns: Vec<String>,
}

impl Discovery {
    /// Build a discovery over a project root.
    ///
    /// # Errors
    ///
    /// Returns [`DiscoveryError::InvalidGlob`] for a malformed pattern, with the field it
    /// came from — an error naming only the pattern leaves the reader searching for it.
    pub fn new(
        root: impl AsRef<Path>,
        include: &[String],
        exclude: &[String],
    ) -> Result<Self, DiscoveryError> {
        let root = root.as_ref();
        let canonical = root
            .canonicalize()
            .map_err(|e| DiscoveryError::Unreadable {
                path: root.display().to_string(),
                detail: e.to_string(),
            })?;

        Ok(Self {
            root: canonical,
            include: build_set(include, "include")?,
            exclude: build_set(exclude, "exclude")?,
            has_include: !include.is_empty(),
            exclude_patterns: exclude.to_vec(),
        })
    }

    /// The project root, canonicalized.
    #[must_use]
    pub fn root(&self) -> &Path {
        &self.root
    }

    /// Why a path relative to the root would not be checked, without walking.
    ///
    /// `None` means the globs select it; the walk may still leave it out (a `.gitignore`
    /// rule), which only the walk can see.
    ///
    /// Exclusion wins over inclusion: a project listing a broad `include` and a narrow
    /// `exclude` means the exclusion, and the other order would make `exclude` useless.
    ///
    /// `.lanekeep/` at the root wins over both, and is not configurable: it is lanekeep's own
    /// directory — the cache, the precompiled components, the `tsc` driver — and nothing in it
    /// was written by the project. See `in_lanekeep_directory` below for the whole reasoning.
    #[must_use]
    pub fn rejects(&self, relative: &FilePath) -> Option<Rejection> {
        let path = relative.as_str();
        if in_lanekeep_directory(path) {
            return Some(Rejection::Lanekeep);
        }
        // `is_match` short-circuits, which is what keeps `selects` cheap on the walk's hot
        // path; the full scan runs only for a file a rejection will quote, to name the
        // pattern as the config wrote it.
        if self.exclude.is_match(path)
            && let Some(index) = self.exclude.matches(path).first()
        {
            return Some(Rejection::Excluded {
                pattern: self.exclude_patterns[*index].clone(),
            });
        }
        if self.has_include && !self.include.is_match(path) {
            return Some(Rejection::NotIncluded);
        }
        None
    }

    /// Whether a path relative to the root is selected. See `rejects` for why a path is
    /// not.
    #[must_use]
    pub fn selects(&self, relative: &FilePath) -> bool {
        self.rejects(relative).is_none()
    }

    /// Every selected file, sorted.
    ///
    /// Infallible: the root was canonicalized when this was built, and a single unreadable
    /// entry is skipped rather than failing a run over a tree that may contain anything.
    #[must_use]
    pub fn walk(&self) -> Vec<FilePath> {
        let mut out = Vec::new();

        for entry in ignore::WalkBuilder::new(&self.root)
            .hidden(false)
            .git_ignore(true)
            .git_global(true)
            .git_exclude(true)
            .parents(true)
            // Honor .gitignore even outside a repository. The walker otherwise treats
            // ignore files as meaningless without a .git directory, which would make
            // discovery depend on whether the project happens to be checked out — the
            // same tree giving different answers in a tarball than in a clone.
            .require_git(false)
            .build()
        {
            // A single unreadable entry is not a reason to fail the run.
            let Ok(entry) = entry else { continue };
            if !entry.file_type().is_some_and(|t| t.is_file()) {
                continue;
            }
            let Ok(relative) = entry.path().strip_prefix(&self.root) else {
                continue;
            };

            let relative = FilePath::new(relative);
            if self.selects(&relative) {
                out.push(relative);
            }
        }

        out.sort();
        out.dedup();
        out
    }
}

/// Whether a path relative to the root is inside lanekeep's own directory.
///
/// The walk sees hidden entries deliberately — a project's `.github/` is code someone may want
/// checked — and `.lanekeep/` at the root is the one hidden directory that is never a subject.
/// It is lanekeep's own: the cache, the precompiled components, and the `tsc` driver lanekeep
/// writes there and then runs. Nothing in it was written by the project, and a rule reporting
/// on it is reporting on lanekeep. Under `types.provider: 'tsc'` it was worse than noise — the
/// driver is JavaScript, so with `allowJs` it entered the program listing and put lanekeep's
/// own version into the key a second time, by a path that only looks like a project file.
///
/// Unconditional, and not something `exclude` can turn off: there is no configuration under
/// which checking it is what someone meant. Matched on the leading path *component*, so
/// `src/.lanekeep-notes.ts` and a project's own `vendor/.lanekeep/` are untouched.
fn in_lanekeep_directory(relative: &str) -> bool {
    relative
        .split('/')
        .next()
        .is_some_and(|first| first == ".lanekeep")
}

fn build_set(patterns: &[String], field: &'static str) -> Result<GlobSet, DiscoveryError> {
    let mut builder = GlobSetBuilder::new();
    for pattern in patterns {
        let glob = Glob::new(pattern).map_err(|e| DiscoveryError::InvalidGlob {
            field,
            pattern: pattern.clone(),
            detail: e.to_string(),
        })?;
        builder.add(glob);
    }
    builder.build().map_err(|e| DiscoveryError::InvalidGlob {
        field,
        pattern: patterns.join(", "),
        detail: e.to_string(),
    })
}

#[cfg(test)]
mod tests {
    use std::fs;

    use super::*;

    struct Fixture {
        dir: PathBuf,
    }

    impl Fixture {
        fn new(name: &str, files: &[&str]) -> Self {
            let dir = std::env::temp_dir().join(format!("lanekeep-discovery-{name}"));
            let _ = fs::remove_dir_all(&dir);
            for path in files {
                let full = dir.join(path);
                if let Some(parent) = full.parent() {
                    fs::create_dir_all(parent).expect("creates parent");
                }
                fs::write(&full, "const x = 1;\n").expect("writes");
            }
            fs::create_dir_all(&dir).expect("creates dir");
            Self { dir }
        }

        fn write(&self, path: &str, contents: &str) {
            let full = self.dir.join(path);
            if let Some(parent) = full.parent() {
                fs::create_dir_all(parent).expect("creates parent");
            }
            fs::write(full, contents).expect("writes");
        }

        fn walk(&self, include: &[&str], exclude: &[&str]) -> Vec<String> {
            let include: Vec<String> = include.iter().map(|s| (*s).to_owned()).collect();
            let exclude: Vec<String> = exclude.iter().map(|s| (*s).to_owned()).collect();
            Discovery::new(&self.dir, &include, &exclude)
                .expect("builds")
                .walk()
                .iter()
                .map(|p| p.as_str().to_owned())
                .collect()
        }
    }

    impl Drop for Fixture {
        fn drop(&mut self) {
            let _ = fs::remove_dir_all(&self.dir);
        }
    }

    /// lanekeep's own directory is never a subject, whatever `include` says.
    ///
    /// The walk sees hidden entries on purpose, and nothing excluded `.lanekeep/` — so the
    /// `tsc` driver lanekeep writes there was discovered as a project file, and under `allowJs`
    /// it entered the compiler's program listing and the run key with it.
    #[test]
    fn lanekeeps_own_directory_is_never_selected() {
        let fixture = Fixture::new(
            "own-directory",
            &[
                "src/a.ts",
                ".lanekeep/driver-abc.mjs",
                ".lanekeep/components/x.wasm",
                // A project's own file that merely starts the same way, and one nested under a
                // directory of that name somewhere else: neither is lanekeep's.
                "src/.lanekeep-notes.ts",
                "vendor/.lanekeep/keep.ts",
            ],
        );
        let found = fixture.walk(&["**/*"], &[]);
        assert!(
            !found.iter().any(|p| p.starts_with(".lanekeep/")),
            "lanekeep's own directory reached the corpus: {found:?}"
        );
        assert!(found.contains(&"src/a.ts".to_owned()), "{found:?}");
        assert!(
            found.contains(&"src/.lanekeep-notes.ts".to_owned()),
            "a project file whose name merely begins the same way is a subject: {found:?}"
        );
        assert!(
            found.contains(&"vendor/.lanekeep/keep.ts".to_owned()),
            "only the directory at the root is lanekeep's: {found:?}"
        );
    }

    /// And `selects` agrees, which is the half `--since` and `--staged` go through.
    #[test]
    fn selects_refuses_lanekeeps_own_directory() {
        let fixture = Fixture::new("own-directory-selects", &["src/a.ts"]);
        let discovery = Discovery::new(&fixture.dir, &[], &[]).expect("builds");
        assert!(!discovery.selects(&FilePath::new(".lanekeep/driver-abc.mjs")));
        assert!(discovery.selects(&FilePath::new("src/a.ts")));
    }

    #[test]
    fn finds_files_matching_include() {
        let fixture = Fixture::new(
            "include",
            &["src/a.ts", "src/b.tsx", "src/c.md", "other/d.ts"],
        );
        assert_eq!(fixture.walk(&["src/**/*.ts"], &[]), ["src/a.ts"]);
    }

    #[test]
    fn no_include_selects_everything_found() {
        let fixture = Fixture::new("no-include", &["a.ts", "b.md"]);
        let found = fixture.walk(&[], &[]);
        assert!(found.contains(&"a.ts".to_owned()));
        assert!(found.contains(&"b.md".to_owned()));
    }

    #[test]
    fn exclude_wins_over_include() {
        // The other order would make `exclude` useless, since anything excluded is by
        // definition something `include` matched.
        let fixture = Fixture::new("exclude", &["src/a.ts", "src/a.test.ts"]);
        assert_eq!(
            fixture.walk(&["src/**/*.ts"], &["**/*.test.ts"]),
            ["src/a.ts"]
        );
    }

    #[test]
    fn respects_gitignore() {
        let fixture = Fixture::new("gitignore", &["src/a.ts", "dist/b.ts"]);
        fixture.write(".gitignore", "dist/\n");

        let found = fixture.walk(&["**/*.ts"], &[]);
        assert!(found.contains(&"src/a.ts".to_owned()));
        assert!(
            !found.contains(&"dist/b.ts".to_owned()),
            "gitignored files must not be checked: {found:?}"
        );
    }

    #[test]
    fn the_order_is_sorted_and_stable() {
        // Nothing downstream depends on this order, but feeding workers in filesystem
        // order would make work distribution vary run to run — which looks like
        // nondeterminism the moment a run breaches a budget.
        let fixture = Fixture::new("order", &["z.ts", "a.ts", "m/n.ts", "b.ts"]);
        let first = fixture.walk(&["**/*.ts"], &[]);
        assert_eq!(first, ["a.ts", "b.ts", "m/n.ts", "z.ts"]);

        for _ in 0..5 {
            assert_eq!(fixture.walk(&["**/*.ts"], &[]), first);
        }
    }

    #[test]
    fn reports_a_bad_glob_with_the_field_it_came_from() {
        let fixture = Fixture::new("bad-glob", &["a.ts"]);
        let err =
            Discovery::new(&fixture.dir, &["src/[".to_owned()], &[]).expect_err("malformed glob");

        match err {
            DiscoveryError::InvalidGlob { field, pattern, .. } => {
                assert_eq!(field, "include");
                assert_eq!(pattern, "src/[");
            }
            DiscoveryError::Unreadable { .. } => panic!("wrong error variant"),
        }

        let err =
            Discovery::new(&fixture.dir, &[], &["**/[".to_owned()]).expect_err("malformed glob");
        assert!(
            matches!(
                err,
                DiscoveryError::InvalidGlob {
                    field: "exclude",
                    ..
                }
            ),
            "{err:?}"
        );
    }

    #[test]
    fn a_missing_root_is_reported() {
        let err = Discovery::new("/definitely/not/here", &[], &[]).expect_err("no such root");
        assert!(matches!(err, DiscoveryError::Unreadable { .. }), "{err:?}");
    }

    #[test]
    fn selects_can_be_asked_without_walking() {
        let fixture = Fixture::new("selects", &["a.ts"]);
        let discovery = Discovery::new(
            &fixture.dir,
            &["src/**/*.ts".to_owned()],
            &["**/*.test.ts".to_owned()],
        )
        .expect("builds");

        assert!(discovery.selects(&FilePath::new("src/a.ts")));
        assert!(!discovery.selects(&FilePath::new("src/a.test.ts")));
        assert!(!discovery.selects(&FilePath::new("other/a.ts")));
    }

    #[test]
    fn rejects_names_the_clause_that_would_drop_a_file() {
        let fixture = Fixture::new("rejects", &["src/a.ts", "vendor/x.ts"]);
        let discovery = Discovery::new(
            &fixture.dir,
            &["src/**/*.ts".to_owned()],
            &["vendor/**".to_owned()],
        )
        .expect("builds");

        assert_eq!(
            discovery.rejects(&FilePath::new("src/a.ts")),
            None,
            "a file the globs select is not rejected"
        );
        assert_eq!(
            discovery.rejects(&FilePath::new("vendor/x.ts")),
            Some(Rejection::Excluded {
                pattern: "vendor/**".to_owned()
            }),
        );
        assert_eq!(
            discovery.rejects(&FilePath::new("other/a.ts")),
            Some(Rejection::NotIncluded),
        );
        assert_eq!(
            discovery.rejects(&FilePath::new(".lanekeep/driver.mjs")),
            Some(Rejection::Lanekeep),
        );
    }
}