Skip to main content

import_lint_cli/
setup.rs

1//! Project setup: turning CLI flags + config-file discovery into a `LintConfig`,
2//! project root, roots to walk, `tsconfig` path, and self-reference mode (PLAN-v1.md
3//! §5, D7). Factored out of `main.rs`'s `lint()` (M5) so watch mode's `ConfigChanged`
4//! reload path (`crates/cli/src/watch.rs`, M6 brief D-W1) can redo exactly the same
5//! computation without duplicating it.
6
7use std::fmt;
8use std::path::{Path, PathBuf};
9
10use import_lint::rule::SelfRefOpt;
11use import_lint::{ConfigError, LintConfig, SelfReferenceMode, find_config};
12
13use crate::runner::RunnerOptions;
14
15/// A loaded config plus the project root it implies (D7: the directory containing
16/// the config file, or the caller's cwd if there's no config file at all).
17pub struct LoadedConfig {
18    pub config: LintConfig,
19    pub project_root: PathBuf,
20    /// The config file that was loaded, if any (`None` means defaults, no config
21    /// file found).
22    pub config_path: Option<PathBuf>,
23}
24
25/// Everything that can go wrong resolving a config: an explicit `--config` path that
26/// doesn't exist, or a discovered/explicit file that fails to parse.
27#[derive(Debug)]
28pub enum ConfigLoadError {
29    ExplicitConfigMissing(PathBuf),
30    Parse(ConfigError),
31}
32
33impl fmt::Display for ConfigLoadError {
34    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
35        match self {
36            ConfigLoadError::ExplicitConfigMissing(path) => {
37                write!(f, "--config {}: no such file", path.display())
38            }
39            ConfigLoadError::Parse(err) => write!(f, "failed to load config: {err}"),
40        }
41    }
42}
43
44impl std::error::Error for ConfigLoadError {}
45
46/// Resolve the config file to load: `explicit_config` if given (must exist — an
47/// explicit path that doesn't exist is a usage error, not "use defaults"), else
48/// discovery from `cwd` upward (D7). Load it (or fall back to `LintConfig::default()`
49/// with `project_root = cwd` when no config file exists at all).
50pub fn load_config(
51    explicit_config: Option<&Path>,
52    cwd: &Path,
53) -> Result<LoadedConfig, ConfigLoadError> {
54    let config_path = match explicit_config {
55        Some(explicit) => {
56            if !explicit.is_file() {
57                return Err(ConfigLoadError::ExplicitConfigMissing(
58                    explicit.to_path_buf(),
59                ));
60            }
61            Some(explicit.to_path_buf())
62        }
63        None => find_config(cwd),
64    };
65
66    match config_path {
67        Some(path) => match LintConfig::load(&path) {
68            Ok(config) => {
69                let project_root = path
70                    .parent()
71                    .map(Path::to_path_buf)
72                    .unwrap_or_else(|| cwd.to_path_buf());
73                Ok(LoadedConfig {
74                    config,
75                    project_root,
76                    config_path: Some(path),
77                })
78            }
79            Err(err) => Err(ConfigLoadError::Parse(err)),
80        },
81        None => Ok(LoadedConfig {
82            config: LintConfig::default(),
83            project_root: cwd.to_path_buf(),
84            config_path: None,
85        }),
86    }
87}
88
89/// The roots to walk: `cli_paths` if non-empty (an explicit CLI override always
90/// wins), else `config.include` resolved relative to `project_root`.
91pub fn compute_roots(
92    cli_paths: &[PathBuf],
93    config: &LintConfig,
94    project_root: &Path,
95) -> Vec<PathBuf> {
96    if cli_paths.is_empty() {
97        config
98            .include
99            .iter()
100            .map(|root| project_root.join(root))
101            .collect()
102    } else {
103        cli_paths.to_vec()
104    }
105}
106
107/// The `tsconfig.json` to feed the resolver: `--tsconfig` if given, else
108/// `config.tsconfig` resolved relative to `project_root`, else
109/// `<project_root>/tsconfig.json` if that file exists (`RunnerOptions::default_tsconfig`).
110pub fn compute_tsconfig(
111    cli_tsconfig: Option<&Path>,
112    config: &LintConfig,
113    project_root: &Path,
114) -> Option<PathBuf> {
115    cli_tsconfig
116        .map(Path::to_path_buf)
117        .or_else(|| config.tsconfig.as_ref().map(|path| project_root.join(path)))
118        .or_else(|| RunnerOptions::default_tsconfig(project_root))
119}
120
121/// `config`'s `treatSelfReferenceAs` option (spec §4.6), translated to core's
122/// `SelfReferenceMode`.
123pub fn compute_self_reference_mode(config: &LintConfig) -> SelfReferenceMode {
124    match config.rules.package_access.options.treat_self_reference_as {
125        SelfRefOpt::Internal => SelfReferenceMode::Internal,
126        SelfRefOpt::External => SelfReferenceMode::External,
127    }
128}