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};
#[derive(Parser)]
#[command(name = "blade", version, arg_required_else_help = true)]
struct Cli {
#[command(subcommand)]
command: Command,
}
#[derive(Subcommand)]
enum Command {
Lint(LintArgs),
}
#[derive(Args)]
struct LintArgs {
#[arg(default_value = ".")]
paths: Vec<PathBuf>,
#[arg(long, value_enum, default_value_t = Format::Human)]
format: Format,
#[arg(long)]
config: Option<PathBuf>,
}
#[derive(Clone, Copy, ValueEnum)]
enum Format {
Human,
Json,
Github,
}
fn main() -> ExitCode {
match Cli::parse().command {
Command::Lint(args) => lint(&args),
}
}
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)
}