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 let workspace = ManifestResolver::workspace_package_names(&config)?;
67 sections.validate(&workspace.iter().map(String::as_str).collect::<Vec<_>>())?;
68 let config = Config {
76 manifest_license: ScannedPackage::agreed_license(&packages),
77 selection: config.selection.also_skipping(§ions.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 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(®istry.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 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 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 ®istry,
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 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 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 manifest_license: None,
227 workspace_dependencies: None,
228 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 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 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 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 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 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 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 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(®istry.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(®istry.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}