Skip to main content

stern4rust/
runner.rs

1// Copyright 2025 Umberto Gotti <umberto.gotti@umbertogotti.dev>
2// Licensed under the MIT License
3// SPDX-License-Identifier: MIT
4
5use crate::adoption::baseline::Baseline;
6use crate::adoption::baseline_outcome::BaselineOutcome;
7use crate::adoption::exclusion_outcome::ExclusionOutcome;
8use crate::adoption::exclusion_set::ExclusionSet;
9use crate::reporting::json_printer::JsonPrinter;
10use crate::reporting::offence::Offence;
11use crate::reporting::offence_threshold::OffenceThreshold;
12use crate::reporting::output_format::OutputFormat;
13use crate::reporting::package_roster::PackageRoster;
14use crate::reporting::report_printer::ReportPrinter;
15use crate::reporting::run_outcome::RunOutcome;
16use crate::reporting::scan_totals::ScanTotals;
17use crate::rule_registry::RuleRegistry;
18use crate::rules::source::header_rule::HeaderRule;
19use crate::settings::args::Args;
20use crate::settings::config::Config;
21use crate::settings::config_file::ConfigFile;
22use crate::settings::header_source::HeaderSource;
23use crate::settings::manifest_resolver::ManifestResolver;
24use crate::settings::package_config::PackageConfig;
25use crate::settings::package_sections::PackageSections;
26use crate::settings::rule_selection::RuleSelection;
27use crate::settings::scanned_package::ScannedPackage;
28use crate::source_file::SourceFile;
29use crate::source_reader::SourceReader;
30use crate::source_walker::SourceWalker;
31use crate::test_file_rewriter::TestFileRewriter;
32use anyhow::Context;
33use anyhow::Result;
34use std::collections::HashSet;
35use std::fs::write as write_file;
36use std::path::Path;
37use std::path::PathBuf;
38
39// Exit codes are the whole contract with a gate script:
40//
41//   0  every rule satisfied
42//   1  could not run -- returned as an Err and turned into 1 by main
43//   2  at least one rule broken
44//
45// 2 is kept distinct from 1 on purpose. A script that treats every non-zero code
46// alike cannot tell "your code has a problem" from "I could not read your code",
47// and the second one silently passing is how a gate stops meaning anything.
48//
49// The line between the two is what can still be enumerated. A bad manifest or an
50// unknown package is a 1: without it there is no list of files to judge. A single
51// unreadable file is a 2, reported against readable-source like any other
52// finding -- it is a fact about the tree, and aborting on it would hide every
53// offence already found in every other file.
54pub struct Runner;
55
56impl Runner {
57    pub fn run(args: Args) -> Result<RunOutcome> {
58        let sections = PackageSections::load(&Self::manifest_directory(&args.manifest_path))?;
59        let config = Self::config_from(&args, None)?;
60        Self::validate_selection(&config)?;
61        let config = Config {
62            workspace_dependencies: ManifestResolver::workspace_dependencies(&config),
63            ..config
64        };
65        let packages = ManifestResolver::packages(&config)?;
66        sections.validate(&packages)?;
67        // What the report answers for. A rule that stood down for any package
68        // did not apply to this run, so the licence stated here is the one every
69        // scanned package agrees on and nothing otherwise. Checking is per
70        // package; only the summary is aggregate, and it understates rather than
71        // overstates -- see
72        // [ADR-PerPackageConfiguration](../docs/ADRs/ADR-PerPackageConfiguration.md),
73        // where the per-package report is the piece still to come.
74        let config = Config {
75            manifest_license: ScannedPackage::agreed_license(&packages),
76            selection: config.selection.also_skipping(&sections.skipped_anywhere()),
77            ..config
78        };
79        let registry = RuleRegistry::from_config(&config);
80        if registry.is_empty() {
81            return Err(anyhow::anyhow!(
82                "no rules are configured, so nothing would be checked -- pass --header-file to \
83                 enable the header rule"
84            ));
85        }
86
87        let mut offences = Vec::new();
88        let mut files_scanned = 0usize;
89        let mut excluded = Vec::new();
90        let mut fixed = 0usize;
91        let mut rosters: Vec<PackageRoster> = Vec::new();
92
93        for package in &packages {
94            // Everything the manifest decides is decided here, by the package
95            // about to be walked, rather than once for the run.
96            let package_config = Config {
97                manifest_license: package.license.clone(),
98                workspace_dependencies: config.workspace_dependencies.clone(),
99                ..Self::config_from(&args, sections.of(&package.name))?
100            };
101            let registry = RuleRegistry::from_config(&package_config);
102            rosters.push(PackageRoster::new(
103                &package.name,
104                Self::owned(&registry.names()),
105                Self::owned(&RuleRegistry::skipped_names(&package_config.selection)),
106                registry
107                    .unconfigured(&package_config)
108                    .into_iter()
109                    .map(|(name, requirement)| (name.to_string(), requirement.to_string()))
110                    .collect(),
111            ));
112            let exclusions = ExclusionSet::new(&package_config.excludes)?;
113            let root = &package.root;
114            // Read the whole package before judging it. Rules whose subject is
115            // the tree -- "there is exactly one all_tests.rs" -- cannot be
116            // answered a file at a time, and the file that carries the offence
117            // is often the one that does not exist.
118            let outcome = exclusions.apply(SourceWalker::walk(root), root);
119            let mut files: Vec<SourceFile> = Vec::new();
120            for path in outcome.kept {
121                files_scanned += 1;
122                match SourceReader::read(root, &path) {
123                    Ok(file) => files.push(file),
124                    Err(offence) => offences.push(*offence),
125                }
126            }
127            if config.fix {
128                let (rewritten, count) = Self::repair(root, files)?;
129                files = rewritten;
130                fixed += count;
131            }
132            for file in &files {
133                offences.extend(registry.check(file));
134            }
135            offences.extend(registry.check_workspace(&files));
136            excluded.push(outcome.excluded);
137        }
138
139        // Rules run in registration order and the tree-wide pass runs last, so
140        // without this the report jumps between files. Sorting is the report's
141        // business rather than any rule's -- a rule states facts, and their
142        // order on the page is not one of them.
143        // The workspace question is asked once per package root, so a rule whose
144        // subject is the *workspace* rather than the package -- the manifest
145        // rules -- states the same finding once per member. The same sentence
146        // about the same line of the same file is one finding, not several.
147        //
148        // By content rather than by `dedup`, because two findings about one
149        // manifest interleave once sorted and consecutive-only removal misses
150        // every copy after the first pair.
151        let mut seen = HashSet::new();
152        offences.retain(|offence| seen.insert(offence.clone()));
153        offences.sort_by(|left, right| left.sort_key().cmp(&right.sort_key()));
154
155        if config.write_baseline {
156            return Self::record(&config, offences);
157        }
158        let baselined = Self::baselined(&config, offences)?;
159        let offences = baselined.kept;
160        Self::report(
161            &config,
162            &registry,
163            ScanTotals::new(files_scanned, fixed),
164            &Self::merged(excluded),
165            &BaselineOutcome::new(Vec::new(), baselined.suppressed, baselined.stale),
166            &rosters,
167            &offences,
168        );
169        Ok(RunOutcome::of(offences.len()))
170    }
171
172    // A misspelled rule name is an error rather than a switch that quietly
173    // matches nothing, and asking for the header rule without a header file is
174    // an error rather than an empty run. Both would otherwise look exactly like
175    // a run that worked.
176    fn validate_selection(config: &Config) -> Result<()> {
177        let known = RuleRegistry::known_names();
178        let unknown = config.selection.unknown_in(&known);
179        if !unknown.is_empty() {
180            return Err(anyhow::anyhow!(
181                "unknown rule name(s): {} -- the rules are: {}",
182                unknown.join(", "),
183                known.join(", ")
184            ));
185        }
186        if config.selection.selects_explicitly(HeaderRule::NAME)
187            && config.expected_header.is_empty()
188        {
189            return Err(anyhow::anyhow!(
190                "--rule {} needs --header-file, otherwise the run would apply no rules at all",
191                HeaderRule::NAME
192            ));
193        }
194        Ok(())
195    }
196
197    // The command line wins over the file, every time and per setting. A
198    // repository states its defaults in stern4rust.toml; a person overrides one
199    // of them for one run without having to restate the rest.
200    //
201    // "Wins" is replacement rather than merging for the list settings. Merging
202    // would make `--rule header` mean "header plus whatever the file already
203    // selected", which is the opposite of what naming one rule means everywhere
204    // else in this tool.
205    fn config_from(args: &Args, section: Option<&PackageConfig>) -> Result<Config> {
206        let directory = Self::manifest_directory(&args.manifest_path);
207        let file = ConfigFile::load(&directory)?;
208        let found = file.as_ref();
209        let header_file = args
210            .header_file
211            .clone()
212            .or_else(|| section.and_then(|s| s.header_file_from(&directory)))
213            .or_else(|| found.and_then(|file| file.header_file_from(&directory)));
214        let expected_header = match &header_file {
215            Some(path) => HeaderSource::read(path)?,
216            None => Vec::new(),
217        };
218        let threshold = args
219            .offence_threshold
220            .or_else(|| found.and_then(|file| file.offence_threshold))
221            .unwrap_or(OffenceThreshold::DEFAULT);
222        Ok(Config {
223            // Filled in by `run` once the manifest has been read; the command
224            // line has nothing to say about it.
225            manifest_license: None,
226            workspace_dependencies: None,
227            // Discovered beside the manifest when nobody named one, the same
228            // way stern4rust.toml is. Implicit suppression would be
229            // unacceptable if it were invisible; every report that used a
230            // baseline names it and states how many offences it hid, so a
231            // reader can always see that one is in force.
232            baseline: args
233                .baseline
234                .clone()
235                .or_else(|| found.and_then(|file| file.baseline_from(&directory)))
236                .or_else(|| Self::discovered_baseline(&directory, args.write_baseline)),
237            write_baseline: args.write_baseline,
238            fix: args.fix,
239            config_file: found.map(|_| directory.join(ConfigFile::NAME)),
240            manifest_path: args.manifest_path.clone(),
241            max_files_per_directory: section
242                .and_then(|s| s.max_files_per_directory)
243                .or_else(|| found.and_then(|file| file.max_files_per_directory)),
244            max_subfolders_per_directory: section
245                .and_then(|s| s.max_subfolders_per_directory)
246                .or_else(|| found.and_then(|file| file.max_subfolders_per_directory)),
247            packages: args.packages.clone(),
248            excludes: Self::preferred(
249                args.excludes.clone(),
250                Self::section_or_root(section.map(|s| &s.exclude), found.map(|file| &file.exclude)),
251            ),
252            expected_header,
253            format: args.format,
254            offence_threshold: OffenceThreshold::new(threshold),
255            selection: RuleSelection::new(
256                Self::preferred(
257                    args.rules.clone(),
258                    Self::section_or_root(section.map(|s| &s.rules), found.map(|file| &file.rules)),
259                ),
260                Self::preferred(
261                    args.skipped_rules.clone(),
262                    Self::section_or_root(section.map(|s| &s.skip), found.map(|file| &file.skip)),
263                ),
264            ),
265        })
266    }
267
268    // When writing, the default path is the destination whether or not it
269    // exists yet. When reading, only an existing file counts -- otherwise every
270    // run without a baseline would fail trying to load one.
271    fn discovered_baseline(directory: &Path, writing: bool) -> Option<PathBuf> {
272        let path = directory.join(Self::BASELINE_NAME);
273        (writing || path.exists()).then_some(path)
274    }
275
276    // A section states its whole list rather than adding to the root's, which is
277    // the argument already made for the command line against the file, one level
278    // down: a reader who wants to know what a package skips reads one list.
279    fn section_or_root<'a>(
280        section: Option<&'a Vec<String>>,
281        root: Option<&'a Vec<String>>,
282    ) -> Option<&'a Vec<String>> {
283        match section {
284            Some(values) if !values.is_empty() => Some(values),
285            _ => root,
286        }
287    }
288
289    fn preferred(from_args: Vec<String>, from_file: Option<&Vec<String>>) -> Vec<String> {
290        if !from_args.is_empty() {
291            return from_args;
292        }
293        from_file.cloned().unwrap_or_default()
294    }
295
296    // The config lives beside the manifest it configures, so a workspace and a
297    // package in it can hold different ones.
298    fn manifest_directory(manifest_path: &Option<PathBuf>) -> PathBuf {
299        manifest_path
300            .as_ref()
301            .and_then(|path| path.parent())
302            .map(Path::to_path_buf)
303            .unwrap_or_else(|| PathBuf::from("."))
304    }
305
306    pub const BASELINE_NAME: &'static str = "stern4rust-baseline.json";
307
308    // Rewrites what can be rewritten and hands back the files as they now are,
309    // so the checks that follow judge the repaired tree. Whatever is still
310    // wrong is reported exactly as it would have been without --fix -- a fixer
311    // that quietly swallowed what it could not fix would be worse than no fixer
312    // at all.
313    fn repair(root: &Path, files: Vec<SourceFile>) -> Result<(Vec<SourceFile>, usize)> {
314        let mut repaired = Vec::with_capacity(files.len());
315        let mut count = 0;
316        for file in files {
317            match TestFileRewriter::rewrite(&file) {
318                Some(contents) => {
319                    let path = root.join(file.relative_path());
320                    write_file(&path, &contents)
321                        .with_context(|| format!("{} could not be rewritten", path.display()))?;
322                    repaired.push(SourceFile::new(file.relative_path(), &contents));
323                    count += 1;
324                }
325                None => repaired.push(file),
326            }
327        }
328        Ok((repaired, count))
329    }
330
331    // Recording is not judging. The run exits clean because nothing was
332    // assessed -- the offences were written down, which is what was asked for.
333    fn record(config: &Config, offences: Vec<Offence>) -> Result<RunOutcome> {
334        let path = config
335            .baseline
336            .as_ref()
337            .ok_or_else(|| anyhow::anyhow!("--write-baseline needs a path to write to"))?;
338        let baseline = Baseline::of(&offences);
339        baseline.save(path)?;
340        println!(
341            "stern4rust wrote {} offence(s) to {}",
342            baseline.len(),
343            path.display()
344        );
345        Ok(RunOutcome::Clean)
346    }
347
348    // A baseline that was asked for and is not there is an error rather than an
349    // empty one. A gate whose baseline path has a typo would otherwise report
350    // every existing offence and look like a regression.
351    fn baselined(config: &Config, offences: Vec<Offence>) -> Result<BaselineOutcome> {
352        let Some(path) = &config.baseline else {
353            return Ok(BaselineOutcome::new(offences, 0, 0));
354        };
355        Ok(Baseline::load(path)?.apply(offences))
356    }
357
358    // One package's exclusions say nothing on their own: a pattern matching
359    // nothing in package A and forty files in package B has done its job, and
360    // reporting it as dead for A would be a wrong answer rather than a missing
361    // one. So the counts are summed across roots before anybody looks at them.
362    fn merged(per_root: Vec<Vec<(String, usize)>>) -> ExclusionOutcome {
363        let mut totals: Vec<(String, usize)> = Vec::new();
364        for counts in per_root {
365            for (pattern, count) in counts {
366                match totals.iter_mut().find(|(known, _)| *known == pattern) {
367                    Some(entry) => entry.1 += count,
368                    None => totals.push((pattern, count)),
369                }
370            }
371        }
372        ExclusionOutcome::new(Vec::new(), totals)
373    }
374
375    fn report(
376        config: &Config,
377        registry: &RuleRegistry,
378        totals: ScanTotals,
379        excluded: &ExclusionOutcome,
380        baselined: &BaselineOutcome,
381        rosters: &[PackageRoster],
382        offences: &[Offence],
383    ) {
384        let threshold = config.offence_threshold;
385        let applied = Self::owned(&registry.names());
386        let skipped = Self::owned(&RuleRegistry::skipped_names(&config.selection));
387        let unconfigured: Vec<(String, String)> = registry
388            .unconfigured(config)
389            .into_iter()
390            .map(|(name, requirement)| (name.to_string(), requirement.to_string()))
391            .collect();
392        let unconfigured_names = Self::owned(&registry.unconfigured_names(config));
393        match config.format {
394            OutputFormat::Text => ReportPrinter::new(totals.files_scanned)
395                .with_threshold(threshold)
396                .with_rules(applied.clone(), skipped.clone(), unconfigured.clone())
397                .with_package_rosters(rosters.to_vec())
398                .with_exclusions(excluded.excluded.clone())
399                .with_config_file(Self::shown(config))
400                .with_baseline(
401                    Self::baseline_shown(config),
402                    baselined.suppressed,
403                    baselined.stale,
404                )
405                .with_fixed(totals.fixed)
406                .print(offences),
407            OutputFormat::Json => JsonPrinter::new(totals.files_scanned)
408                .with_threshold(threshold)
409                .with_rules(applied, skipped, unconfigured_names)
410                .with_exclusions(excluded.excluded.clone())
411                .with_config_file(Self::shown(config))
412                .with_baseline(
413                    Self::baseline_shown(config),
414                    baselined.suppressed,
415                    baselined.stale,
416                )
417                .with_fixed(totals.fixed)
418                .print(offences),
419        }
420    }
421
422    fn baseline_shown(config: &Config) -> Option<String> {
423        config
424            .baseline
425            .as_ref()
426            .map(|path| path.to_string_lossy().replace('\\', "/"))
427    }
428
429    fn shown(config: &Config) -> Option<String> {
430        config
431            .config_file
432            .as_ref()
433            .map(|path| path.to_string_lossy().replace('\\', "/"))
434    }
435
436    fn owned(names: &[&str]) -> Vec<String> {
437        names.iter().map(|name| (*name).to_string()).collect()
438    }
439}