1use std::borrow::Cow;
4use std::collections::{BTreeMap, BTreeSet};
5use std::path::{Path, PathBuf};
6use std::sync::Arc;
7
8use clap::ColorChoice;
9use rayon::prelude::*;
10use serde_json::{Map, Value};
11use skif::{
12 CachedFs, Config, ConfigOverrides, DiscoverOptions, FileSystem, FixPlan, IdleReason, IgnoreEntry, Linter, OsFs,
13 Prefer, Report, Selector, Target, Workspace, join_lexical, relative_tsconfig,
14};
15use skif_core::timing;
16use skif_report::escape_controls;
17
18use crate::args::{Format, LintArgs, Select};
19use crate::cache::{CacheEnv, CacheHost, DiskHost};
20use crate::env::{Env, github_workspace};
21use crate::error::{CliError, Kind};
22use crate::explain;
23use crate::filter::{self, Filter};
24use crate::fix::{self, FixRun, RootFix};
25use crate::install::{self, InstallStatus};
26use crate::output::{self, Rendering, RootView, emit_error, emit_error_with, stderr_line};
27use crate::roots::{self, Linters, Resolved, RootError, RootRun};
28use crate::trace::{self, Trace};
29use crate::write::write_plan;
30
31const CLEAN: u8 = 0;
32const PROBLEMS: u8 = 1;
33const COULD_NOT_RUN: u8 = 2;
34
35#[derive(Debug, Clone, Copy, PartialEq, Eq)]
37pub enum Teardown {
38 Free,
40 Leak,
42}
43
44pub fn run(args: &LintArgs, env: Env, teardown: Teardown) -> u8 {
47 let host = DiskHost::new(args.cache_flags(), CacheEnv::detect(env.ci), args.debug);
48 run_with_cache(args, env, teardown, Some(&host))
49}
50
51pub fn run_with_cache(args: &LintArgs, env: Env, teardown: Teardown, modules: Option<&dyn CacheHost>) -> u8 {
54 let trace = Trace::start(args);
55 let result = match &args.trace_dependency {
56 Some(name) => explain::trace_dependency(args, name).map(|()| CLEAN),
57 None => execute(args, env, teardown, modules, None),
58 };
59 let complete = completed(&result);
60 let code = match result {
61 Ok(code) => code,
62 Err(error) => run_failed(args, &error),
63 };
64 if let Some(modules) = modules {
65 timing::phase("cache store", || modules.finish(complete));
66 }
67 trace.finish();
68 code
69}
70
71fn completed(result: &Result<u8, CliError>) -> bool {
74 matches!(result, Ok(code) if *code != COULD_NOT_RUN)
75}
76
77pub fn run_failed(args: &LintArgs, error: &CliError) -> u8 {
79 emit_error(error, args.format());
80 COULD_NOT_RUN
81}
82
83fn rule_given_as_path(path: &Path) -> Result<(), CliError> {
87 if path.exists() {
88 return Ok(());
89 }
90 let Some(name) = path.to_str() else {
91 return Ok(());
92 };
93 let id = match skif_migrate::sherif_rule_id(name) {
94 Some(id) => id,
95 None => match Linter::new(&Config::default())?.rules().find(|meta| meta.id == name) {
96 Some(meta) => meta.id,
97 None => return Ok(()),
98 },
99 };
100 Err(CliError::new(
101 Kind::Usage,
102 format!(
103 "`{name}` is a rule, not a path: `-r` is `--recursive` in skif, not sherif's `--ignore-rule`; \
104 use `--ignore-rule {id}` to turn the rule off, or `--rule {id}=<level>` to set its level"
105 ),
106 ))
107}
108
109fn annotations(args: &LintArgs, env: Env) -> bool {
112 args.format.is_empty() && env.github_actions
113}
114
115pub fn canonical(path: &Path) -> Result<PathBuf, CliError> {
117 let resolved = std::fs::canonicalize(path).map_err(|error| CliError::io("cannot resolve", path, &error))?;
118 Ok(simplified(resolved))
119}
120
121pub(crate) fn absolute_file(file: &Path) -> PathBuf {
124 simplified(std::path::absolute(file).unwrap_or_else(|_| file.to_path_buf()))
125}
126
127#[cfg(windows)]
128pub(crate) fn simplified(path: PathBuf) -> PathBuf {
129 let text = path.to_string_lossy();
130 match text.strip_prefix(r"\\?\") {
131 Some(rest) if rest.as_bytes().get(1) == Some(&b':') => PathBuf::from(rest),
132 _ => path,
133 }
134}
135
136#[cfg(not(windows))]
137pub(crate) const fn simplified(path: PathBuf) -> PathBuf {
138 path
139}
140
141fn repo_root(root: &Path) -> Option<PathBuf> {
144 github_workspace()
145 .map(|workspace| simplified(std::fs::canonicalize(&workspace).unwrap_or(workspace)))
146 .filter(|workspace| root.starts_with(workspace))
147 .or_else(|| {
148 root.ancestors()
149 .find(|dir| dir.join(".git").exists())
150 .map(Path::to_path_buf)
151 })
152}
153
154pub fn overrides(args: &LintArgs) -> ConfigOverrides {
155 ConfigOverrides::default()
156 .with_rules(args.rules.iter().cloned())
157 .with_ignore_rules(args.ignore_rule.clone())
158 .with_ignore_packages(args.ignore_package.clone())
159 .with_ignore_dependencies(args.ignore_dependency.clone())
160 .with_fail_on_warnings(args.fail_on_warnings.then_some(true))
161 .with_production((args.production || args.strict).then_some(true))
162 .with_no_js(args.no_js)
163 .with_config_file(args.config.as_ref().map(|file| absolute_file(file)))
164 .with_no_config(args.no_config)
165}
166
167fn require_reasons(args: &LintArgs, config: &Config) -> Result<(), CliError> {
170 let required_by = if args.require_ignore_reasons {
171 "--require-ignore-reasons"
172 } else if config.lint.require_ignore_reasons {
173 "[lint] require-ignore-reasons"
174 } else {
175 return Ok(());
176 };
177 match config.missing_ignore_reason() {
178 Some(entry) => Err(CliError::new(
179 Kind::Config,
180 format!(
181 "{entry}: no `reason`, which {required_by} requires (the position is in the list merged from every \
182 config file and its `extend-*` keys)"
183 ),
184 )),
185 None => Ok(()),
186 }
187}
188
189pub(crate) fn adjust(args: &LintArgs, config: &mut Config) -> Result<(), CliError> {
191 require_reasons(args, config)?;
193 for (rule, package) in &args.ignore_rule_for_package {
194 config.ignore.push(
195 IgnoreEntry::default()
196 .with_rules([rule.clone()])
197 .with_packages(Selector::new([package.clone()])?),
198 );
199 }
200 crate::instances::apply_filter(&args.filter, config)?;
201 if args.isolate_workspaces {
202 config.js.isolate_workspaces = true;
203 }
204 if args.strict {
205 config.js.strict = true;
206 }
207 if args.no_gitignore {
208 config.js.no_gitignore = true;
209 }
210 if args.use_tsconfig_files {
211 config.js.use_tsconfig_files = true;
212 }
213 if args.include_entry_exports {
214 config.js.include_entry_exports = true;
215 for workspace in config.js.workspaces.values_mut() {
216 if workspace.include_entry_exports.is_some() {
217 workspace.include_entry_exports = Some(true);
218 }
219 }
220 }
221 if let Some(select) = args.select {
222 config.policy.prefer = match select {
223 Select::Highest => Prefer::Highest,
224 Select::Lowest => Prefer::Lowest,
225 };
226 }
227 Ok(())
228}
229
230fn tsconfig_exists(root: &Path, path: &str) -> Option<bool> {
233 relative_tsconfig(path).map(|relative| root.join(relative).is_file())
234}
235
236pub(crate) fn apply_tsconfig(args: &LintArgs, targets: &mut [Target]) -> Result<(), CliError> {
246 if let Some(path) = &args.tsconfig {
247 let mut found = false;
248 let mut searched = Vec::new();
249 for target in targets.iter_mut().filter(|target| target.config.js.enabled) {
250 if tsconfig_exists(&target.root, path) != Some(false) {
251 target.config.js.tsconfig = Some(path.clone());
252 found = true;
253 }
254 searched.push(target.root.display().to_string());
255 }
256 if !found && !searched.is_empty() {
257 return Err(CliError::new(
258 Kind::Config,
259 format!("--tsconfig: `{path}` does not exist in {}", searched.join(", ")),
260 ));
261 }
262 }
263 for target in targets.iter().filter(|target| target.config.js.enabled) {
264 if let Some(path) = &target.config.js.tsconfig
265 && tsconfig_exists(&target.root, path) == Some(false)
266 {
267 return Err(CliError::new(
268 Kind::Config,
269 format!("[js] tsconfig: `{path}` does not exist in {}", target.root.display()),
270 ));
271 }
272 }
273 Ok(())
274}
275
276fn warn_empty_tsconfig_projects(targets: &[Target], fs: &dyn FileSystem) {
279 for target in targets {
280 for config in skif::empty_tsconfig_projects(&target.workspace, &target.config, fs) {
281 stderr_line(&format!(
282 "warning: {}: selects no file of its package (`files`, `include`), so --use-tsconfig-files leaves \
283 that package without project files",
284 escape_controls(&crate::error::slashes(target.root.join(config).display().to_string()))
285 ));
286 }
287 }
288}
289
290fn lint_once(
296 linter: &Linter,
297 previous: &Workspace,
298 (config, config_path, handed, other_root_uses): RootInputs<'_>,
299 fs: &dyn FileSystem,
300) -> Result<(Workspace, Report), CliError> {
301 let mut workspace = Workspace::discover_with_fs(&previous.root, config, fs)?;
302 workspace.set_nested(previous.is_nested());
303 workspace.set_workspace_keys_anchor(previous.workspace_keys_anchor().map(str::to_owned));
304 let ignored: BTreeSet<PathBuf> = previous
305 .package_ids()
306 .filter(|id| previous.is_ignored(*id))
307 .filter_map(|id| previous.package(id))
308 .map(|package| previous.root.join(&package.dir))
309 .collect();
310 workspace.ignore_dirs(&ignored);
311 let report = roots::lint_loaded(linter, &workspace, config_path, handed)?;
312 let report = roots::credit_other_root_uses(report, other_root_uses);
313 Ok((workspace, report))
314}
315
316fn is_manifest_or_catalog(path: &Path) -> bool {
317 matches!(
318 path.file_name().and_then(|name| name.to_str()),
319 Some("package.json" | "pnpm-workspace.yaml")
320 )
321}
322
323fn install_step(args: &LintArgs, changed: &[&Path], workspace: &Workspace) -> InstallStatus {
324 if args.no_install {
325 return InstallStatus::Skipped {
326 reason: "--no-install was given",
327 };
328 }
329 if !changed.iter().any(|path| is_manifest_or_catalog(path)) {
330 return InstallStatus::Skipped {
331 reason: "no manifest or catalog changed",
332 };
333 }
334 match workspace.package_manager {
335 Some(manager) => install::install(manager, &workspace.root, args.format() != Format::Human),
336 None => InstallStatus::Skipped {
337 reason: "no package manager detected",
338 },
339 }
340}
341
342fn color_enabled(args: &LintArgs, env: Env, format: Format, file: Option<&Path>) -> bool {
345 let primary = format == args.format() && (file.is_none() || args.output.is_some());
346 primary
347 && format == Format::Human
348 && match args.color {
349 ColorChoice::Always => true,
350 ColorChoice::Never => false,
351 ColorChoice::Auto => env.stdout_tty && !env.no_color && file.is_none(),
352 }
353}
354
355fn run_exit_code(args: &LintArgs, runs: &[RootRun], aggregate: &Report) -> u8 {
359 if args.no_exit_code {
360 return CLEAN;
361 }
362 if aggregate.summary.errors > args.max_issues.unwrap_or(0) {
363 return PROBLEMS;
364 }
365 let too_many_warnings = match args.max_warnings {
366 Some(max) => aggregate.summary.warnings > max,
367 None => runs
368 .iter()
369 .any(|run| run.config.lint.fail_on_warnings && run.report.summary.warnings > 0),
370 };
371 if too_many_warnings { PROBLEMS } else { CLEAN }
372}
373
374type RootInputs<'a> = (
377 &'a Config,
378 Option<&'a Path>,
379 &'a roots::HandedFiles,
380 &'a roots::OtherRootUses,
381);
382
383enum Fixed {
386 All(Vec<RootRun>, Vec<FixRun>),
387 Stopped(u8),
388}
389
390fn fix_roots(
396 (args, filter): (&LintArgs, &Filter),
397 env: Env,
398 linters: &Linters,
399 runs: Vec<RootRun>,
400 fs: &CachedFs<OsFs>,
401 only: Option<&BTreeSet<String>>,
402) -> Result<Fixed, CliError> {
403 let plans = per_root(fix::prompts(args, env), &runs, |run| {
404 let selection = fix::selection(args, env, &run.report, run.config.policy.prefer, only)?;
405 Ok(skif::apply_fixes(&run.workspace, &run.report, &selection, fs)?)
406 })?;
407 let planned: Vec<(RootRun, FixPlan)> = runs.into_iter().zip(plans).collect();
408 if let Some(code) = write_plans(args, &planned)? {
409 return Ok(Fixed::Stopped(code));
410 }
411 fs.clear();
413 let written: Vec<BTreeSet<PathBuf>> = planned
414 .iter()
415 .map(|(run, plan)| {
416 plan.paths()
417 .map(|path| join_lexical(&run.workspace.root, path))
418 .collect()
419 })
420 .collect();
421 let sources: Vec<&[PathBuf]> = planned.iter().map(|(run, _)| run.config_sources.as_slice()).collect();
422 let again = relinted(&written, &sources);
423 match relint_roots(args, linters, planned, &again, fs) {
424 Fixed::All(mut done, fixes) => {
425 filter.apply_runs(&mut done)?;
426 Ok(Fixed::All(done, fixes))
427 }
428 stopped @ Fixed::Stopped(_) => Ok(stopped),
429 }
430}
431
432fn write_plans(args: &LintArgs, planned: &[(RootRun, FixPlan)]) -> Result<Option<u8>, CliError> {
435 for (index, (run, plan)) in planned.iter().enumerate() {
436 let Err(error) = write_plan(plan, &run.workspace.root) else {
437 continue;
438 };
439 let earlier = &planned[..index];
440 if earlier.iter().all(|(_, plan)| plan.is_empty()) {
441 return Err(error);
442 }
443 let prefixes: Vec<&Path> = earlier.iter().map(|(run, _)| run.prefix.as_path()).collect();
444 let fixes: Vec<FixRun> = earlier.iter().map(|(_, plan)| FixRun::stopped(plan.clone())).collect();
445 return Ok(Some(fix_incomplete(
446 args,
447 "fixes were written to earlier roots, but fixing a later root failed",
448 &error,
449 &roots_fix(&prefixes, &fixes),
450 )));
451 }
452 Ok(None)
453}
454
455fn relinted(written: &[BTreeSet<PathBuf>], sources: &[&[PathBuf]]) -> Vec<bool> {
459 let all: BTreeSet<&PathBuf> = written.iter().flatten().collect();
460 written
461 .iter()
462 .zip(sources)
463 .map(|(files, sources)| !files.is_empty() || sources.iter().any(|source| all.contains(&source)))
464 .collect()
465}
466
467fn per_root<T: Send>(
471 in_order: bool,
472 runs: &[RootRun],
473 work: impl Fn(&RootRun) -> Result<T, CliError> + Sync + Send,
474) -> Result<Vec<T>, CliError> {
475 if in_order {
476 return runs.iter().map(work).collect();
477 }
478 let done: Vec<Result<T, CliError>> = runs.par_iter().map(work).collect();
479 done.into_iter().collect()
480}
481
482type Relinted = Result<(Workspace, Report), CliError>;
484
485fn may_install(args: &LintArgs, planned: &[(RootRun, FixPlan)]) -> bool {
488 !args.no_install && planned.iter().any(|(_, plan)| plan.paths().any(is_manifest_or_catalog))
489}
490
491fn relint(linter: &Linter, run: &RootRun, fs: &CachedFs<OsFs>) -> Relinted {
493 let inputs = (
494 &run.config,
495 run.config_path.as_deref(),
496 &run.handed,
497 &run.other_root_uses,
498 );
499 lint_once(linter, &run.workspace, inputs, fs)
500}
501
502fn relint_roots(
506 args: &LintArgs,
507 linters: &Linters,
508 planned: Vec<(RootRun, FixPlan)>,
509 again: &[bool],
510 fs: &CachedFs<OsFs>,
511) -> Fixed {
512 let mut early: Vec<Option<Relinted>> = if may_install(args, &planned) {
513 Vec::new()
514 } else {
515 planned
516 .par_iter()
517 .zip(again.par_iter())
518 .map(|((run, _), &again)| again.then(|| relint(linters.get(run.linter), run, fs)))
519 .collect()
520 };
521 let mut done: Vec<RootRun> = Vec::with_capacity(planned.len());
522 let mut fixes: Vec<FixRun> = Vec::with_capacity(planned.len());
523 let mut planned = planned.into_iter().zip(again.iter().copied()).enumerate();
524 while let Some((index, ((run, plan), again))) = planned.next() {
525 let prefix = run.prefix.clone();
526 let linted = early.get_mut(index).and_then(Option::take);
527 let (fix_run, outcome) = relint_root(args, linters.get(run.linter), (run, plan), (again, linted), fs);
528 fixes.push(fix_run);
529 match outcome {
530 Ok(run) => done.push(run),
531 Err(error) => {
532 let (rest, plans): (Vec<PathBuf>, Vec<FixPlan>) =
533 planned.map(|(_, ((run, plan), _))| (run.prefix, plan)).unzip();
534 fixes.extend(plans.into_iter().map(FixRun::relint_failed));
535 let prefixes: Vec<&Path> = done
536 .iter()
537 .map(|run| run.prefix.as_path())
538 .chain(std::iter::once(prefix.as_path()))
539 .chain(rest.iter().map(PathBuf::as_path))
540 .collect();
541 return Fixed::Stopped(fix_incomplete(
542 args,
543 "fixes were written, but linting again failed",
544 &error,
545 &roots_fix(&prefixes, &fixes),
546 ));
547 }
548 }
549 }
550 Fixed::All(done, fixes)
551}
552
553fn relint_root(
556 args: &LintArgs,
557 linter: &Linter,
558 (run, plan): (RootRun, FixPlan),
559 (again, linted): (bool, Option<Relinted>),
560 fs: &CachedFs<OsFs>,
561) -> (FixRun, Result<RootRun, CliError>) {
562 if !again {
563 let install = installed(install_step(args, &[], &run.workspace), fs);
564 let fix_run = FixRun {
565 plan,
566 install,
567 preview: None,
568 };
569 return (fix_run, Ok(run));
570 }
571 match linted.unwrap_or_else(|| relint(linter, &run, fs)) {
572 Ok((workspace, report)) => {
573 let changed: Vec<&Path> = plan.paths().collect();
574 let install = installed(install_step(args, &changed, &workspace), fs);
575 let fix_run = FixRun {
576 plan,
577 install,
578 preview: None,
579 };
580 (
581 fix_run,
582 Ok(RootRun {
583 workspace,
584 report,
585 ..run
586 }),
587 )
588 }
589 Err(error) => (FixRun::relint_failed(plan), Err(error)),
590 }
591}
592
593fn installed(status: InstallStatus, fs: &CachedFs<OsFs>) -> InstallStatus {
596 if !matches!(status, InstallStatus::Skipped { .. }) {
597 fs.clear();
598 }
599 status
600}
601
602fn plan_roots(
604 args: &LintArgs,
605 env: Env,
606 runs: &[RootRun],
607 fs: &CachedFs<OsFs>,
608 only: Option<&BTreeSet<String>>,
609) -> Result<Vec<FixRun>, CliError> {
610 per_root(fix::prompts(args, env), runs, |run| {
611 let selection = fix::selection(args, env, &run.report, run.config.policy.prefer, only)?;
612 let plan = skif::apply_fixes(&run.workspace, &run.report, &selection, fs)?;
613 let preview = fix::preview(&plan, &run.workspace.root, fs)?;
614 Ok(FixRun::dry_run(plan, preview))
615 })
616}
617
618pub fn lint_to_json(path: &Path, overrides: &ConfigOverrides, recursive: bool) -> Result<String, CliError> {
632 let args = json_args(path, recursive)?;
633 let (stdout, _) = capture(&args, overrides, None)?;
634 String::from_utf8(stdout).map_err(|error| CliError::new(Kind::Io, format!("the report is not UTF-8: {error}")))
635}
636
637#[derive(Debug, Clone, Default, PartialEq, Eq)]
641#[non_exhaustive]
642pub struct LintCache {
643 pub enabled: Option<bool>,
645 pub location: Option<PathBuf>,
647 pub max_size: Option<u64>,
649}
650
651impl LintCache {
652 #[must_use]
654 pub const fn with_enabled(mut self, enabled: bool) -> Self {
655 self.enabled = Some(enabled);
656 self
657 }
658
659 #[must_use]
661 pub fn with_location(mut self, location: PathBuf) -> Self {
662 self.location = Some(location);
663 self
664 }
665
666 #[must_use]
668 pub const fn with_max_size(mut self, max_size: u64) -> Self {
669 self.max_size = Some(max_size);
670 self
671 }
672}
673
674pub fn lint_to_json_cached(
681 path: &Path,
682 overrides: &ConfigOverrides,
683 recursive: bool,
684 cache: &LintCache,
685) -> Result<String, CliError> {
686 if cache
687 .location
688 .as_ref()
689 .is_some_and(|location| location.as_os_str().is_empty())
690 {
691 return Err(CliError::new(Kind::Usage, crate::args::EMPTY_CACHE_LOCATION));
692 }
693 let args = json_args(path, recursive)?;
694 let flags = crate::cache::CacheFlags {
695 cache: cache.enabled == Some(true),
696 no_cache: cache.enabled == Some(false),
697 location: cache.location.clone(),
698 max_size: cache.max_size,
699 };
700 let host = DiskHost::new(flags, CacheEnv::detect(Env::detect().ci), false);
701 let (stdout, _) = capture(&args, overrides, Some(&host))?;
702 String::from_utf8(stdout).map_err(|error| CliError::new(Kind::Io, format!("the report is not UTF-8: {error}")))
703}
704
705fn json_args(path: &Path, recursive: bool) -> Result<LintArgs, CliError> {
707 use clap::{Args as _, FromArgMatches as _};
708 let mut argv: Vec<std::ffi::OsString> = vec!["--format".into(), "json".into()];
709 if recursive {
710 argv.push("--recursive".into());
711 }
712 argv.extend(["--".into(), path.as_os_str().to_owned()]);
713 let command = LintArgs::augment_args(clap::Command::new("skif").no_binary_name(true));
714 command
715 .try_get_matches_from(argv)
716 .and_then(|matches| LintArgs::from_arg_matches(&matches))
717 .map_err(|error| CliError::new(Kind::Internal, error.to_string()))
718}
719
720pub fn lint_root(
725 path: &Path,
726 overrides: &ConfigOverrides,
727 fs: &Arc<dyn FileSystem>,
728 modules: Option<&dyn CacheHost>,
729) -> Result<(PathBuf, Report, Vec<RootRun>), CliError> {
730 let start = canonical(path)?;
731 let cached: Arc<dyn FileSystem> = Arc::new(CachedFs::new(Arc::clone(fs)));
732 let Resolved { base, targets, .. } = roots::resolve(&start, false, cached.as_ref(), overrides)?;
733 let attached = modules.map_or_default(|host| host.attach(&base, &targets));
734 let linters = Linters::build_with(&targets, Some(&cached), &attached)?;
735 let mut runs = roots::lint_targets(&base, targets, &linters)?;
736 roots::settle_shared_config(&mut runs);
737 let reports: Vec<Cow<'_, Report>> = runs
738 .iter()
739 .map(|run| roots::prefixed(&run.report, &run.prefix))
740 .collect();
741 let report = roots::aggregate(&reports).into_owned();
742 Ok((base, report, runs))
743}
744
745fn truncated_json(truncated: &[PathBuf]) -> Value {
747 Value::Array(truncated.iter().map(|dir| Value::String(roots::display(dir))).collect())
748}
749
750fn note_truncated(truncated: &[PathBuf]) {
752 const SHOWN: usize = 5;
753 if truncated.is_empty() {
754 return;
755 }
756 let shown: Vec<String> = truncated
757 .iter()
758 .take(SHOWN)
759 .map(|dir| escape_controls(&roots::display(dir)).into_owned())
760 .collect();
761 let more = truncated.len().saturating_sub(SHOWN);
762 let tail = if more > 0 {
763 format!(" and {more} more")
764 } else {
765 String::new()
766 };
767 stderr_line(&format!(
768 "warning: the search for roots stopped {} levels down; nothing below {}{tail} was searched",
769 DiscoverOptions::default().max_depth,
770 shown.join(", ")
771 ));
772}
773
774const HOST: Env = Env {
777 ci: false,
778 no_color: true,
779 stdin_tty: false,
780 stdout_tty: false,
781 github_actions: false,
782};
783
784pub(crate) fn run_captured(args: &LintArgs, modules: Option<&dyn CacheHost>) -> Result<(Vec<u8>, u8), CliError> {
791 capture(args, &overrides(args), modules)
792}
793
794fn capture(
796 args: &LintArgs,
797 overrides: &ConfigOverrides,
798 modules: Option<&dyn CacheHost>,
799) -> Result<(Vec<u8>, u8), CliError> {
800 let mut stdout = Vec::new();
801 let result = execute_with(args, overrides, HOST, Teardown::Free, modules, Some(&mut stdout));
802 if let Some(modules) = modules {
803 modules.finish(completed(&result));
804 }
805 result.map(|code| (stdout, code))
806}
807
808fn execute(
810 args: &LintArgs,
811 env: Env,
812 teardown: Teardown,
813 modules: Option<&dyn CacheHost>,
814 capture: Option<&mut Vec<u8>>,
815) -> Result<u8, CliError> {
816 execute_with(args, &overrides(args), env, teardown, modules, capture)
817}
818
819fn execute_with(
821 args: &LintArgs,
822 overrides: &ConfigOverrides,
823 env: Env,
824 teardown: Teardown,
825 modules: Option<&dyn CacheHost>,
826 capture: Option<&mut Vec<u8>>,
827) -> Result<u8, CliError> {
828 let shared = Arc::new(CachedFs::new(OsFs));
829 let fs: &CachedFs<OsFs> = &shared;
830 let targets_out = args.targets()?;
831 if args.dry_run && !args.fixing() {
832 return Err(CliError::new(Kind::Usage, "--dry-run needs --fix or --fix-unsafe"));
833 }
834 if args.fixing() && !args.dry_run() && env.ci {
836 return Err(CliError::ci_refusal());
837 }
838 check_max_show_issues(args, &targets_out)?;
839 if args.recursive {
840 rule_given_as_path(&args.path)?;
841 }
842 let start = canonical(&args.path)?;
843 let Resolved {
844 base,
845 mut targets,
846 multi,
847 failures: root_errors,
848 truncated,
849 } = timing::phase("root discovery (roots, configs, workspaces)", || {
850 roots::resolve(&start, args.recursive, fs, overrides)
851 })?;
852 note_truncated(&truncated);
853 warn_unanchored_patterns(&targets);
854 warn_idle_patterns(&targets);
855 if args.debug {
856 trace::debug_targets(&base, &targets);
857 }
858 let filter = Filter::new(args)?;
859 for target in &mut targets {
860 adjust(args, &mut target.config)?;
861 filter.configure(&mut target.config)?;
862 }
863 apply_tsconfig(args, &mut targets)?;
864 warn_empty_tsconfig_projects(&targets, fs);
865 let attached = modules.map_or_default(|host| host.attach(&base, &targets));
866 let run_fs: Arc<dyn FileSystem> = shared.clone();
867 let linters = Linters::build_with(&targets, Some(&run_fs), &attached)?;
868 let only = fix::fix_type_rules(&args.fix_type, linters.rules().into_iter().map(|meta| meta.id))?;
870 let mut runs = timing::phase("lint roots", || roots::lint_targets(&base, targets, &linters))?;
871 filter.apply_runs(&mut runs)?;
872 if !multi && args.fixing() {
873 warn_nested_roots(args, &base, &runs, fs);
874 }
875
876 let mut fixes: Vec<FixRun> = Vec::new();
877 if args.dry_run() {
878 fixes = plan_roots(args, env, &runs, fs, only.as_ref())?;
879 } else if args.fixing() {
880 match fix_roots((args, &filter), env, &linters, runs, fs, only.as_ref())? {
881 Fixed::All(fixed_runs, done) => {
882 runs = fixed_runs;
883 fixes = done;
884 }
885 Fixed::Stopped(code) => return Ok(code),
886 }
887 }
888 roots::settle_shared_config(&mut runs);
890
891 let reports: Vec<Cow<'_, Report>> = runs
892 .iter()
893 .map(|run| roots::prefixed(&run.report, &run.prefix))
894 .collect();
895 let aggregate = roots::aggregate(&reports);
896 if args.debug {
897 trace::debug_cache(&aggregate.cache);
898 }
899 let prefixes: Vec<&Path> = runs.iter().map(|run| run.prefix.as_path()).collect();
900 let root_fixes = roots_fix(&prefixes, &fixes);
901 let cut: Option<Vec<Cow<'_, Report>>> = args.max_show_issues.map(|max| {
904 let (cut, hidden) = filter::truncate_shown(reports.clone(), max);
905 if hidden > 0 && args.format() == Format::Human {
906 stderr_line(&format!(
907 "note: --max-show-issues {max} left {hidden} finding{} out of the list",
908 if hidden == 1 { "" } else { "s" }
909 ));
910 }
911 cut
912 });
913 let shown = cut.as_ref().map(|cut| {
914 let mut shown = roots::aggregate(cut).into_owned();
915 shown.summary = aggregate.summary;
916 shown
917 });
918 let listed = cut.as_ref().unwrap_or(&reports);
919
920 let views: Vec<RootView<'_>> = runs
921 .iter()
922 .zip(listed)
923 .enumerate()
924 .map(|(index, (run, report))| RootView {
925 prefix: &run.prefix,
926 report,
927 json: multi.then(|| roots::root_json(run, report)),
928 fix: fixes.get(index),
929 })
930 .collect();
931 let rendering = Rendering {
932 format: Format::default(),
933 annotations: annotations(args, env),
934 color: false,
935 root: &base,
936 repo_root: None,
937 rules: linters.rules(),
938 multi,
939 errors: root_errors.iter().map(RootError::to_json).collect(),
940 truncated: truncated_json(&truncated),
941 };
942 render_and_write(
943 args,
944 env,
945 &targets_out,
946 rendering,
947 (&aggregate, shown.as_ref(), &views, &root_fixes),
948 fs,
949 capture,
950 )?;
951 if !fixes.is_empty() && !matches!(args.format(), Format::Human | Format::Json | Format::Toon) {
952 write_summary_to_stderr(&root_fixes);
953 }
954
955 for root_error in &root_errors {
956 stderr_line(&format!("error: {}", escape_controls(&root_error.describe())));
957 }
958 let install_failures: Vec<&InstallStatus> = fixes
959 .iter()
960 .map(|run| &run.install)
961 .filter(|status| matches!(status, InstallStatus::Failed { .. }))
962 .collect();
963 for status in &install_failures {
964 if let InstallStatus::Failed { command, message } = status {
965 stderr_line(&format!(
966 "error: install failed ({}): {}",
967 escape_controls(command),
968 escape_controls(message)
969 ));
970 }
971 }
972 if !install_failures.is_empty() || !root_errors.is_empty() {
973 return Ok(COULD_NOT_RUN);
974 }
975 let code = run_exit_code(args, &runs, &aggregate);
976 if teardown == Teardown::Leak {
977 std::mem::forget(views);
980 std::mem::forget(aggregate);
981 std::mem::forget(shown);
982 std::mem::forget(cut);
983 std::mem::forget(reports);
984 std::mem::forget(runs);
985 std::mem::forget(linters);
986 std::mem::forget(run_fs);
987 std::mem::forget(shared);
988 }
989 Ok(code)
990}
991
992fn warn_unanchored_patterns(targets: &[Target]) {
995 let mut seen: BTreeSet<(PathBuf, &str)> = BTreeSet::new();
996 for target in targets {
997 for scope in target
998 .config
999 .overrides
1000 .iter()
1001 .filter_map(|scoped| scoped.scope.as_ref())
1002 {
1003 let file = target
1004 .sources
1005 .get(scope.source)
1006 .map_or_else(|| scope.declared_in.clone(), |source| source.path.clone());
1007 for pattern in scope.unanchored() {
1008 if seen.insert((file.clone(), pattern.as_str())) {
1009 stderr_line(&format!(
1010 "warning: {}: the [[overrides]] pattern `{}` leaves the directory it is anchored at, so it \
1011 matches nothing; write a path from the workspace root as `$ROOT/<path>`",
1012 file.display(),
1013 escape_controls(pattern)
1014 ));
1015 }
1016 }
1017 }
1018 }
1019}
1020
1021fn warn_idle_patterns(targets: &[Target]) {
1026 let mut idle: BTreeMap<(PathBuf, &str), Option<(IdleReason, &Path)>> = BTreeMap::new();
1027 for target in targets {
1028 let dirs: Vec<(&str, String)> = target
1029 .workspace
1030 .all_packages()
1031 .map(|package| {
1032 let dir = if package.dir.as_os_str().is_empty() {
1033 skif_core::slash(&target.root)
1034 } else {
1035 skif_core::slash(&target.root.join(&package.dir))
1036 };
1037 (package.display_name(), dir)
1038 })
1039 .collect();
1040 let packages: Vec<(&str, &str)> = dirs.iter().map(|(name, dir)| (*name, dir.as_str())).collect();
1041 for scoped in &target.config.overrides {
1042 let Some(scope) = scoped.scope.as_ref() else {
1043 continue;
1044 };
1045 let file = target
1046 .sources
1047 .get(scope.source)
1048 .map_or_else(|| scope.declared_in.clone(), |source| source.path.clone());
1049 let found = scope.idle_patterns(&packages);
1050 for pattern in scoped.packages.patterns().iter().chain(scoped.files.patterns()) {
1051 let verdict = found
1052 .iter()
1053 .find(|(written, _)| *written == pattern.as_str())
1054 .map(|(_, reason)| (*reason, scope.declared_in.as_path()));
1055 let entry = idle.entry((file.clone(), pattern.as_str())).or_insert(verdict);
1056 if verdict.is_none() {
1057 *entry = None;
1058 }
1059 }
1060 }
1061 }
1062 for ((file, pattern), verdict) in idle {
1063 let Some((reason, declared_in)) = verdict else {
1064 continue;
1065 };
1066 let shown = file.display().to_string();
1067 let (file, pattern) = (escape_controls(&shown), escape_controls(pattern));
1068 stderr_line(&match reason {
1069 IdleReason::NoPackage => {
1070 format!("warning: {file}: the [[overrides]] pattern `{pattern}` selects no package of the run")
1071 }
1072 _ => format!(
1073 "warning: {file}: the [[overrides]] pattern `{pattern}` selects nothing: it is relative to {}, the \
1074 directory of the file, and no root of the run lies below it; write a path from the root as \
1075 `$ROOT/<path>`",
1076 escape_controls(&declared_in.display().to_string())
1077 ),
1078 });
1079 }
1080}
1081
1082const DEPENDENCY_REMOVALS: [&str; 2] = ["unused-dependencies", "unused-dev-dependencies"];
1084
1085fn warn_nested_roots(args: &LintArgs, root: &Path, runs: &[RootRun], fs: &dyn FileSystem) {
1089 let removes = runs
1090 .iter()
1091 .flat_map(|run| &run.report.diagnostics)
1092 .any(|diagnostic| DEPENDENCY_REMOVALS.contains(&diagnostic.rule.as_str()) && !diagnostic.fixes.is_empty());
1093 if !removes {
1094 return;
1095 }
1096 let overrides = overrides(args);
1098 let discovery = match runs.iter().find(|run| run.workspace.root.as_path() == root) {
1099 Some(run) => skif::discover_targets_below(&run.workspace, fs, &overrides),
1100 None => skif::discover_targets(root, fs, &overrides),
1101 };
1102 let Ok(discovery) = discovery else {
1103 return;
1104 };
1105 let nested: Vec<String> = discovery
1106 .targets
1107 .iter()
1108 .filter(|target| target.root.as_path() != root)
1109 .map(|target| skif::slash(target.root.strip_prefix(root).unwrap_or(&target.root)))
1110 .collect();
1111 if nested.is_empty() {
1112 return;
1113 }
1114 stderr_line(&format!(
1115 "warning: {} holds other roots ({}) that this run does not analyse, so a dependency only their code uses is \
1116 reported unused and its fix removes it; run with -r to credit their uses",
1117 root.display(),
1118 escape_controls(&nested.join(", "))
1119 ));
1120}
1121
1122fn check_max_show_issues(args: &LintArgs, targets: &[(Format, Option<PathBuf>)]) -> Result<(), CliError> {
1130 if args.max_show_issues.is_none() {
1131 return Ok(());
1132 }
1133 let reason = if args.fixing() {
1134 "cannot be combined with --fix or --fix-unsafe"
1135 } else if targets
1136 .iter()
1137 .any(|(format, _)| !matches!(format, Format::Human | Format::Json | Format::Toon))
1138 {
1139 "applies to human, json and toon output only; other formats always list every finding"
1140 } else {
1141 return Ok(());
1142 };
1143 Err(CliError::new(Kind::Usage, format!("--max-show-issues {reason}")))
1144}
1145
1146fn render_and_write(
1153 args: &LintArgs,
1154 env: Env,
1155 targets: &[(Format, Option<PathBuf>)],
1156 mut rendering: Rendering<'_>,
1157 (report, shown, views, fixes): (&Report, Option<&Report>, &[RootView<'_>], &[RootFix<'_>]),
1158 fs: &dyn FileSystem,
1159 mut capture: Option<&mut Vec<u8>>,
1160) -> Result<(), CliError> {
1161 let needs_repo_root = rendering.annotations
1162 || targets.iter().any(|(format, _)| {
1163 matches!(
1164 format,
1165 Format::Github | Format::Sarif | Format::Codeclimate | Format::Codeowners
1166 )
1167 });
1168 if needs_repo_root {
1169 rendering.repo_root = repo_root(rendering.root);
1170 }
1171 if let [(format, None)] = targets {
1173 rendering.format = *format;
1174 rendering.color = color_enabled(args, env, *format, None);
1175 let listed = shown.filter(|_| lists_shown(*format)).unwrap_or(report);
1176 return timing::phase("render", || match capture {
1177 Some(capture) => {
1178 capture.extend(output::render(listed, views, &rendering, fs, fixes)?);
1179 Ok(())
1180 }
1181 None => output::render_to_stdout(listed, views, &rendering, fs, fixes),
1182 });
1183 }
1184 let mut rendered = Vec::with_capacity(targets.len());
1185 for (format, file) in targets {
1186 rendering.format = *format;
1187 rendering.color = color_enabled(args, env, *format, file.as_deref());
1188 let listed = shown.filter(|_| lists_shown(*format)).unwrap_or(report);
1189 let bytes = timing::phase("render", || output::render(listed, views, &rendering, fs, fixes))?;
1190 rendered.push((bytes, file.as_deref()));
1191 }
1192 for (bytes, file) in &rendered {
1194 if let Some(file) = file {
1195 output::emit(bytes, Some(file))?;
1196 }
1197 }
1198 for (bytes, file) in &rendered {
1199 if file.is_none() {
1200 match capture.as_deref_mut() {
1201 Some(capture) => capture.extend_from_slice(bytes),
1202 None => output::emit(bytes, None)?,
1203 }
1204 }
1205 }
1206 Ok(())
1207}
1208
1209const fn lists_shown(format: Format) -> bool {
1211 matches!(format, Format::Json | Format::Toon)
1212}
1213
1214fn roots_fix<'a>(prefixes: &[&'a Path], fixes: &'a [FixRun]) -> Vec<RootFix<'a>> {
1215 prefixes
1216 .iter()
1217 .zip(fixes)
1218 .map(|(&prefix, run)| RootFix { prefix, run })
1219 .collect()
1220}
1221
1222fn fix_incomplete(args: &LintArgs, headline: &str, error: &CliError, fixes: &[RootFix<'_>]) -> u8 {
1225 let error = CliError {
1226 message: format!("{headline}: {}", error.message),
1227 kind: error.kind,
1228 path: error.path.clone(),
1229 line: error.line,
1230 column: error.column,
1231 };
1232 if matches!(args.format(), Format::Json | Format::Toon) {
1233 let mut extra = Map::new();
1234 extra.insert("fix".to_owned(), fix::fixes_json(fixes));
1235 emit_error_with(&error, args.format(), extra, &mut std::io::stdout().lock());
1236 } else {
1237 if args.format() == Format::Human {
1239 let mut summary = Vec::new();
1240 if fix::write_fixes_human(fixes, &mut summary).is_ok() {
1241 let _ = output::write_stdout(&summary);
1242 }
1243 } else {
1244 write_summary_to_stderr(fixes);
1245 }
1246 emit_error(&error, args.format());
1247 }
1248 COULD_NOT_RUN
1249}
1250
1251fn write_summary_to_stderr(fixes: &[RootFix<'_>]) {
1253 let mut summary = Vec::new();
1254 if fix::write_fixes_human(fixes, &mut summary).is_ok() {
1255 stderr_line(String::from_utf8_lossy(&summary).trim_end());
1256 }
1257}
1258
1259#[cfg(test)]
1260#[allow(clippy::unwrap_used)]
1261mod tests {
1262 use clap::Parser;
1263
1264 use super::*;
1265 use crate::args::Cli;
1266
1267 fn lint_args(flags: &[&str]) -> LintArgs {
1268 Cli::try_parse_from(std::iter::once("skif").chain(flags.iter().copied()))
1269 .unwrap()
1270 .lint
1271 }
1272
1273 const TERMINAL: Env = Env {
1274 ci: false,
1275 no_color: false,
1276 stdin_tty: true,
1277 stdout_tty: true,
1278 github_actions: false,
1279 };
1280
1281 #[test]
1282 fn only_the_primary_human_rendering_is_coloured() {
1283 let file = Some(Path::new("report.txt"));
1284 let args = lint_args(&["--format", "human", "--format", "human=report.txt"]);
1285 assert!(color_enabled(&args, TERMINAL, Format::Human, None));
1286 assert!(!color_enabled(&args, TERMINAL, Format::Human, file));
1287
1288 let args = lint_args(&["--color", "always", "--format", "json", "--format", "human=report.txt"]);
1289 assert!(!color_enabled(&args, TERMINAL, Format::Human, file));
1290
1291 let args = lint_args(&["--format", "human", "--output", "report.txt"]);
1293 assert!(!color_enabled(&args, TERMINAL, Format::Human, file));
1294 let args = lint_args(&["--color", "always", "--format", "human", "--output", "report.txt"]);
1295 assert!(color_enabled(&args, TERMINAL, Format::Human, file));
1296
1297 let args = lint_args(&["--format", "human"]);
1298 let no_color = Env {
1299 no_color: true,
1300 ..TERMINAL
1301 };
1302 assert!(!color_enabled(&args, no_color, Format::Human, None));
1303 let piped = Env {
1304 stdout_tty: false,
1305 ..TERMINAL
1306 };
1307 assert!(!color_enabled(&args, piped, Format::Human, None));
1308 let args = lint_args(&["--color", "never", "--format", "human"]);
1309 assert!(!color_enabled(&args, TERMINAL, Format::Human, None));
1310 }
1311
1312 #[test]
1313 fn a_missing_path_named_like_a_rule_is_a_usage_error() {
1314 let sherif = rule_given_as_path(std::path::Path::new("multiple-dependency-versions")).unwrap_err();
1315 assert_eq!(sherif.kind, Kind::Usage);
1316 assert!(
1317 sherif.message.contains("--ignore-rule version-mismatch"),
1318 "{}",
1319 sherif.message
1320 );
1321 let skif = rule_given_as_path(std::path::Path::new("unused-dependencies")).unwrap_err();
1322 assert_eq!(skif.kind, Kind::Usage);
1323 assert!(
1324 skif.message.contains("--ignore-rule unused-dependencies"),
1325 "{}",
1326 skif.message
1327 );
1328 }
1329
1330 #[test]
1331 fn a_root_whose_configuration_a_plan_wrote_is_linted_again() {
1332 let shared = PathBuf::from("/etc/skif.toml");
1334 let own = PathBuf::from("/r/c/skif.toml");
1335 let written = [
1336 BTreeSet::from([shared.clone(), PathBuf::from("/r/package.json")]),
1337 BTreeSet::new(),
1338 BTreeSet::new(),
1339 ];
1340 let sources: [&[PathBuf]; 3] = [
1341 std::slice::from_ref(&shared),
1342 std::slice::from_ref(&shared),
1343 std::slice::from_ref(&own),
1344 ];
1345 assert_eq!(relinted(&written, &sources), [true, true, false]);
1346 }
1347
1348 #[test]
1349 fn a_root_without_a_plan_or_a_written_configuration_is_not_linted_again() {
1350 let shared = PathBuf::from("/etc/skif.toml");
1351 let written = [BTreeSet::new(), BTreeSet::from([PathBuf::from("/r/b/package.json")])];
1352 let sources: [&[PathBuf]; 2] = [std::slice::from_ref(&shared), std::slice::from_ref(&shared)];
1353 assert_eq!(relinted(&written, &sources), [false, true]);
1354 }
1355
1356 #[test]
1357 fn other_paths_are_left_to_root_discovery() {
1358 assert!(rule_given_as_path(std::path::Path::new("no-such-directory-here")).is_ok());
1359 assert!(rule_given_as_path(std::path::Path::new(".")).is_ok());
1360 }
1361}