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