mago_cli/commands/
fix.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
use clap::Parser;

use mago_interner::ThreadedInterner;
use mago_service::config::Configuration;
use mago_service::linter::LintService;
use mago_service::source::SourceService;

use crate::utils::bail;

#[derive(Parser, Debug)]
#[command(
    name = "fix",
    about = "Fix lint issues identified during the linting process",
    long_about = r#"
Fix lint issues identified during the linting process.

Automatically applies fixes where possible, based on the rules in the `mago.toml` or the default settings.
    "#
)]
pub struct FixCommand {
    #[arg(long, short, help = "Apply fixes that are marked as unsafe, including potentially unsafe fixes")]
    pub r#unsafe: bool,
    #[arg(long, short, help = "Apply fixes that are marked as potentially unsafe")]
    pub potentially_unsafe: bool,
    #[arg(long, short, help = "Run the command without writing any changes to disk")]
    pub dry_run: bool,
}

pub async fn execute(command: FixCommand, configuration: Configuration) -> i32 {
    let interner = ThreadedInterner::new();

    let source_service = SourceService::new(interner.clone(), configuration.source);
    let source_manager = source_service.load().await.unwrap_or_else(bail);

    let service = LintService::new(configuration.linter, interner.clone(), source_manager.clone());

    let result = service.fix(command.r#unsafe, command.potentially_unsafe, command.dry_run).await.unwrap_or_else(bail);

    if result.skipped_unsafe > 0 {
        mago_feedback::warn!(
            "Skipped {} fixes because they were marked as unsafe. To apply those fixes, use the `--unsafe` flag.",
            result.skipped_unsafe
        );
    }

    if result.skipped_potentially_unsafe > 0 {
        mago_feedback::warn!(
            "Skipped {} fixes because they were marked as potentially unsafe. To apply those fixes, use the `--potentially-unsafe` flag.",
            result.skipped_potentially_unsafe
        );
    }

    if result.changed == 0 {
        mago_feedback::info!("No fixes were applied");

        return 0;
    }

    if command.dry_run {
        mago_feedback::info!("Found {} fixes that can be applied", result.changed);

        1
    } else {
        mago_feedback::info!("Applied {} fixes successfully", result.changed);

        0
    }
}