mago 1.20.1

A comprehensive suite of PHP tooling inspired by Rust’s approach, providing parsing, linting, formatting, and more through a unified CLI and library interface.
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
//! Linting command implementation.
//!
//! This module implements the `mago lint` command, which checks PHP code against a
//! configurable set of linting rules to identify style violations, code smells, and
//! potential quality issues.
//!
//! # Features
//!
//! The linter provides several modes of operation:
//!
//! - **Full Linting** (default): Run all enabled rules against the codebase
//! - **Semantics Only** (`--semantics`): Only validate syntax and basic semantic structure
//! - **Pedantic Mode** (`--pedantic`): Enable all available rules for maximum thoroughness
//! - **Targeted Linting** (`--only`): Run only specific rules by code
//!
//! # Rule Discovery
//!
//! The command supports introspection of available rules:
//!
//! - **List Rules** (`--list-rules`): Display all currently enabled rules
//! - **Explain Rule** (`--explain <CODE>`): Show detailed documentation for a specific rule
//!
//! # Baseline Support
//!
//! The linter integrates with baseline functionality to enable incremental adoption
//! by ignoring pre-existing issues while catching new ones. See [`BaselineReportingArgs`]
//! for baseline options.

use std::path::PathBuf;
use std::process::ExitCode;
use std::time::Instant;

use clap::ColorChoice;
use clap::Parser;
use colored::Colorize;

use mago_database::DatabaseReader;
use mago_linter::registry::RuleRegistry;
use mago_linter::rule::AnyRule;
use mago_linter::rule_meta::RuleEntry;
use mago_orchestrator::service::lint::LintMode;
use mago_reporting::Level;

use crate::commands::args::baseline_reporting::BaselineReportingArgs;
use crate::commands::stdin_input;
use crate::config::Configuration;
use crate::error::Error;
use crate::utils::create_orchestrator;
use crate::utils::git;

/// Command for linting PHP source code.
///
/// This command runs configurable linting rules to check code style, consistency,
/// and quality. It supports multiple modes including semantic-only validation,
/// pedantic checking, and targeted rule execution.
///
/// # Examples
///
/// Lint all configured source paths:
/// ```text
/// mago lint
/// ```
///
/// Lint specific files or directories:
/// ```text
/// mago lint src/ tests/
/// ```
///
/// Run only specific rules:
/// ```text
/// mago lint --only no-empty,constant-condition
/// ```
///
/// Show documentation for a rule:
/// ```text
/// mago lint --explain no-empty
/// ```
#[derive(Parser, Debug)]
#[command(
    name = "lint",
    about = "Lints PHP source code for style, consistency, and structural errors.",
    long_about = indoc::indoc! {"
        Analyzes PHP files to find and report stylistic issues, inconsistencies, and
        potential code quality improvements based on a configurable set of rules.

        This is the primary tool for ensuring your codebase adheres to established
        coding standards and best practices.

        USAGE:

            mago lint
            mago lint src/
            mago lint --list-rules
            mago lint --explain no-empty
            mago lint --only no-empty,constant-condition

        By default, it lints all source paths defined in your `mago.toml` file. You can
        also provide specific file or directory paths to lint a subset of your project.
    "}
)]
pub struct LintCommand {
    /// Specific files or directories to lint instead of using configuration.
    ///
    /// When provided, these paths override the source configuration in mago.toml.
    /// You can specify individual files or entire directories to lint.
    #[arg()]
    pub path: Vec<PathBuf>,

    /// Skip linter rules and only perform basic syntax and semantic validation.
    ///
    /// This mode only checks that your PHP code parses correctly and has valid
    /// semantic structure, without applying any style or quality rules.
    /// Useful for quick syntax validation.
    #[arg(long, short = 's', conflicts_with_all = ["list_rules", "explain", "only"])]
    pub semantics: bool,

    /// Enable every available linter rule for maximum thoroughness.
    ///
    /// This overrides your configuration and enables all rules, including those
    /// disabled by default. The output will be extremely verbose and is not
    /// recommended for regular use. Useful for comprehensive code audits.
    #[arg(long)]
    pub pedantic: bool,

    /// Show detailed documentation for a specific linter rule.
    ///
    /// Displays the rule's description, examples of good and bad code,
    /// and available configuration options. Use the rule's code name,
    /// such as 'no-empty' or 'prefer-while-loop'.
    #[arg(
        long,
        conflicts_with_all = ["list_rules", "sort", "fixable_only", "semantics", "reporting_target", "reporting_format"]
    )]
    pub explain: Option<String>,

    /// Show all currently enabled linter rules and their descriptions.
    ///
    /// This displays a table of all rules that are active for your current
    /// configuration, along with their severity levels and categories.
    /// Combine with --json for machine-readable output.
    #[arg(
        long,
        conflicts_with_all = ["explain", "sort", "fixable_only", "semantics", "reporting_target", "reporting_format"]
    )]
    pub list_rules: bool,

    /// Output rule information in JSON format.
    ///
    /// When combined with --list-rules, outputs rule information as JSON
    /// instead of a human-readable table. Useful for generating documentation
    /// or integrating with other tools.
    #[arg(long, requires = "list_rules")]
    pub json: bool,

    /// Run only specific rules, ignoring the configuration file.
    ///
    /// Provide a comma-separated list of rule codes to run only those rules.
    /// This overrides your mago.toml configuration and is useful for targeted
    /// analysis or testing specific rules.
    #[arg(short, long, conflicts_with = "semantics", num_args = 1.., value_delimiter = ',')]
    pub only: Vec<String>,

    /// Only lint files that are staged in git.
    ///
    /// This flag is designed for git pre-commit hooks. It will find all PHP files
    /// currently staged for commit and lint only those files.
    ///
    /// Fails if not in a git repository.
    #[arg(long, conflicts_with_all = ["path", "list_rules", "explain"])]
    pub staged: bool,

    /// Read the file content from stdin and use the given path for baseline and reporting.
    ///
    /// Intended for editor integrations: pipe unsaved buffer content and pass the real file path.
    #[arg(long, conflicts_with_all = ["list_rules", "explain", "staged"])]
    pub stdin_input: bool,

    #[clap(flatten)]
    pub baseline_reporting: BaselineReportingArgs,
}

impl LintCommand {
    /// Executes the lint command.
    ///
    /// This method orchestrates the linting process based on the command's configuration:
    ///
    /// 1. Creates an orchestrator with the configured settings
    /// 2. Applies path overrides if `path` was provided
    /// 3. Loads the database by scanning the file system
    /// 4. Creates the linting service with the database
    /// 5. Handles special modes (`--explain`, `--list-rules`)
    /// 6. Runs linting in the appropriate mode (full or semantics-only)
    /// 7. Processes and reports issues through the baseline processor
    ///
    /// # Arguments
    ///
    /// * `configuration` - The loaded configuration containing linter settings
    /// * `color_choice` - Whether to use colored output
    ///
    /// # Returns
    ///
    /// - `Ok(ExitCode::SUCCESS)` if linting completed successfully (even with issues found)
    /// - `Ok(ExitCode::FAILURE)` if a rule explanation was requested but the rule wasn't found
    /// - `Err(Error)` if database loading, linting, or reporting failed
    ///
    /// # Special Modes
    ///
    /// - **Explain Mode** (`--explain`): Displays detailed rule documentation and exits
    /// - **List Mode** (`--list-rules`): Shows all enabled rules and exits
    /// - **Empty Database**: Logs a message and exits successfully if no files found
    pub fn execute(self, mut configuration: Configuration, color_choice: ColorChoice) -> Result<ExitCode, Error> {
        let trace_enabled = tracing::enabled!(tracing::Level::TRACE);
        let command_start = trace_enabled.then(Instant::now);

        let editor_url = configuration.editor_url.take();

        let orchestrator_init_start = trace_enabled.then(Instant::now);
        let mut orchestrator = create_orchestrator(&configuration, color_choice, self.pedantic, true, false);
        orchestrator.add_exclude_patterns(configuration.linter.excludes.iter());

        let stdin_override = stdin_input::resolve_stdin_override(
            self.stdin_input,
            &self.path,
            &configuration.source.workspace,
            &mut orchestrator,
        )?;

        if !self.stdin_input && self.staged {
            let staged_paths = git::get_staged_file_paths(&configuration.source.workspace)?;
            if staged_paths.is_empty() {
                tracing::info!("No staged files to lint.");
                return Ok(ExitCode::SUCCESS);
            }

            if self.baseline_reporting.reporting.fix {
                git::ensure_staged_files_are_clean(&configuration.source.workspace, &staged_paths)?;
            }

            orchestrator.set_source_paths(staged_paths.iter().map(|p| p.to_string_lossy().to_string()));
        } else if !self.stdin_input && !self.path.is_empty() {
            stdin_input::set_source_paths_from_paths(&mut orchestrator, &self.path);
        }
        let orchestrator_init_duration = orchestrator_init_start.map(|s| s.elapsed());

        let load_database_start = trace_enabled.then(Instant::now);
        let mut database = orchestrator.load_database(&configuration.source.workspace, false, None, stdin_override)?;
        let load_database_duration = load_database_start.map(|s| s.elapsed());

        let service = orchestrator.get_lint_service(database.read_only());

        if let Some(explain_code) = self.explain {
            let registry = service.create_registry(
                if self.only.is_empty() { None } else { Some(&self.only) },
                self.pedantic, // Enable all rules if pedantic is set
            );

            return explain_rule(&registry, &explain_code);
        }

        if self.list_rules {
            let registry = service.create_registry(
                if self.only.is_empty() { None } else { Some(&self.only) },
                self.pedantic, // Enable all rules if pedantic is set
            );

            return list_rules(registry.rules(), self.json);
        }

        if database.is_empty() {
            tracing::info!("No files found to lint.");

            return Ok(ExitCode::SUCCESS);
        }

        let lint_run_start = trace_enabled.then(Instant::now);
        let issues = service.lint(
            if self.semantics { LintMode::SemanticsOnly } else { LintMode::Full },
            if self.only.is_empty() { None } else { Some(self.only.as_slice()) },
        )?;
        let lint_run_duration = lint_run_start.map(|s| s.elapsed());

        let report_start = trace_enabled.then(Instant::now);
        let baseline = configuration.linter.baseline.as_deref();
        let baseline_variant = configuration.linter.baseline_variant;
        let processor = self.baseline_reporting.get_processor(
            color_choice,
            baseline,
            baseline_variant,
            editor_url,
            configuration.linter.minimum_fail_level,
        );

        let (exit_code, changed_file_ids) = processor.process_issues(&orchestrator, &mut database, issues)?;
        let report_duration = report_start.map(|s| s.elapsed());

        if self.staged && !changed_file_ids.is_empty() {
            git::stage_files(&configuration.source.workspace, &database, changed_file_ids)?;
        }

        let drop_database_start = trace_enabled.then(Instant::now);
        drop(database);
        let drop_database_duration = drop_database_start.map(|s| s.elapsed());

        let drop_orchestrator_start = trace_enabled.then(Instant::now);
        drop(orchestrator);
        let drop_orchestrator_duration = drop_orchestrator_start.map(|s| s.elapsed());

        if let Some(start) = command_start {
            tracing::trace!("Orchestrator initialized in {:?}.", orchestrator_init_duration.unwrap_or_default());
            tracing::trace!("Database loaded in {:?}.", load_database_duration.unwrap_or_default());
            tracing::trace!("Lint service ran in {:?}.", lint_run_duration.unwrap_or_default());
            tracing::trace!("Issues filtered and reported in {:?}.", report_duration.unwrap_or_default());
            tracing::trace!("Database dropped in {:?}.", drop_database_duration.unwrap_or_default());
            tracing::trace!("Orchestrator dropped in {:?}.", drop_orchestrator_duration.unwrap_or_default());
            tracing::trace!("Lint command finished in {:?}.", start.elapsed());
        }

        Ok(exit_code)
    }
}

/// Displays detailed documentation for a specific linting rule.
///
/// This function shows comprehensive information about a rule including its
/// description, code, category, and good/bad examples. The output is formatted
/// for terminal display with colors and proper wrapping.
///
/// # Arguments
///
/// * `registry` - The rule registry containing all available rules
/// * `code` - The rule code to explain (e.g., "no-empty", "prefer-while-loop")
///
/// # Returns
///
/// - `Ok(ExitCode::SUCCESS)` if the rule was found and explained
/// - `Ok(ExitCode::FAILURE)` if the rule code doesn't exist in the registry
///
/// # Output Format
///
/// The explanation includes:
/// - Rule name and description (wrapped to 80 characters)
/// - Rule code and category
/// - Good example (if available)
/// - Bad example (if available)
/// - Suggested command to try the rule
pub fn explain_rule(registry: &RuleRegistry, code: &str) -> Result<ExitCode, Error> {
    let Some(rule) = registry.rules().iter().find(|r| r.meta().code == code) else {
        println!();
        println!("  {}", "Error: Rule not found".red().bold());
        println!("  {}", format!("Could not find a rule with the code '{}'.", code).bright_black());
        println!("  {}", "Please check the spelling and try again.".bright_black());
        println!();

        return Ok(ExitCode::FAILURE);
    };

    let meta = rule.meta();

    println!();
    println!("  ╭─ {} {}", "Rule".bold(), meta.name.cyan().bold());
    println!("");

    println!("{}", wrap_and_prefix(meta.description, "", 80));

    println!("");
    println!("{}: {}", "Code".bold(), meta.code.yellow());
    println!("{}: {}", "Category".bold(), meta.category.as_str().magenta());

    if !meta.good_example.trim().is_empty() {
        println!("");
        println!("{}", "✅ Good Example".green().bold());
        println!("");
        println!("{}", colorize_code_block(meta.good_example));
    }

    if !meta.bad_example.trim().is_empty() {
        println!("");
        println!("{}", "🚫 Bad Example".red().bold());
        println!("");
        println!("{}", colorize_code_block(meta.bad_example));
    }

    println!("");
    println!("{}", "Try it out!".bold());
    println!("{}", format!("mago lint --only {}", meta.code).bright_black());
    println!("  ╰─");
    println!();

    Ok(ExitCode::SUCCESS)
}

/// Lists all enabled linting rules.
///
/// This function displays all currently active rules in either human-readable
/// table format or JSON format. The table is formatted with proper column
/// alignment showing rule name, code, severity level, and category.
///
/// # Arguments
///
/// * `rules` - The list of enabled rules to display
/// * `json` - Whether to output in JSON format instead of a table
///
/// # Returns
///
/// Always returns `Ok(ExitCode::SUCCESS)` since listing rules cannot fail.
///
/// # Output Formats
///
/// **Table Format** (default):
/// - Aligned columns for Name, Code, Level, and Category
/// - Color-coded severity levels (Error=red, Warning=yellow, etc.)
/// - Helpful footer with `--explain` command suggestion
///
/// **JSON Format** (`--json`):
/// - Array of rule metadata objects
/// - Pretty-printed for readability
/// - Machine-parseable for tooling integration
pub fn list_rules(rules: &[AnyRule], json: bool) -> Result<ExitCode, Error> {
    if rules.is_empty() && !json {
        println!("{}", "No rules are currently enabled.".yellow());

        return Ok(ExitCode::SUCCESS);
    }

    if json {
        let entries: Vec<_> = rules.iter().map(|r| RuleEntry { meta: r.meta(), level: r.default_level() }).collect();

        println!("{}", serde_json::to_string_pretty(&entries)?);

        return Ok(ExitCode::SUCCESS);
    }

    let max_name = rules.iter().map(|r| r.meta().name.len()).max().unwrap_or(0);
    let max_code = rules.iter().map(|r| r.meta().code.len()).max().unwrap_or(0);

    println!();
    println!(
        "  {: <width_name$}   {: <width_code$}   {: <8}   {}",
        "Name".bold().underline(),
        "Code".bold().underline(),
        "Level".bold().underline(),
        "Category".bold().underline(),
        width_name = max_name,
        width_code = max_code,
    );
    println!();

    for rule in rules {
        let meta = rule.meta();
        let level_str = match rule.default_level() {
            Level::Error => "Error".red(),
            Level::Warning => "Warning".yellow(),
            Level::Help => "Help".green(),
            Level::Note => "Note".blue(),
        };

        println!(
            "  {: <width_name$}   {: <width_code$}   {: <8}   {}",
            meta.name.cyan(),
            meta.code.bright_black(),
            level_str.bold(),
            meta.category.as_str().magenta(),
            width_name = max_name,
            width_code = max_code,
        );
    }

    println!();
    println!("  Run {} to see more information about a specific rule.", "mago lint --explain <CODE>".bold());
    println!();

    Ok(ExitCode::SUCCESS)
}

fn colorize_code_block(code: &str) -> String {
    let mut colored_code = String::new();
    for line in code.trim().lines() {
        let trimmed_line = line.trim_start();
        let indentation = &line[..line.len() - trimmed_line.len()];

        let colored_line =
            if trimmed_line.starts_with("<?php") || trimmed_line.starts_with("<?") || trimmed_line.starts_with("?>") {
                trimmed_line.yellow().bold().to_string()
            } else {
                trimmed_line.to_string()
            };

        colored_code.push_str(&format!("{}{}\n", indentation.bright_black(), colored_line));
    }

    colored_code.trim_end().to_string()
}

fn wrap_and_prefix(text: &str, prefix: &str, width: usize) -> String {
    let mut result = String::new();
    let wrap_width = width.saturating_sub(prefix.len());

    for (i, paragraph) in text.trim().split("\n\n").enumerate() {
        if i > 0 {
            result.push_str(prefix);
            result.push('\n');
        }

        let mut current_line = String::new();
        for word in paragraph.split_whitespace() {
            if !current_line.is_empty() && current_line.len() + word.len() + 1 > wrap_width {
                result.push_str(prefix);
                result.push_str(&current_line);
                result.push('\n');
                current_line.clear();
            }

            if !current_line.is_empty() {
                current_line.push(' ');
            }
            current_line.push_str(word);
        }

        if !current_line.is_empty() {
            result.push_str(prefix);
            result.push_str(&current_line);
            result.push('\n');
        }
    }

    result.trim_end().to_string()
}