1use clap::Parser;
2
3use mago_interner::ThreadedInterner;
4use mago_service::config::Configuration;
5use mago_service::linter::LintService;
6use mago_service::source::SourceService;
7
8use crate::utils::bail;
9
10#[derive(Parser, Debug)]
11#[command(
12 name = "fix",
13 about = "Fix lint issues identified during the linting process",
14 long_about = r#"
15Fix lint issues identified during the linting process.
16
17Automatically applies fixes where possible, based on the rules in the `mago.toml` or the default settings.
18 "#
19)]
20pub struct FixCommand {
21 #[arg(long, short, help = "Apply fixes that are marked as unsafe, including potentially unsafe fixes")]
22 pub r#unsafe: bool,
23 #[arg(long, short, help = "Apply fixes that are marked as potentially unsafe")]
24 pub potentially_unsafe: bool,
25 #[arg(long, short, help = "Run the command without writing any changes to disk")]
26 pub dry_run: bool,
27}
28
29pub async fn execute(command: FixCommand, configuration: Configuration) -> i32 {
30 let interner = ThreadedInterner::new();
31
32 let source_service = SourceService::new(interner.clone(), configuration.source);
33 let source_manager = source_service.load().await.unwrap_or_else(bail);
34
35 let service = LintService::new(configuration.linter, interner.clone(), source_manager.clone());
36
37 let result = service.fix(command.r#unsafe, command.potentially_unsafe, command.dry_run).await.unwrap_or_else(bail);
38
39 if result.skipped_unsafe > 0 {
40 mago_feedback::warn!(
41 "Skipped {} fixes because they were marked as unsafe. To apply those fixes, use the `--unsafe` flag.",
42 result.skipped_unsafe
43 );
44 }
45
46 if result.skipped_potentially_unsafe > 0 {
47 mago_feedback::warn!(
48 "Skipped {} fixes because they were marked as potentially unsafe. To apply those fixes, use the `--potentially-unsafe` flag.",
49 result.skipped_potentially_unsafe
50 );
51 }
52
53 if result.changed == 0 {
54 mago_feedback::info!("No fixes were applied");
55
56 return 0;
57 }
58
59 if command.dry_run {
60 mago_feedback::info!("Found {} fixes that can be applied", result.changed);
61
62 1
63 } else {
64 mago_feedback::info!("Applied {} fixes successfully", result.changed);
65
66 0
67 }
68}