1use 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
39pub 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 let config = Config {
75 manifest_license: ScannedPackage::agreed_license(&packages),
76 selection: config.selection.also_skipping(§ions.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 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(®istry.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 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 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 ®istry,
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 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 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 manifest_license: None,
226 workspace_dependencies: None,
227 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 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 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 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 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 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 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 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(®istry.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(®istry.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}