Skip to main content

fallow_engine/resolved_run/
steps.rs

1//! The steps of a config load: validate, flatten the production mode,
2//! resolve with the environment, and collect the workspace metadata.
3//!
4//! [`super::resolve::resolve_run`] and the `config_for_project*` entry
5//! points of [`crate::project_config`] call the same steps, so each step has
6//! one implementation.
7
8use std::path::{Path, PathBuf};
9
10use fallow_config::{
11    CommandKind, ConfigInputs, ConfigInputsSnapshot, EnvSnapshot, EnvVar, FallowConfig,
12    ResolvedConfig, WorkspaceDiagnostic, WorkspaceInfo,
13};
14use rustc_hash::FxHashSet;
15
16use crate::project_config::ResolveOptions;
17use crate::{EngineError, EngineResult};
18
19/// The resolved config of one production mode, with its workspace metadata.
20#[derive(Debug)]
21pub struct ModeEntry {
22    /// The resolved config.
23    pub config: ResolvedConfig,
24    /// The plugin files, rule packs and `autoDiscover` directories that
25    /// resolution read.
26    pub inputs: ConfigInputs,
27    /// The content of [`Self::inputs`] just before resolution read them.
28    pub inputs_before_resolve: ConfigInputsSnapshot,
29    /// The workspaces under the root.
30    pub workspaces: Vec<WorkspaceInfo>,
31    /// The diagnostics of workspace discovery.
32    pub workspace_diagnostics: Vec<WorkspaceDiagnostic>,
33    /// The wall time of workspace discovery, in milliseconds.
34    pub workspace_discovery_ms: f64,
35}
36
37/// The run settings that a surface gives and that win over the environment.
38#[derive(Debug, Clone, Default)]
39pub struct GivenSettings {
40    /// The max file size in megabytes.
41    pub max_file_size_mb: Option<u32>,
42    /// The cache directory. A relative path resolves from the project root.
43    pub cache_dir: Option<PathBuf>,
44    /// Whether dead code reports the exports of entry files.
45    pub include_entry_exports: Option<bool>,
46    /// Whether the run reads `workspaces.changedSince`.
47    pub package_baselines: Option<bool>,
48}
49
50impl GivenSettings {
51    /// The snapshot without the variables that a given setting replaces. A
52    /// given `package_baselines` must remove `FALLOW_PACKAGE_BASELINES`,
53    /// because [`apply_env_overrides_from`] clears the baselines and
54    /// [`Self::apply`] cannot get them back.
55    #[must_use]
56    pub(crate) fn env_for_steps(&self, env: &EnvSnapshot) -> EnvSnapshot {
57        env.clone().retain(|var| match var {
58            EnvVar::MaxFileSize => self.max_file_size_mb.is_none(),
59            EnvVar::CacheDir => self.cache_dir.is_none(),
60            EnvVar::PackageBaselines => self.package_baselines.is_none(),
61            _ => true,
62        })
63    }
64
65    /// Write the given settings on a config that the steps resolved.
66    pub fn apply(&self, config: &mut ResolvedConfig) {
67        if let Some(mb) = self.max_file_size_mb {
68            config.max_file_size_bytes = fallow_config::resolve_max_file_size_bytes(Some(mb));
69        }
70        if let Some(dir) = &self.cache_dir {
71            config.override_cache_dir(dir.clone());
72        }
73        // A given `true` wins over each workspace setting, as the
74        // `--include-entry-exports` flag does.
75        match self.include_entry_exports {
76            Some(true) => config.force_include_entry_exports(),
77            Some(false) => config.include_entry_exports = false,
78            None => {}
79        }
80        if self.package_baselines == Some(false) {
81            config.workspace_changed_since.clear();
82        }
83    }
84}
85
86/// The workspace metadata: the workspaces, their diagnostics and the wall time
87/// of the discovery in milliseconds.
88type WorkspaceMetadata = (Vec<WorkspaceInfo>, Vec<WorkspaceDiagnostic>, f64);
89
90/// Set the `production` setting of `config` to `on` for every analysis. A
91/// config from a file keeps its production `ignore` globs. A config without a
92/// file gets the bool form.
93pub(crate) fn flatten_production(config: &mut FallowConfig, from_file: bool, on: bool) {
94    config.production = if from_file {
95        config.production.for_run(on)
96    } else {
97        on.into()
98    };
99}
100
101/// Put a cache directory outside the root in a subdirectory of the root, as
102/// [`ResolvedConfig::scope_shared_cache_dir_to_root`] does. Returns whether
103/// the directory changed.
104pub(crate) fn scope_cache_dir_to_root(config: &mut ResolvedConfig) -> bool {
105    let shared = config.cache_dir.clone();
106    config.scope_shared_cache_dir_to_root();
107    config.cache_dir != shared
108}
109
110/// Resolve `config` for `root` and collect its workspace metadata. A
111/// workspace discovery error is an error.
112pub(crate) fn mode_entry(
113    root: &Path,
114    config: FallowConfig,
115    options: ResolveOptions,
116    env: &EnvSnapshot,
117) -> EngineResult<ModeEntry> {
118    let (inputs, inputs_before_resolve, config) = resolve_with_inputs(root, config, options, env);
119    let (workspaces, workspace_diagnostics, workspace_discovery_ms) =
120        collect_workspace_metadata(&config)?;
121    Ok(ModeEntry {
122        config,
123        inputs,
124        inputs_before_resolve,
125        workspaces,
126        workspace_diagnostics,
127        workspace_discovery_ms,
128    })
129}
130
131/// [`mode_entry`], with no workspaces when the workspace discovery fails.
132pub(crate) fn mode_entry_lossy(
133    root: &Path,
134    config: FallowConfig,
135    options: ResolveOptions,
136    env: &EnvSnapshot,
137) -> ModeEntry {
138    let (inputs, inputs_before_resolve, config) = resolve_with_inputs(root, config, options, env);
139    let (workspaces, workspace_diagnostics, workspace_discovery_ms) =
140        collect_workspace_metadata(&config).unwrap_or_default();
141    ModeEntry {
142        config,
143        inputs,
144        inputs_before_resolve,
145        workspaces,
146        workspace_diagnostics,
147        workspace_discovery_ms,
148    }
149}
150
151fn resolve_with_inputs(
152    root: &Path,
153    config: FallowConfig,
154    options: ResolveOptions,
155    env: &EnvSnapshot,
156) -> (ConfigInputs, ConfigInputsSnapshot, ResolvedConfig) {
157    let inputs = ConfigInputs::new(root, &config);
158    let inputs_before_resolve = inputs.snapshot();
159    let resolved = resolve_with_env_from(config, root, options, env);
160    (inputs, inputs_before_resolve, resolved)
161}
162
163/// Resolve the config for `root`, then apply the environment variables that
164/// `env` gives.
165pub(crate) fn resolve_with_env_from(
166    config: FallowConfig,
167    root: &Path,
168    options: ResolveOptions,
169    env: &EnvSnapshot,
170) -> ResolvedConfig {
171    let mut resolved = config.resolve(
172        root.to_path_buf(),
173        options.output,
174        options.threads,
175        options.no_cache,
176        options.quiet,
177        None,
178    );
179    apply_env_overrides_from(&mut resolved, env);
180    resolved
181}
182
183/// The `FALLOW_MAX_FILE_SIZE` value in megabytes, when it is a valid number.
184pub(crate) fn max_file_size_env(env: &EnvSnapshot) -> Option<u32> {
185    env.get(EnvVar::MaxFileSize)
186        .and_then(|raw| raw.to_str().and_then(|raw| raw.trim().parse::<u32>().ok()))
187}
188
189/// Apply the environment variables that every host honors. The CLI, the LSP,
190/// the MCP server and the Node bindings all load config through these steps,
191/// so a variable applied here has the same meaning on each surface.
192pub(crate) fn apply_env_overrides_from(config: &mut ResolvedConfig, env: &EnvSnapshot) {
193    if let Some(max_file_size_mb) = max_file_size_env(env) {
194        config.max_file_size_bytes =
195            fallow_config::resolve_max_file_size_bytes(Some(max_file_size_mb));
196    }
197    if let Some(dir) = env
198        .get(EnvVar::CacheDir)
199        .map(std::ffi::OsStr::to_os_string)
200        .and_then(fallow_config::cache_dir_from_env_value)
201    {
202        config.override_cache_dir(dir);
203    }
204    if let Some(mb) = env
205        .get(EnvVar::CacheMaxSize)
206        .and_then(fallow_config::cache_max_size_from_env_value)
207    {
208        config.cache_max_size_mb = Some(mb);
209    }
210    config.apply_package_baselines_env(env.get(EnvVar::PackageBaselines));
211}
212
213/// Discover the workspaces of a resolved config.
214///
215/// # Errors
216///
217/// Returns an error when the root manifest cannot be parsed.
218pub(crate) fn collect_workspace_metadata(
219    config: &ResolvedConfig,
220) -> EngineResult<WorkspaceMetadata> {
221    let start = std::time::Instant::now();
222    let (workspaces, diagnostics) =
223        fallow_config::discover_workspaces_with_diagnostics_and_patterns(
224            &config.root,
225            &config.ignore_patterns,
226            &config.workspace_patterns,
227        )
228        .map_err(|err| EngineError::new(err.to_string()))?;
229    let diagnostics = with_undeclared_workspace_diagnostics(config, &workspaces, diagnostics);
230    let elapsed_ms = start.elapsed().as_secs_f64() * 1000.0;
231    Ok((workspaces, diagnostics, elapsed_ms))
232}
233
234fn with_undeclared_workspace_diagnostics(
235    config: &ResolvedConfig,
236    workspaces: &[WorkspaceInfo],
237    mut diagnostics: Vec<WorkspaceDiagnostic>,
238) -> Vec<WorkspaceDiagnostic> {
239    let mut existing: FxHashSet<PathBuf> = diagnostics
240        .iter()
241        .map(|diagnostic| {
242            dunce::canonicalize(&diagnostic.path).unwrap_or_else(|_| diagnostic.path.clone())
243        })
244        .collect();
245    for diagnostic in fallow_config::find_undeclared_workspaces_with_ignores(
246        &config.root,
247        workspaces,
248        &config.ignore_patterns,
249    ) {
250        let canonical =
251            dunce::canonicalize(&diagnostic.path).unwrap_or_else(|_| diagnostic.path.clone());
252        if existing.insert(canonical) {
253            diagnostics.push(diagnostic);
254        }
255    }
256    diagnostics
257}
258
259/// Validate the config of a run of `command`.
260///
261/// - `plugin-check` reports each external plugin, also a plugin that fails
262///   validation, so it validates only the boundaries and the rule packs.
263/// - A coverage upload reads the project as the config file gives it, so it
264///   validates nothing.
265/// - Each other command validates the external plugins, the boundaries and
266///   the rule packs.
267pub(crate) fn validate_command_config(
268    command: CommandKind,
269    root: &Path,
270    config: &FallowConfig,
271) -> EngineResult<()> {
272    match command {
273        CommandKind::PluginCheck => validate_boundaries_and_rule_packs(root, config),
274        CommandKind::CoverageUpload => Ok(()),
275        _ => validate_config(root, config),
276    }
277}
278
279/// Validate the external plugins, the boundaries and the rule packs.
280pub(crate) fn validate_config(root: &Path, config: &FallowConfig) -> EngineResult<()> {
281    fallow_config::discover_and_validate_external_plugins(root, &config.plugins)
282        .map_err(|errors| joined_config_errors("invalid external plugin definition", &errors))?;
283    validate_boundaries_and_rule_packs(root, config)
284}
285
286/// Validate the boundaries and the rule packs.
287pub(crate) fn validate_boundaries_and_rule_packs(
288    root: &Path,
289    config: &FallowConfig,
290) -> EngineResult<()> {
291    config
292        .validate_resolved_boundaries(root)
293        .map_err(|errors| joined_config_errors("invalid boundary configuration", &errors))?;
294    let packs = fallow_config::load_rule_packs(root, &config.rule_packs)
295        .map_err(|errors| joined_config_errors("invalid rule pack", &errors))?;
296    let zone_errors = fallow_config::validate_rule_pack_zones(
297        root,
298        &config.boundaries,
299        &config.rule_packs,
300        &packs,
301    );
302    if !zone_errors.is_empty() {
303        return Err(joined_config_errors("invalid rule pack", &zone_errors));
304    }
305    Ok(())
306}
307
308fn joined_config_errors(label: &str, errors: &[impl ToString]) -> EngineError {
309    let joined = errors
310        .iter()
311        .map(ToString::to_string)
312        .collect::<Vec<_>>()
313        .join("\n  - ");
314    EngineError::new(format!("{label}:\n  - {joined}"))
315}