skif 0.3.0

Embeddable facade for skif: discover a JS/TS workspace, lint it and plan fixes without IO side effects.
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
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
//! Multi-root discovery: every workspace and standalone package below a directory, each with its own configuration.

use std::collections::{BTreeMap, BTreeSet};
use std::path::{Component, Path, PathBuf};

use rayon::prelude::*;
use skif_config::{
    Assignment, Ceiling, Config, ConfigCache, ConfigError, ConfigLoader, ConfigOverrides, ConfigSource, Origins,
    SourceKind, join_key,
};
use skif_core::FileSystem;
use skif_lint::LintError;
use skif_workspace::{
    DiscoverOptions, RootKind, Workspace, claim_roots, declared_member_dirs, declares_workspace, repository_root,
    scan_candidates,
};

use crate::error::Error;
use crate::root::{Located, config_ceiling, is_enclosed, locate, resolve_config};

/// One root to lint: a workspace or a standalone package, with the configuration that governs it.
#[derive(Debug)]
#[non_exhaustive]
pub struct Target {
    /// Absolute root directory.
    pub root: PathBuf,
    /// Every `skif.toml` or `.skif.toml` from the root up to the ceiling, with what they extend, merged and with the
    /// overrides applied; the defaults when there is none.
    pub config: Config,
    /// Absolute path of the nearest configuration file `config` was read from, when there is one.
    pub config_file: Option<PathBuf>,
    /// The files `config` was merged from, in the order they were applied.
    pub sources: Vec<ConfigSource>,
    /// Where each key of `config` was set, as indices into `sources`.
    pub origins: Origins,
    /// The discovered workspace (a standalone package is a workspace of one package).
    pub workspace: Workspace,
}

impl Target {
    /// The configuration file relative to [`root`](Self::root), for
    /// [`RunOptions::with_config_path`](crate::RunOptions::with_config_path): `skif.toml` when it sits in the root,
    /// `../skif.toml` when it was inherited from a parent directory, `../../etc/skif.toml` when an explicit
    /// configuration lives elsewhere; the absolute path when the two share no directory.
    #[must_use]
    pub fn config_path(&self) -> Option<PathBuf> {
        let file = self.config_file.as_ref()?;
        let base: Vec<Component<'_>> = self.root.components().collect();
        let target: Vec<Component<'_>> = file.components().collect();
        let common = base
            .iter()
            .zip(&target)
            .take_while(|(left, right)| left == right)
            .count();
        if common == 0 {
            return Some(file.clone());
        }
        let mut path: PathBuf = std::iter::repeat_n("..", base.len() - common).collect();
        path.extend(&target[common..]);
        Some(path)
    }

    /// Keeps the `[[ignore]]` entries of [`config`](Self::config) at the indices `keep` accepts, with
    /// [`origins`](Self::origins) renumbered to match, so a later error about an entry still names the file that set
    /// it.
    pub fn retain_ignore(&mut self, keep: impl Fn(usize) -> bool) {
        let entries = std::mem::take(&mut self.config.ignore);
        self.config.ignore = entries
            .into_iter()
            .enumerate()
            .filter(|(index, _)| keep(*index))
            .map(|(_, entry)| entry)
            .collect();
        self.origins.retain_list("ignore", keep);
    }

    /// `error`, raised while building a linter for this target, with an unknown rule ID attributed to the file (and,
    /// for a file of the chain, the line and column) that names it: a `[rules]` key, an `[[ignore]]` entry or an
    /// override. Any other error is returned as it is.
    ///
    /// A located error is a [`ConfigError::Parse`] whose `message` is the [`ConfigError::UnknownRule`] text, its
    /// suggestion included, since that variant has no fields for a file and position; a host that matches on
    /// `UnknownRule` should do so before calling this. An error with no recorded origin stays `UnknownRule`.
    #[must_use]
    pub fn locate(&self, error: Error) -> Error {
        match error {
            Error::Config(error) => Error::Config(self.locate_config(error)),
            Error::Lint(LintError::Config(error)) => Error::Lint(LintError::Config(self.locate_config(error))),
            other => other,
        }
    }

    fn locate_config(&self, error: ConfigError) -> ConfigError {
        let ConfigError::UnknownRule { rule, .. } = &error else {
            return error;
        };
        let Some(assignment) = self.rule_origin(rule) else {
            return error;
        };
        let Some(source) = self.sources.get(assignment.source) else {
            return error;
        };
        // A package file is recorded as a whole, so its position says nothing about the rule.
        let known = |position: usize| (position > 0 && source.kind != SourceKind::Package).then_some(position);
        ConfigError::Parse {
            path: Some(source.path.clone()),
            message: error.to_string(),
            span: None,
            line: known(assignment.line),
            column: known(assignment.column),
        }
    }

    /// The assignment that put `rule` into the configuration: its `[rules]` key, else the first `[[ignore]]` entry
    /// naming it, else the first override that does.
    fn rule_origin(&self, rule: &str) -> Option<&Assignment> {
        let names = |rules: &[String]| rules.iter().any(|id| id == rule);
        let own = join_key("rules", rule);
        let ignore = || {
            let index = self.config.ignore.iter().position(|entry| names(&entry.rules))?;
            self.origins.last(&format!("ignore[{index}]"))
        };
        let scoped = || {
            let index = self.config.overrides.iter().position(|scoped| {
                scoped.rules.contains_key(rule) || scoped.ignore.iter().any(|entry| names(&entry.rules))
            })?;
            self.origins.last(&format!("overrides[{index}]"))
        };
        self.origins
            .last(&format!("{own}.level"))
            .or_else(|| self.origins.last(&format!("{own}.options")))
            .or_else(ignore)
            .or_else(scoped)
    }
}

/// Loads the configuration for `root` from every config file in `root` or a parent up to the `ceiling`, merged (see
/// [`resolve_config`](crate::resolve_config)), and discovers the workspace at `root`.
///
/// A `skif.toml` in the directory of a workspace member (a package file) is applied as an override scoped to that
/// package, after the files of the chain (see [`ConfigLoader::add_package_files`]); `--no-config` skips them.
///
/// `cache` is shared by the roots of a run so each config file is read once; it may be used from several threads.
///
/// # Errors
/// [`Error::Config`] for an unreadable, ambiguous or invalid configuration, [`Error::Workspace`] when the root cannot
/// be discovered.
pub fn load_target(
    root: &Path,
    ceiling: &Ceiling,
    fs: &dyn FileSystem,
    overrides: &ConfigOverrides,
    cache: &ConfigCache,
) -> Result<Target, Error> {
    let mut resolved = resolve_config(root, ceiling, fs, overrides, cache)?;
    let workspace = Workspace::discover_with_fs(root, &resolved.config, fs)?;
    if !overrides.no_config {
        let members: Vec<PathBuf> = workspace.member_dirs().into_iter().collect();
        ConfigLoader::new(fs, cache).add_package_files(&mut resolved, root, &members)?;
    }
    let file = resolved.nearest_file().map(Path::to_path_buf);
    Ok(Target {
        root: root.to_path_buf(),
        config: resolved.config,
        config_file: file,
        sources: resolved.sources,
        origins: resolved.origins,
        workspace,
    })
}

/// Loads `root` with the configuration its repository gives it: the config files at and above `root` up to the root
/// of the git repository, or `root` alone outside one.
fn load_in_repository(
    root: &Path,
    fs: &dyn FileSystem,
    overrides: &ConfigOverrides,
    cache: &ConfigCache,
) -> Result<Target, Error> {
    load_target(root, &Ceiling::Vcs, fs, overrides, cache)
}

/// Finds the workspace that `start` belongs to and loads it, discovering it once.
///
/// The root is the one [`find_workspace_root`](crate::find_workspace_root) names. Its configuration is every config
/// file at or above it, up to the root of the git repository holding it (the root itself outside one), merged, which
/// is the configuration [`discover_all`] gives the same directory. A standalone package with a project above it in the
/// same repository is marked [`Workspace::is_nested`], as [`discover_targets`] marks it.
///
/// # Errors
/// [`Error::RelativePath`] for a relative `start`, [`Error::NoWorkspace`] when `start` and its ancestors hold no
/// project, otherwise [`load_target`]'s errors for the chosen root. An ancestor workspace that lists the project but
/// cannot be loaded is that error, not a silent fallback to the project alone.
pub fn find_target(start: &Path, fs: &dyn FileSystem, overrides: &ConfigOverrides) -> Result<Target, Error> {
    let cached = crate::cache::per_call(fs);
    let fs: &dyn FileSystem = &cached;
    let Located { project, ancestors } = locate(start, fs)?;
    let cache = ConfigCache::new();
    if declares_workspace(fs, &project) {
        return load_in_repository(&project, fs, overrides, &cache);
    }
    for ancestor in ancestors {
        match load_in_repository(&ancestor, fs, overrides, &cache) {
            Ok(target) if target.workspace.claimed_dirs().contains(&project) => return Ok(target),
            Err(error) if declared_member_dirs(fs, &ancestor).contains(&project) => return Err(error),
            _ => {}
        }
    }
    let mut target = load_in_repository(&project, fs, overrides, &cache)?;
    if !declares_workspace(fs, &project) {
        target
            .workspace
            .set_nested(is_enclosed(&project, &config_ceiling(&project, fs), fs));
    }
    Ok(target)
}

/// A root that could not be loaded.
#[derive(Debug)]
#[non_exhaustive]
pub struct RootFailure {
    /// The root directory.
    pub root: PathBuf,
    /// Why it could not be loaded.
    pub error: Error,
}

/// The outcome of [`discover_targets`].
#[derive(Debug, Default)]
#[non_exhaustive]
pub struct Discovery {
    /// The roots that loaded, sorted by path.
    pub targets: Vec<Target>,
    /// The roots that did not, sorted by path.
    pub failures: Vec<RootFailure>,
    /// Directories at the depth limit with subdirectories the walk did not enter.
    pub truncated: Vec<PathBuf>,
}

/// Finds every workspace root and standalone package at or below `start` and loads each as a [`Target`], sorted by
/// path (see [`skif_workspace::claim_roots`] for what counts as a root).
///
/// Each workspace is discovered once, with the configuration that governs it, and the directories it lists decide
/// which packages are claimed. A root's configuration is every config file at or above it, up to the root of the git
/// repository holding it (`start` outside one), merged farthest first, so a project file adds to the organisation
/// file above it unless it says `root = true`. The config files are read once for all the roots. A workspace that is listed as a member of an outer workspace
/// is a root of its own and the outer one leaves its package to it, so every package is linted by exactly one root.
///
/// A standalone package below another root is marked [`Workspace::is_nested`], which the rules that only concern a
/// repository's outermost project (`root-package-manager-field`) honour. Directories matching
/// `[workspace] discover-ignore` (by default `__fixtures__`, `fixtures`, `__mocks__` and `__snapshots__`) are not
/// searched for roots; the setting is read from the configuration file that governs `start`. A workspace declared
/// by `pnpm-workspace.yaml` or `rush.json` alone, with no root `package.json`, loads as a workspace without a root
/// manifest.
///
/// A root that cannot be loaded is a [`RootFailure`]; the others still load. A workspace that cannot be loaded
/// still claims the directories its patterns declare.
///
/// Roots can read one configuration file (a `--config` file, or a file above them), and each judges its settings on
/// its own; a host that lints the targets passes the reports, in this order, to
/// [`settle_shared_config`](crate::settle_shared_config) so a `stale-js-config` finding about such a file is reported
/// once, and only when no root used the setting.
///
/// # Errors
/// [`Error::RelativePath`] for a relative `start`.
pub fn discover_targets(start: &Path, fs: &dyn FileSystem, overrides: &ConfigOverrides) -> Result<Discovery, Error> {
    let cached = crate::cache::per_call(fs);
    let fs: &dyn FileSystem = &cached;
    if !start.has_root() {
        return Err(Error::RelativePath(start.to_path_buf()));
    }
    let dir = if fs.is_dir(start) {
        start
    } else {
        start.parent().unwrap_or(start)
    };
    let cache = ConfigCache::new();
    let ceiling = Ceiling::VcsOr(dir.to_path_buf());
    let enclosing = |root: &Path| repository_ceiling(root, dir, fs);
    let candidates = scan_candidates(dir, fs, &discover_options(dir, fs, overrides, &cache));
    let mut workspaces: BTreeMap<PathBuf, Result<Target, Error>> = candidates
        .workspaces
        .par_iter()
        .map(|root| (root.clone(), load_target(root, &ceiling, fs, overrides, &cache)))
        .collect();
    let members: BTreeMap<PathBuf, BTreeSet<PathBuf>> = workspaces
        .iter()
        .map(|(root, loaded)| {
            let dirs = match loaded {
                Ok(target) => target.workspace.claimed_dirs(),
                Err(_) => declared_member_dirs(fs, root),
            };
            (root.clone(), dirs)
        })
        .collect();
    let claimed = claim_roots(fs, &candidates, &members);
    let slots: Vec<(PathBuf, Option<Result<Target, Error>>)> = claimed
        .iter()
        .map(|root| (root.path().to_path_buf(), workspaces.remove(root.path())))
        .collect();
    let loaded: Vec<(PathBuf, Result<Target, Error>)> = slots
        .into_par_iter()
        .map(|(root, found)| {
            let result = found.unwrap_or_else(|| load_target(&root, &ceiling, fs, overrides, &cache));
            (root, result)
        })
        .collect();
    let mut discovery = Discovery {
        truncated: candidates.truncated,
        ..Discovery::default()
    };
    let root_dirs: BTreeSet<&Path> = claimed.iter().map(RootKind::path).collect();
    for (root, result) in loaded {
        match result {
            Ok(mut target) => {
                let nested = !candidates.workspaces.contains(&root)
                    && (root.ancestors().skip(1).any(|ancestor| root_dirs.contains(ancestor))
                        || is_enclosed(&root, &enclosing(&root), fs));
                target.workspace.set_nested(nested);
                target.workspace.ignore_dirs(&candidates.workspaces);
                if overrides.config_file.is_some() {
                    target.workspace.set_workspace_keys_anchor(start_relative(&root, dir));
                }
                discovery.targets.push(target);
            }
            Err(error) => discovery.failures.push(RootFailure { root, error }),
        }
    }
    Ok(discovery)
}

/// `root` relative to `start`, the directory a run with an explicit configuration file started at, when `root` lies
/// below it: the [`Workspace::set_workspace_keys_anchor`] of the root, so that the `[js.workspaces]` keys and
/// `ignore-workspaces` globs of the file select packages from `start` (ADR 0098). `"."` is then the root at `start`
/// alone, and `tools/sub` the root in that directory. `None` for the root at `start`.
fn start_relative(root: &Path, start: &Path) -> Option<String> {
    root.strip_prefix(start)
        .ok()
        .filter(|rel| !rel.as_os_str().is_empty())
        .map(crate::slash)
}

/// Why a configuration file below a root was not applied.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum UnappliedReason {
    /// The file is not in the root's own directory or in the directory of one of its workspace members, the only
    /// places configuration is read from.
    NotAMember,
    /// The file is in a member's directory but was not loaded for this run.
    NotLoaded,
}

impl UnappliedReason {
    /// A short sentence for output.
    #[must_use]
    pub const fn describe(self) -> &'static str {
        match self {
            Self::NotAMember => "not in the root or a workspace member directory",
            Self::NotLoaded => "in a workspace member directory but not loaded for this run",
        }
    }
}

/// A `skif.toml` below a root that no configuration of that root was built from.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct UnappliedConfig {
    /// Absolute path of the file.
    pub path: PathBuf,
    /// Why the file was not applied.
    pub reason: UnappliedReason,
}

/// The `skif.toml` and `.skif.toml` files below `target.root` that its configuration was not built from, sorted by
/// path.
///
/// Configuration is read from the root, the directories above it, what those files extend, and the directory of each
/// workspace member (a package file). Any other file is reported here with the reason. The walk skips `node_modules`,
/// hidden directories and what git ignores, but enters directories `workspace.discover-ignore` skips (a fixture
/// directory is a likely home for such a file). A file in the directory of a deeper root of the same run
/// (`other_roots`) belongs to that root and is not reported.
#[must_use]
pub fn unapplied_config_files(target: &Target, other_roots: &[&Path], fs: &dyn FileSystem) -> Vec<UnappliedConfig> {
    let candidates = scan_candidates(&target.root, fs, &unapplied_scan_options());
    unapplied_among(target, other_roots, candidates.config_files)
}

/// [`unapplied_config_files`] for every target of a run at once: entry `i` is the answer for `targets[i]`, with the
/// other targets as the deeper roots.
///
/// The tree below each outermost root is walked once and its files are shared out among the roots inside it, where
/// calling [`unapplied_config_files`] per target walks an inner tree once for every root around it.
#[must_use]
pub fn unapplied_config_files_all(targets: &[Target], fs: &dyn FileSystem) -> Vec<Vec<UnappliedConfig>> {
    let roots: Vec<&Path> = targets.iter().map(|target| target.root.as_path()).collect();
    let mut scans: BTreeMap<&Path, BTreeSet<PathBuf>> = BTreeMap::new();
    targets
        .iter()
        .map(|target| {
            let outermost = roots
                .iter()
                .copied()
                .filter(|root| target.root.starts_with(root))
                .min_by_key(|root| root.components().count())
                .unwrap_or(target.root.as_path());
            let files = scans
                .entry(outermost)
                .or_insert_with(|| scan_candidates(outermost, fs, &unapplied_scan_options()).config_files);
            let below = files.iter().filter(|file| file.starts_with(&target.root)).cloned();
            unapplied_among(target, &roots, below)
        })
        .collect()
}

/// The walk that looks for configuration files: nothing is skipped by `workspace.discover-ignore`.
fn unapplied_scan_options() -> DiscoverOptions {
    DiscoverOptions::default().with_ignore(Vec::new())
}

/// The files of `config_files` below `target.root` that its configuration was not built from.
fn unapplied_among(
    target: &Target,
    other_roots: &[&Path],
    config_files: impl IntoIterator<Item = PathBuf>,
) -> Vec<UnappliedConfig> {
    let members = target.workspace.member_dirs();
    config_files
        .into_iter()
        .filter_map(|path| {
            let dir = path.parent()?;
            let owned_elsewhere = other_roots
                .iter()
                .any(|other| *other != target.root && other.starts_with(&target.root) && dir.starts_with(other));
            if dir == target.root || owned_elsewhere || target.sources.iter().any(|source| source.path == path) {
                return None;
            }
            let reason = if members.contains(dir) {
                UnappliedReason::NotLoaded
            } else {
                UnappliedReason::NotAMember
            };
            Some(UnappliedConfig { path, reason })
        })
        .collect()
}

/// The bounds of the walk started at `start`: the defaults, with the skipped directories from the configuration that
/// governs `start` when it loads (a broken file is reported by the root that uses it, not here).
fn discover_options(
    start: &Path,
    fs: &dyn FileSystem,
    overrides: &ConfigOverrides,
    cache: &ConfigCache,
) -> DiscoverOptions {
    match resolve_config(start, &Ceiling::Vcs, fs, overrides, cache) {
        Ok(resolved) => DiscoverOptions::default().with_ignore(resolved.config.workspace.discover_ignore),
        Err(_) => DiscoverOptions::default(),
    }
}

/// The directory the configuration search of `root` stops at in a run started at `start`.
fn repository_ceiling(root: &Path, start: &Path, fs: &dyn FileSystem) -> PathBuf {
    repository_root(fs, root).unwrap_or_else(|| start.to_path_buf())
}

/// Like [`discover_targets`], failing with the first root that cannot be loaded.
///
/// # Errors
/// [`Error::RelativePath`] for a relative `start`, otherwise the first failing root's [`load_target`] error.
///
/// # Examples
/// ```
/// use std::path::Path;
/// use skif::{ConfigOverrides, MemoryFs, discover_all};
///
/// let fs = MemoryFs::new()
///     .with_file("/r/a/package.json", r#"{"name": "a", "version": "1.0.0"}"#)
///     .with_file("/r/b/package.json", r#"{"name": "b", "version": "1.0.0"}"#);
/// let targets = discover_all(Path::new("/r"), &fs, &ConfigOverrides::default())?;
/// assert_eq!(targets.len(), 2);
/// # Ok::<(), skif::Error>(())
/// ```
pub fn discover_all(start: &Path, fs: &dyn FileSystem, overrides: &ConfigOverrides) -> Result<Vec<Target>, Error> {
    let discovery = discover_targets(start, fs, overrides)?;
    match discovery.failures.into_iter().next() {
        Some(failure) => Err(failure.error),
        None => Ok(discovery.targets),
    }
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
    use skif_core::MemoryFs;
    use skif_workspace::PackageManager;

    use super::*;

    fn fs() -> MemoryFs {
        MemoryFs::new()
            .with_file("/r/skif.toml", "[lint]\nfail-on-warnings = true\n")
            .with_file("/r/a/package.json", r#"{"name": "a", "version": "1.0.0"}"#)
            .with_file("/r/b/skif.toml", "")
            .with_file("/r/b/package.json", r#"{"name": "b", "version": "1.0.0"}"#)
    }

    #[test]
    fn every_config_up_to_the_start_directory_contributes() {
        let targets = discover_all(Path::new("/r"), &fs(), &ConfigOverrides::default()).unwrap();
        let roots: Vec<_> = targets.iter().map(|target| target.root.clone()).collect();
        assert_eq!(roots, [PathBuf::from("/r/a"), PathBuf::from("/r/b")]);
        assert!(targets[0].config.lint.fail_on_warnings);
        assert_eq!(targets[0].config_path(), Some(PathBuf::from("../skif.toml")));
        assert_eq!(targets[0].sources.len(), 1);
        assert!(targets[1].config.lint.fail_on_warnings);
        assert_eq!(targets[1].config_path(), Some(PathBuf::from("skif.toml")));
        assert_eq!(targets[1].sources.len(), 2);
    }

    #[test]
    fn config_above_the_start_directory_is_not_inherited() {
        let targets = discover_all(Path::new("/r/a"), &fs(), &ConfigOverrides::default()).unwrap();
        assert_eq!(targets.len(), 1);
        assert!(!targets[0].config.lint.fail_on_warnings);
        assert_eq!(targets[0].config_path(), None);
    }

    #[test]
    fn an_explicit_configuration_outside_the_root_is_named_relative_to_it() {
        let fs = MemoryFs::new()
            .with_file("/r/a/package.json", r#"{"name": "a", "version": "1.0.0"}"#)
            .with_file("/etc/org/skif.toml", "[lint]\nfail-on-warnings = true\n");
        let overrides = ConfigOverrides::default().with_config_file(Some(PathBuf::from("/etc/org/skif.toml")));
        let target = load_target(Path::new("/r/a"), &Ceiling::Vcs, &fs, &overrides, &ConfigCache::new()).unwrap();
        assert_eq!(target.config_file, Some(PathBuf::from("/etc/org/skif.toml")));
        assert_eq!(target.config_path(), Some(PathBuf::from("../../etc/org/skif.toml")));
    }

    fn nested_fs(explicit: &str) -> MemoryFs {
        MemoryFs::new()
            .with_file("/r/package.json", r#"{"name": "app", "version": "1.0.0"}"#)
            .with_file("/r/tools/sub/package.json", r#"{"name": "sub", "version": "1.0.0"}"#)
            .with_file(
                "/r/tools/other/package.json",
                r#"{"name": "other", "version": "1.0.0"}"#,
            )
            .with_file("/etc/skif.toml", explicit)
    }

    fn anchors(start: &str, fs: &MemoryFs, overrides: &ConfigOverrides) -> Vec<(PathBuf, Option<String>)> {
        discover_all(Path::new(start), fs, overrides)
            .unwrap()
            .into_iter()
            .map(|target| {
                let anchor = target.workspace.workspace_keys_anchor().map(str::to_owned);
                (target.root, anchor)
            })
            .collect()
    }

    fn explicit() -> ConfigOverrides {
        ConfigOverrides::default().with_config_file(Some(PathBuf::from("/etc/skif.toml")))
    }

    #[test]
    fn an_explicit_configuration_anchors_the_workspace_keys_of_nested_roots_at_the_start() {
        for file in [
            "[js.workspaces.\".\"]\nentry = [\"src/extra.js\"]\n",
            "[js]\nignore-workspaces = [\"tools/sub/legacy\"]\n",
            "[js]\nentry = [\"src/extra.js\"]\n",
        ] {
            assert_eq!(
                anchors("/r", &nested_fs(file), &explicit()),
                [
                    (PathBuf::from("/r"), None),
                    (PathBuf::from("/r/tools/other"), Some("tools/other".to_owned())),
                    (PathBuf::from("/r/tools/sub"), Some("tools/sub".to_owned())),
                ],
                "{file}"
            );
        }
    }

    #[test]
    fn the_configuration_carries_no_anchor_so_anchored_roots_share_it() {
        let targets = discover_all(
            Path::new("/r"),
            &nested_fs("[js.workspaces.\"tools/*\"]\nentry = [\"src/extra.js\"]\n"),
            &explicit(),
        )
        .unwrap();
        assert_eq!(targets.len(), 3);
        assert!(targets.iter().all(|target| target.config == targets[0].config));
    }

    #[test]
    fn a_start_that_is_no_root_anchors_every_root_below_it() {
        let fs = MemoryFs::new()
            .with_file("/r/a/package.json", r#"{"name": "a", "version": "1.0.0"}"#)
            .with_file("/r/b/sub/package.json", r#"{"name": "sub", "version": "1.0.0"}"#)
            .with_file("/etc/skif.toml", "[js.workspaces.\"a\"]\nentry = [\"src/extra.js\"]\n");
        assert_eq!(
            anchors("/r", &fs, &explicit()),
            [
                (PathBuf::from("/r/a"), Some("a".to_owned())),
                (PathBuf::from("/r/b/sub"), Some("b/sub".to_owned())),
            ]
        );
    }

    #[test]
    fn discovered_configurations_leave_the_roots_unanchored() {
        let discovered = nested_fs("").with_file("/r/skif.toml", "[js.workspaces.\".\"]\nentry = [\"src/extra.js\"]\n");
        assert_eq!(
            anchors("/r", &discovered, &ConfigOverrides::default()),
            [
                (PathBuf::from("/r"), None),
                (PathBuf::from("/r/tools/other"), None),
                (PathBuf::from("/r/tools/sub"), None),
            ]
        );
    }

    #[test]
    fn the_root_a_run_starts_at_is_never_anchored() {
        let fs = nested_fs("[js.workspaces.\".\"]\nentry = [\"src/extra.js\"]\n");
        let expected: [(PathBuf, Option<String>); 1] = [(PathBuf::from("/r/tools/sub"), None)];
        assert_eq!(anchors("/r/tools/sub", &fs, &explicit()), expected);
    }

    #[test]
    fn relative_start_is_rejected() {
        assert!(matches!(
            discover_all(Path::new("r"), &fs(), &ConfigOverrides::default()),
            Err(Error::RelativePath(_))
        ));
    }

    fn names(discovery: &Discovery) -> Vec<String> {
        discovery
            .targets
            .iter()
            .map(|target| target.root.display().to_string().replace('\\', "/"))
            .collect()
    }

    fn discover(fs: &MemoryFs, start: &str) -> Discovery {
        discover_targets(Path::new(start), fs, &ConfigOverrides::default()).unwrap()
    }

    fn packages_of(target: &Target) -> Vec<String> {
        target
            .workspace
            .iter()
            .filter(|(id, _)| !target.workspace.is_ignored(*id))
            .filter_map(|(_, package)| package.name.clone())
            .collect()
    }

    fn divergent_declarations() -> MemoryFs {
        MemoryFs::new()
            .with_file("/r/package.json", r#"{"name": "root", "workspaces": ["npmpkgs/*"]}"#)
            .with_file("/r/pnpm-workspace.yaml", "packages:\n  - 'yarnpkgs/*'\n")
            .with_file("/r/skif.toml", "[workspace]\npackage-manager = \"npm\"\n")
            .with_file("/r/npmpkgs/x/package.json", r#"{"name": "x"}"#)
            .with_file("/r/yarnpkgs/y/package.json", r#"{"name": "y"}"#)
    }

    #[test]
    fn members_are_claimed_with_the_root_s_own_configuration() {
        let discovery = discover(&divergent_declarations(), "/r");
        assert_eq!(names(&discovery), ["/r", "/r/yarnpkgs/y"]);
        assert_eq!(packages_of(&discovery.targets[0]), ["root", "x"]);
        assert_eq!(packages_of(&discovery.targets[1]), ["y"]);
    }

    #[test]
    fn a_nested_workspace_is_a_root_and_its_members_are_linted_once() {
        let fs = MemoryFs::new()
            .with_file("/r/package.json", r#"{"name": "root", "workspaces": ["packages/*"]}"#)
            .with_file(
                "/r/packages/inner/package.json",
                r#"{"name": "inner", "workspaces": ["x/*"]}"#,
            )
            .with_file("/r/packages/inner/x/y/package.json", r#"{"name": "y"}"#)
            .with_file("/r/packages/plain/package.json", r#"{"name": "plain"}"#);
        let discovery = discover(&fs, "/r");
        assert_eq!(names(&discovery), ["/r", "/r/packages/inner"]);
        assert_eq!(packages_of(&discovery.targets[0]), ["root", "plain"]);
        assert_eq!(packages_of(&discovery.targets[1]), ["inner", "y"]);

        let direct = find_target(Path::new("/r/packages/inner"), &fs, &ConfigOverrides::default()).unwrap();
        assert_eq!(direct.root, Path::new("/r/packages/inner"));
        assert_eq!(packages_of(&direct), ["inner", "y"]);
    }

    #[test]
    fn a_root_that_fails_is_reported_and_the_others_still_load() {
        let fs = MemoryFs::new()
            .with_file("/r/bad/package.json", r#"{"name": "#)
            .with_file("/r/good/package.json", r#"{"name": "good", "version": "1.0.0"}"#)
            .with_file("/r/ws/pnpm-workspace.yaml", "packages:\n  - 'p/*'\n")
            .with_file("/r/ws/p/m/package.json", r#"{"name": "m"}"#);
        let discovery = discover(&fs, "/r");
        assert_eq!(names(&discovery), ["/r/good", "/r/ws"]);
        let failed: Vec<_> = discovery.failures.iter().map(|failure| failure.root.clone()).collect();
        assert_eq!(failed, [PathBuf::from("/r/bad")]);
        assert!(discover_all(Path::new("/r"), &fs, &ConfigOverrides::default()).is_err());
    }

    #[test]
    fn the_loaded_workspace_carries_its_own_members_and_configuration() {
        let discovery = discover(&divergent_declarations(), "/r");
        let root = &discovery.targets[0];
        assert_eq!(root.workspace.member_dirs().len(), 1);
        assert_eq!(root.config_path(), Some(PathBuf::from("skif.toml")));
    }

    fn nested_project_in_a_workspace_tree() -> MemoryFs {
        MemoryFs::new()
            .with_file("/r/.git/HEAD", "ref")
            .with_file("/r/I/skif.toml", "[lint]\nfail-on-warnings = true\n")
            .with_file("/r/I/package.json", r#"{"name": "i", "workspaces": ["pkgs/*"]}"#)
            .with_file("/r/I/pkgs/a/package.json", r#"{"name": "a"}"#)
            .with_file("/r/I/examples/e/package.json", r#"{"name": "e"}"#)
    }

    #[test]
    fn a_project_gets_the_same_configuration_whichever_way_it_is_reached() {
        let fs = nested_project_in_a_workspace_tree();
        let overrides = ConfigOverrides::default();
        let discovery = discover(&fs, "/r/I");
        let by_discovery = discovery
            .targets
            .iter()
            .find(|target| target.root == Path::new("/r/I/examples/e"))
            .unwrap();
        let direct = find_target(Path::new("/r/I/examples/e"), &fs, &overrides).unwrap();
        assert!(by_discovery.config.lint.fail_on_warnings);
        assert_eq!(direct.config, by_discovery.config);
        assert_eq!(direct.config_path(), Some(PathBuf::from("../../skif.toml")));
    }

    #[test]
    fn the_configuration_search_climbs_to_the_repository_root_and_no_higher() {
        let fs = nested_project_in_a_workspace_tree()
            .with_file("/skif.toml", "[lint]\nfail-on-warnings = true\n")
            .with_file("/r/skif.toml", "")
            .with_file("/r/solo/package.json", r#"{"name": "solo"}"#);
        let found = find_target(Path::new("/r/solo"), &fs, &ConfigOverrides::default()).unwrap();
        assert!(!found.config.lint.fail_on_warnings);
        assert_eq!(found.config_file, Some(PathBuf::from("/r/skif.toml")));
        assert_eq!(found.config_path(), Some(PathBuf::from("../skif.toml")));
    }

    #[test]
    fn find_target_returns_the_ancestor_that_lists_the_project() {
        let fs = divergent_declarations();
        let target = find_target(Path::new("/r/npmpkgs/x"), &fs, &ConfigOverrides::default()).unwrap();
        assert_eq!(target.root, Path::new("/r"));
        let own = find_target(Path::new("/r/yarnpkgs/y"), &fs, &ConfigOverrides::default()).unwrap();
        assert_eq!(own.root, Path::new("/r/yarnpkgs/y"));
    }

    #[test]
    fn an_ancestor_that_lists_the_project_but_cannot_load_is_an_error() {
        let fs = MemoryFs::new()
            .with_file("/r/package.json", r#"{"workspaces": ["p/*"]"#)
            .with_file("/r/pnpm-workspace.yaml", "packages:\n  - 'p/*'\n")
            .with_file("/r/p/m/package.json", r#"{"name": "m"}"#);
        let error = find_target(Path::new("/r/p/m"), &fs, &ConfigOverrides::default()).unwrap_err();
        assert!(matches!(error, Error::Workspace(_)), "{error}");
    }

    #[test]
    fn both_ancestor_searches_name_an_ancestor_whose_configuration_is_broken() {
        let fs = MemoryFs::new()
            .with_file("/r/package.json", r#"{"workspaces": ["p/*"]}"#)
            .with_file("/r/skif.toml", "[lint\n")
            .with_file("/r/p/m/package.json", r#"{"name": "m"}"#);
        let start = Path::new("/r/p/m");
        assert_eq!(crate::find_workspace_root(start, &fs).unwrap(), Path::new("/r"));
        let error = find_target(start, &fs, &ConfigOverrides::default()).unwrap_err();
        assert!(matches!(error, Error::Config(_)), "{error}");
    }

    #[test]
    fn unapplied_files_of_all_targets_match_the_per_target_answers() {
        let fs = MemoryFs::new()
            .with_file("/r/package.json", r#"{"name": "root", "workspaces": ["packages/*"]}"#)
            .with_file("/r/packages/a/package.json", r#"{"name": "a"}"#)
            .with_file("/r/packages/a/skif.toml", "")
            .with_file("/r/stray/skif.toml", "")
            .with_file("/r/inner/pnpm-workspace.yaml", "packages:\n  - 'q/*'\n")
            .with_file("/r/inner/q/n/package.json", r#"{"name": "n"}"#)
            .with_file("/r/inner/q/n/skif.toml", "")
            .with_file("/r/inner/loose/skif.toml", "");
        let targets = discover(&fs, "/r").targets;
        assert_eq!(names(&discover(&fs, "/r")), ["/r", "/r/inner"]);
        let roots: Vec<&Path> = targets.iter().map(|target| target.root.as_path()).collect();
        let expected: Vec<Vec<UnappliedConfig>> = targets
            .iter()
            .map(|target| unapplied_config_files(target, &roots, &fs))
            .collect();
        assert_eq!(unapplied_config_files_all(&targets, &fs), expected);
        let paths =
            |files: &[UnappliedConfig]| -> Vec<PathBuf> { files.iter().map(|file| file.path.clone()).collect() };
        assert_eq!(paths(&expected[0]), [PathBuf::from("/r/stray/skif.toml")]);
        assert_eq!(paths(&expected[1]), [PathBuf::from("/r/inner/loose/skif.toml")]);
    }

    #[test]
    fn only_standalone_packages_below_another_root_are_nested() {
        let fs = MemoryFs::new()
            .with_file("/s/a/package.json", r#"{"name": "a"}"#)
            .with_file("/s/b/package.json", r#"{"name": "b"}"#)
            .with_file("/s/b/inner/package.json", r#"{"name": "inner"}"#)
            .with_file("/s/w/package.json", r#"{"name": "w", "workspaces": ["p/*"]}"#)
            .with_file("/s/w/p/m/package.json", r#"{"name": "m"}"#)
            .with_file("/s/w/examples/e/package.json", r#"{"name": "e"}"#)
            .with_file("/s/w/examples/e/deeper/pnpm-workspace.yaml", "packages:\n  - 'q/*'\n")
            .with_file("/s/w/examples/e/deeper/q/n/package.json", r#"{"name": "n"}"#);
        let discovery = discover(&fs, "/s");
        let nested: Vec<_> = discovery
            .targets
            .iter()
            .map(|target| {
                (
                    target.root.display().to_string().replace('\\', "/"),
                    target.workspace.is_nested(),
                )
            })
            .collect();
        assert_eq!(
            nested,
            [
                ("/s/a".to_owned(), false),
                ("/s/b".to_owned(), false),
                ("/s/b/inner".to_owned(), true),
                ("/s/w".to_owned(), false),
                ("/s/w/examples/e".to_owned(), true),
                ("/s/w/examples/e/deeper".to_owned(), false),
            ]
        );
    }

    #[test]
    fn a_single_root_is_never_nested() {
        let fs = MemoryFs::new()
            .with_file("/r/package.json", r#"{"name": "r"}"#)
            .with_file("/r/inner/package.json", r#"{"name": "inner"}"#);
        let target = find_target(Path::new("/r/inner"), &fs, &ConfigOverrides::default()).unwrap();
        assert!(!target.workspace.is_nested());
    }

    #[test]
    fn a_workspace_file_without_a_root_manifest_is_a_workspace_and_not_a_failure() {
        let fs = MemoryFs::new()
            .with_file("/r/ws/pnpm-workspace.yaml", "packages:\n  - 'p/*'\n")
            .with_file("/r/ws/p/m/package.json", r#"{"name": "m"}"#);
        let discovery = discover(&fs, "/r");
        assert!(discovery.failures.is_empty(), "{:?}", discovery.failures);
        assert_eq!(names(&discovery), ["/r/ws"]);
        assert!(!discovery.targets[0].workspace.has_root_manifest());
        assert_eq!(packages_of(&discovery.targets[0]), ["m"]);

        let direct = find_target(Path::new("/r/ws"), &fs, &ConfigOverrides::default()).unwrap();
        assert_eq!(direct.root, Path::new("/r/ws"));
        assert_eq!(packages_of(&direct), ["m"]);
    }

    #[test]
    fn a_rush_workspace_is_one_root_with_its_projects_as_members() {
        let fs = MemoryFs::new()
            .with_file(
                "/r/rush.json",
                r#"{"npmVersion": "10.0.0", "projects": [{"packageName": "a", "projectFolder": "apps/a"}]}"#,
            )
            .with_file("/r/apps/a/package.json", r#"{"name": "a"}"#)
            .with_file("/r/apps/a/examples/e/package.json", r#"{"name": "e"}"#);
        let discovery = discover(&fs, "/r");
        assert_eq!(names(&discovery), ["/r"]);
        assert_eq!(packages_of(&discovery.targets[0]), ["a"]);
        assert_eq!(
            discovery.targets[0].workspace.package_manager,
            Some(PackageManager::Npm)
        );
    }

    #[test]
    fn fixture_directories_are_skipped_unless_the_configuration_says_otherwise() {
        let tree = MemoryFs::new()
            .with_file("/r/real/package.json", r#"{"name": "real"}"#)
            .with_file("/r/real/fixtures/f/package.json", r#"{"name": "f"}"#)
            .with_file("/r/examples/e/package.json", r#"{"name": "e"}"#);
        assert_eq!(names(&discover(&tree, "/r")), ["/r/examples/e", "/r/real"]);

        let replaced = tree
            .clone()
            .with_file("/r/skif.toml", "[workspace]\ndiscover-ignore = [\"examples\"]\n");
        assert_eq!(names(&discover(&replaced, "/r")), ["/r/real", "/r/real/fixtures/f"]);

        let none = tree.with_file("/r/skif.toml", "[workspace]\ndiscover-ignore = []\n");
        assert_eq!(
            names(&discover(&none, "/r")),
            ["/r/examples/e", "/r/real", "/r/real/fixtures/f"]
        );
    }
}