use super::args::{self, Args};
use super::{check, config, explain, fix, guard, init, out, stats, usage};
use crate::judge::Config;
use crate::render::{self, Format, Shape};
use std::io::Read;
use std::path::PathBuf;
use std::process::ExitCode;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Outcome {
Ok,
Violation,
Usage,
Broken,
}
impl Outcome {
#[must_use]
pub(crate) fn code(self) -> ExitCode {
match self {
Self::Ok => ExitCode::SUCCESS,
Self::Violation | Self::Broken => ExitCode::from(1),
Self::Usage => ExitCode::from(2),
}
}
}
struct Run<'a> {
args: &'a Args,
config: &'a Config,
format: Format,
verb: &'a str,
}
#[must_use]
pub fn run(args: &[String]) -> ExitCode {
match verb_of(args) {
None => usage().code(),
Some("guard") => hooked(args).code(),
Some(_) => match args::parse(args) {
Ok(read) => routed(&read, args).code(),
Err(message) => refused(named_verb(args), args, &message).code(),
},
}
}
fn named_verb(args: &[String]) -> &str {
args::verb_in(args).unwrap_or_default()
}
fn verb_of(args: &[String]) -> Option<&str> {
args.first().map(String::as_str)
}
fn hooked(args: &[String]) -> Outcome {
match args.get(1..) {
Some([only]) if only == "--help" || only == "-h" => {
out::shown(usage::GUARD, Outcome::Ok)
}
_ => guarded(),
}
}
fn routed(read: &Args, argv: &[String]) -> Outcome {
if read.has("--version") || read.has("-V") {
return version();
}
match read.verb.as_deref() {
Some(verb) if !usage::VERBS.contains(&verb) => {
failed(&usage::unknown_verb(verb))
}
_ if asks_help(read) => help(read.verb.as_deref()),
Some("guard") => guarded(),
Some(verb) => invoked(verb, argv),
None => failed(&usage::missing_verb()),
}
}
fn invoked(verb: &str, argv: &[String]) -> Outcome {
match prepared(verb, argv) {
Ok((args, config, format)) => {
let run = Run {
args: &args,
config: &config,
format,
verb,
};
dispatched(verb, &run)
}
Err(message) => refused(verb, argv, &message),
}
}
fn asks_help(read: &Args) -> bool {
read.has("--help") || read.has("-h")
}
fn prepared(
verb: &str,
argv: &[String],
) -> Result<(Args, Config, Format), String> {
prepared_at(&cwd(), verb, argv)
}
fn prepared_at(
cwd: &std::path::Path,
verb: &str,
argv: &[String],
) -> Result<(Args, Config, Format), String> {
let mut parsed = args::parse(argv)?;
arity(verb, &parsed.paths)?;
let format = format_of(&parsed)?;
if sarif_misused(verb, format) {
return Err(sarif_refused(verb));
}
let base = config::situated(cwd, &mut parsed);
let typed = |message: String| as_typed(&message, &parsed);
let config = config::load(&base, &parsed).map_err(typed)?;
config.validate().map_err(typed)?;
Ok((parsed, config, format))
}
fn as_typed(message: &str, args: &Args) -> String {
args.flags.iter().fold(message.to_owned(), |text, flag| {
let typed = flag.value.as_deref().map_or_else(
|| flag.name.to_owned(),
|value| format!("{} '{}'", flag.name, value.escape_debug()),
);
text.replace(&format!("argv[{}]", flag.index), &typed)
})
}
fn dispatched(verb: &str, run: &Run<'_>) -> Outcome {
match verb {
"check" => checked(run),
"explain" => explained(run),
"sets" => listed(run),
"init" => said(run, drafted(run)),
"fix" => fixed(run),
_ => counted(run),
}
}
fn format_of(args: &Args) -> Result<Format, String> {
match args.value("--format") {
None | Some("human") => Ok(Format::Human),
Some("json") => Ok(Format::Json),
Some("sarif") => Ok(Format::Sarif),
Some(other) => Err(format!(
"unknown format `{other}` -- choose human, json or sarif"
)),
}
}
fn arity(verb: &str, paths: &[String]) -> Result<(), String> {
let most = match verb {
"explain" => 1,
"init" => 0,
_ => return Ok(()),
};
match paths.get(most) {
Some(extra) => Err(format!(
"`{verb}` takes at most {most} path(s); `{extra}` is one too many"
)),
None => Ok(()),
}
}
fn sarif_misused(verb: &str, format: Format) -> bool {
verb != "check" && format == Format::Sarif
}
fn sarif_refused(verb: &str) -> String {
format!(
"--format sarif reports findings, and only `check` has them; \
`{verb}` takes --format human or json"
)
}
fn failed(message: &str) -> Outcome {
eprintln!("ctrm: {message}");
Outcome::Usage
}
fn failed_as(verb: &str, json: bool, message: &str) -> Outcome {
if json {
out::shown(&render::error(verb, message), Outcome::Usage);
}
failed(message)
}
fn failed_in(run: &Run<'_>, message: &str) -> Outcome {
failed_as(run.verb, run.format == Format::Json, message)
}
fn refused(verb: &str, argv: &[String], message: &str) -> Outcome {
let json = args::parse(argv).map_or_else(
|_| argv.windows(2).any(|w| w == ["--format", "json"]),
|read| read.value("--format") == Some("json"),
);
failed_as(verb, json, message)
}
fn cwd() -> PathBuf {
std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."))
}
fn checked(run: &Run<'_>) -> Outcome {
let shape = match shape_of(run) {
Ok(shape) => shape,
Err(message) => return failed_in(run, &message),
};
match check::shaped(run.config, &run.args.paths, run.format, shape) {
Ok(report) => report_of(&report),
Err(message) => failed_in(run, &message),
}
}
fn shape_of(run: &Run<'_>) -> Result<Shape, String> {
let summary = run.args.has("--summary");
let max = run.args.value("--max").map(count).transpose()?;
let refused = (summary && run.format == Format::Sarif)
|| (max.is_some() && run.format != Format::Human);
if refused {
return Err(String::from(
"--summary takes --format human or json; --max, human only",
));
}
Ok(Shape { summary, max })
}
fn count(word: &str) -> Result<usize, String> {
word.parse()
.map_err(|_| format!("--max takes a count of rows, not `{word}`"))
}
fn said(run: &Run<'_>, answer: Result<String, String>) -> Outcome {
match answer {
Ok(text) => out::shown(&text, Outcome::Ok),
Err(message) => failed_in(run, &message),
}
}
fn explained(run: &Run<'_>) -> Outcome {
let (config, paths) = (run.config, &run.args.paths);
said(
run,
match run.args.value("--as") {
Some(form) => explain::exported(config, paths, run.format, form),
None => explain::run(config, paths, run.format),
},
)
}
fn listed(run: &Run<'_>) -> Outcome {
let asked = explain::Asked {
names: &run.args.paths,
locales: run.args.has("--locales"),
containing: run.args.value("--containing"),
};
said(run, explain::sets(run.config, run.format, &asked))
}
fn fixed(run: &Run<'_>) -> Outcome {
let write = !run.args.has("--check");
match fix::run(run.config, &run.args.paths, run.format, write) {
Ok(report) => fix_report_of(&report),
Err(message) => failed_in(run, &message),
}
}
fn fix_report_of(report: &fix::Report) -> Outcome {
let outcome = reported(&report.text, report.code);
noted(&report.note);
outcome
}
fn noted(note: &str) {
if !note.is_empty() {
eprintln!("{note}");
}
}
fn counted(run: &Run<'_>) -> Outcome {
let bpe = run.args.has("--bpe");
said(
run,
stats::run(run.config, &run.args.paths, run.format, bpe),
)
}
fn guarded() -> Outcome {
let mut stdin = Vec::new();
let read = std::io::stdin().read_to_end(&mut stdin);
adapted(match read {
Ok(_) => guard::run(&stdin, &cwd()),
Err(e) => Err(format!("stdin: {e}")),
})
}
fn adapted(answer: Result<String, String>) -> Outcome {
match answer {
Ok(text) if text.is_empty() => Outcome::Ok,
Ok(text) => match out::shown(&text, Outcome::Ok) {
Outcome::Usage => Outcome::Broken,
kept => kept,
},
Err(message) => {
eprintln!("ctrm guard: {message}");
Outcome::Broken
}
}
}
fn report_of(report: &check::Report) -> Outcome {
let outcome = reported(&report.text, report.code);
noted(&report.note);
outcome
}
fn reported(text: &str, code: u8) -> Outcome {
let verdict = if code == 0 {
Outcome::Ok
} else {
Outcome::Violation
};
if text.is_empty() {
return verdict;
}
out::shown(text, verdict)
}
fn version() -> Outcome {
let name = env!("CARGO_PKG_NAME");
let line = format!("{name} {}", env!("CARGO_PKG_VERSION"));
out::shown(&line, Outcome::Ok)
}
fn help(verb: Option<&str>) -> Outcome {
let page = verb.and_then(usage::verb_help).unwrap_or(usage::USAGE);
out::shown(page, Outcome::Ok)
}
fn usage() -> Outcome {
eprintln!("{}", usage::USAGE);
Outcome::Usage
}
#[cfg(test)]
#[path = "dispatch_test.rs"]
mod tests;
fn drafted(run: &Run<'_>) -> Result<String, String> {
let print = run.args.has("--print");
let keep = run.args.has("--keep-fixable");
init::run(run.config, init::Ask { print, keep })
}