opencult 0.0.1

Discover, install and deploy free, open source tools.
use std::fs;
use std::path::{Path, PathBuf};
use std::process::ExitCode;

use clap::{Parser, Subcommand};
use opencult_core::manifest::Access;
use opencult_core::{Diagnostic, MANIFEST_FILE, Manifest};
use serde::Serialize;

#[derive(Parser)]
#[command(
    name = "opencult",
    version,
    about = "Discover, install and deploy free, open source tools."
)]
struct Cli {
    #[command(subcommand)]
    command: Command,
}

#[derive(Subcommand)]
enum Command {
    /// Check opencult.toml manifests: a file, a listing directory, or a whole registry
    Validate {
        #[arg(default_value = ".")]
        paths: Vec<PathBuf>,
        /// Print results as JSON
        #[arg(long)]
        json: bool,
    },
    /// Print the JSON Schema for opencult.toml
    Schema,
}

fn main() -> ExitCode {
    match Cli::parse().command {
        Command::Validate { paths, json } => validate(&paths, json),
        Command::Schema => {
            println!(
                "{}",
                serde_json::to_string_pretty(&opencult_core::json_schema())
                    .expect("schema serializes")
            );
            ExitCode::SUCCESS
        }
    }
}

#[derive(Serialize)]
struct Report {
    file: PathBuf,
    valid: bool,
    diagnostics: Vec<Diagnostic>,
}

fn validate(paths: &[PathBuf], json: bool) -> ExitCode {
    let mut reports = Vec::new();
    for path in paths {
        let mut files = Vec::new();
        if let Err(e) = collect(path, &mut files) {
            reports.push(Report {
                file: path.clone(),
                valid: false,
                diagnostics: vec![Diagnostic::error("", e)],
            });
            continue;
        }
        if files.is_empty() {
            reports.push(Report {
                file: path.clone(),
                valid: false,
                diagnostics: vec![Diagnostic::error("", format!("no {MANIFEST_FILE} found"))],
            });
        }
        for file in files {
            reports.push(check_file(&file));
        }
    }

    let failed = reports.iter().filter(|r| !r.valid).count();
    if json {
        println!(
            "{}",
            serde_json::to_string_pretty(&reports).expect("report serializes")
        );
    } else {
        for r in &reports {
            println!("{} {}", if r.valid { "✓" } else { "✗" }, r.file.display());
            for d in &r.diagnostics {
                println!("    {d}");
            }
        }
        println!("\n{} checked, {} failed", reports.len(), failed);
    }
    if failed == 0 {
        ExitCode::SUCCESS
    } else {
        ExitCode::FAILURE
    }
}

fn check_file(file: &Path) -> Report {
    let src = match fs::read_to_string(file) {
        Ok(s) => s,
        Err(e) => {
            return Report {
                file: file.into(),
                valid: false,
                diagnostics: vec![Diagnostic::error("", e.to_string())],
            };
        }
    };
    let (manifest, mut diagnostics) = opencult_core::check(&src);
    if let Some(m) = &manifest {
        diagnostics.extend(file_checks(m, file));
    }
    let valid = !diagnostics.iter().any(Diagnostic::is_error);
    Report {
        file: file.into(),
        valid,
        diagnostics,
    }
}

/// Checks that need the filesystem, so they live here rather than in core (which also runs as WASM).
fn file_checks(m: &Manifest, file: &Path) -> Vec<Diagnostic> {
    let mut d = Vec::new();
    let dir = file.parent().map(Path::to_path_buf).unwrap_or_default();
    let dir = fs::canonicalize(&dir).unwrap_or(dir);
    if let Some(name) = dir.file_name().and_then(|n| n.to_str())
        && name != m.listing.id
    {
        d.push(Diagnostic::warning(
            "listing.id",
            format!(
                "`{}` doesn't match its directory `{name}`; in the registry they must match",
                m.listing.id
            ),
        ));
    }
    for (i, a) in m.access.iter().enumerate() {
        if let Access::Compose { file: f } = a
            && !dir.join(f).is_file()
        {
            d.push(Diagnostic::error(
                format!("access[{i}].file"),
                format!("`{f}` not found next to {MANIFEST_FILE}"),
            ));
        }
    }
    d
}

fn collect(path: &Path, out: &mut Vec<PathBuf>) -> Result<(), String> {
    if path.is_file() {
        out.push(path.into());
        return Ok(());
    }
    if !path.is_dir() {
        return Err(format!("{} does not exist", path.display()));
    }
    let direct = path.join(MANIFEST_FILE);
    if direct.is_file() {
        out.push(direct);
        return Ok(());
    }
    walk(path, 0, out).map_err(|e| e.to_string())
}

fn walk(dir: &Path, depth: usize, out: &mut Vec<PathBuf>) -> std::io::Result<()> {
    const SKIP: &[&str] = &[".git", "target", "node_modules"];
    if depth > 4 {
        return Ok(());
    }
    let mut entries: Vec<PathBuf> = fs::read_dir(dir)?
        .filter_map(Result::ok)
        .map(|e| e.path())
        .collect();
    entries.sort();
    for p in entries {
        let skip = p
            .file_name()
            .and_then(|n| n.to_str())
            .is_some_and(|n| SKIP.contains(&n));
        if !p.is_dir() || skip {
            continue;
        }
        let manifest = p.join(MANIFEST_FILE);
        if manifest.is_file() {
            out.push(manifest);
        } else {
            walk(&p, depth + 1, out)?;
        }
    }
    Ok(())
}