vpf-cli 0.2.0

The `vpf` command: check plans in the Verifiable Plan Format and show them in words.
//! `vpf`: check plans in the Verifiable Plan Format and show them in words.

use std::fs;
use std::path::{Path, PathBuf};
use std::process::ExitCode;

use clap::{Parser, Subcommand};

/// Check plans in the Verifiable Plan Format (VPF) and show them in words.
#[derive(Parser)]
#[command(name = "vpf", version, about)]
struct Cli {
    #[command(subcommand)]
    command: Command,
}

#[derive(Subcommand)]
enum Command {
    /// Check plans and tell every problem. Ends with 1 when a plan may not run.
    Check {
        /// The plan files.
        #[arg(required = true)]
        files: Vec<PathBuf>,
        /// Answer in JSON.
        #[arg(long)]
        json: bool,
    },
    /// Say a plan in words: for each step, what to do, who does it and what proves it.
    Show {
        /// The plan file.
        file: PathBuf,
    },
}

fn read(file: &Path) -> Result<String, ExitCode> {
    fs::read_to_string(file).map_err(|error| {
        eprintln!("vpf: cannot read {}: {error}", file.display());
        ExitCode::from(2)
    })
}

fn print_problems(file: &Path, report: &vpf::Report) {
    let count = report.problems.len();
    let noun = if count == 1 { "problem" } else { "problems" };
    println!("{}: {count} {noun}", file.display());
    for problem in &report.problems {
        println!("  {problem}");
    }
}

fn check(files: &[PathBuf], json: bool) -> ExitCode {
    let mut answers = Vec::new();
    let mut all_run = true;
    for file in files {
        let text = match read(file) {
            Ok(text) => text,
            Err(code) => return code,
        };
        let report = vpf::check(&text);
        all_run &= report.may_run();
        if json {
            let problems: Vec<serde_json::Value> = report
                .problems
                .iter()
                .map(|problem| {
                    serde_json::json!({
                        "reason": problem.reason.as_str(),
                        "step": problem.step,
                        "message": problem.reason.sentence(),
                        "detail": problem.detail,
                    })
                })
                .collect();
            answers.push(serde_json::json!({
                "file": file.display().to_string(),
                "may_run": report.may_run(),
                "problems": problems,
            }));
        } else if report.may_run() {
            println!("{}: no problems, it may run", file.display());
        } else {
            print_problems(file, &report);
        }
    }
    if json {
        println!(
            "{}",
            serde_json::to_string_pretty(&answers).unwrap_or_default()
        );
    }
    if all_run {
        ExitCode::SUCCESS
    } else {
        ExitCode::from(1)
    }
}

fn show(file: &Path) -> ExitCode {
    let text = match read(file) {
        Ok(text) => text,
        Err(code) => return code,
    };
    let report = vpf::check(&text);
    if let (Some(plan), true) = (&report.plan, report.problems.is_empty()) {
        print!("{}", vpf::words_text(plan));
        ExitCode::SUCCESS
    } else {
        print_problems(file, &report);
        ExitCode::from(1)
    }
}

fn main() -> ExitCode {
    match Cli::parse().command {
        Command::Check { files, json } => check(&files, json),
        Command::Show { file } => show(&file),
    }
}