blade-cli 0.1.0

Fast, Node-free linter for Laravel Blade templates
mod config;
mod files;
mod output;

use std::fs;
use std::io::{self, Write};
use std::path::PathBuf;
use std::process::ExitCode;

use blade_lint::Severity;
use clap::{Args, Parser, Subcommand, ValueEnum};

/// Fast, Node-free linter for Laravel Blade templates.
#[derive(Parser)]
#[command(name = "blade", version, arg_required_else_help = true)]
struct Cli {
    #[command(subcommand)]
    command: Command,
}

#[derive(Subcommand)]
enum Command {
    /// Check Blade templates for problems.
    Lint(LintArgs),
}

#[derive(Args)]
struct LintArgs {
    /// Files or directories to lint. Directories are searched for *.blade.php,
    /// skipping hidden and .gitignored paths.
    #[arg(default_value = ".")]
    paths: Vec<PathBuf>,
    /// How to print the results.
    #[arg(long, value_enum, default_value_t = Format::Human)]
    format: Format,
    /// The config file to use. Defaults to ./blade.toml if it exists.
    #[arg(long)]
    config: Option<PathBuf>,
}

#[derive(Clone, Copy, ValueEnum)]
enum Format {
    /// Findings with source snippets, and a summary.
    Human,
    /// One JSON object, for other tools.
    Json,
    /// GitHub Actions annotations.
    Github,
}

fn main() -> ExitCode {
    match Cli::parse().command {
        Command::Lint(args) => lint(&args),
    }
}

/// Exit codes: 0 no errors (warnings allowed), 1 errors found, 2 couldn't run.
fn lint(args: &LintArgs) -> ExitCode {
    let config = match config::load(args.config.as_deref()) {
        Ok(config) => config,
        Err(e) => return fail(&e),
    };
    let paths = match files::collect(&args.paths) {
        Ok(paths) => paths,
        Err(e) => return fail(&e),
    };

    let mut unreadable = false;
    let mut reports = Vec::new();
    for path in paths {
        let shown = files::display(&path);
        let text = match fs::read(&path).map(String::from_utf8) {
            Ok(Ok(text)) => text,
            Ok(Err(_)) => {
                eprintln!("error: {shown}: not valid UTF-8");
                unreadable = true;
                continue;
            }
            Err(e) => {
                eprintln!("error: {shown}: {e}");
                unreadable = true;
                continue;
            }
        };
        let diagnostics = blade_lint::lint(&text, &config);
        reports.push(output::Report {
            path: shown,
            text,
            diagnostics,
        });
    }

    let mut out = io::stdout().lock();
    let written = match args.format {
        Format::Human => output::human(&reports, &mut out),
        Format::Json => output::json(&reports, &mut out),
        Format::Github => output::github(&reports, &mut out),
    };
    if written.and_then(|()| out.flush()).is_err() {
        return ExitCode::from(2);
    }

    let errors = reports
        .iter()
        .flat_map(|r| &r.diagnostics)
        .any(|d| d.severity == Severity::Error);
    if unreadable {
        ExitCode::from(2)
    } else if errors {
        ExitCode::from(1)
    } else {
        ExitCode::SUCCESS
    }
}

fn fail(message: &str) -> ExitCode {
    eprintln!("error: {message}");
    ExitCode::from(2)
}