use std::fs;
use std::path::{Path, PathBuf};
use std::time::Instant;
use crate::cli::{CheckArgs, OutputFormat};
use crate::error::CliError;
use crate::output::{Action, FileEntry, Report};
use crate::templates::{
RenderContext, canonical_templates, render_template, template_to_output_path,
};
pub fn run(args: &CheckArgs, output: &OutputFormat) -> Result<(), CliError> {
let start = Instant::now();
let target = resolve_target(&args.path)?;
let opencode_dir = target.join(".opencode");
let manifest = crate::manifest::load(&opencode_dir)?;
let plugin_version = manifest.plugin_version.clone();
let ctx = RenderContext::with_version(&plugin_version);
let mut report = Report::new("check", &plugin_version);
let mut has_drift = false;
for &template_path in canonical_templates() {
let output_path = template_to_output_path(template_path);
if output_path.starts_with("node_modules") {
continue;
}
let dest = opencode_dir.join(output_path);
let rendered = render_template(template_path, &ctx)
.ok_or_else(|| CliError::Generic(format!("template not found: {template_path}")))?;
let expected_hash = crate::hash::sha256_hex(&rendered);
let size_bytes = rendered.len() as u64;
let (action, current_sha, expected_sha) = if !dest.exists() {
has_drift = true;
(Action::Missing, String::new(), Some(expected_hash.clone()))
} else {
let existing = fs::read(&dest)
.map_err(|e| CliError::io(dest.to_string_lossy().into_owned(), e))?;
let current_hash = crate::hash::sha256_hex(&existing);
if current_hash != expected_hash {
has_drift = true;
(Action::Modified, current_hash, Some(expected_hash.clone()))
} else {
(Action::Skipped, current_hash, None)
}
};
report.files.push(FileEntry {
path: output_path.to_string(),
action,
sha256: current_sha,
expected_sha256: expected_sha,
size_bytes,
});
if args.strict && has_drift {
report.duration_ms = start.elapsed().as_millis() as u64;
report.finalize();
emit_report(&report, output);
return Err(CliError::DriftStrict);
}
}
report.duration_ms = start.elapsed().as_millis() as u64;
report.finalize();
emit_report(&report, output);
if has_drift && !args.exit_zero {
return Err(CliError::Generic("drift detected".to_string()));
}
Ok(())
}
fn resolve_target(path: &Path) -> Result<PathBuf, CliError> {
let resolved = if path.is_absolute() {
path.to_path_buf()
} else {
std::env::current_dir()
.map_err(|e| CliError::io("current directory", e))?
.join(path)
};
if !resolved.exists() {
return Err(CliError::Io {
path: resolved.to_string_lossy().to_string(),
source: std::io::Error::new(std::io::ErrorKind::NotFound, "directory does not exist"),
});
}
let canonical = resolved
.canonicalize()
.map_err(|e| CliError::io(resolved.to_string_lossy().into_owned(), e))?;
let has_parent = path
.components()
.any(|c| c == std::path::Component::ParentDir);
if has_parent {
let cwd = std::env::current_dir().map_err(|e| CliError::io("current directory", e))?;
let cwd_canonical = cwd
.canonicalize()
.map_err(|e| CliError::io("current directory", e))?;
if !canonical.starts_with(&cwd_canonical) {
return Err(CliError::Usage(
"path traversal detected: path points outside the working directory".to_string(),
));
}
}
Ok(canonical)
}
fn emit_report(report: &Report, format: &OutputFormat) {
match format {
OutputFormat::Text => crate::output::text::print_report(report),
OutputFormat::Json => crate::output::json::print_report(report),
OutputFormat::Ndjson => crate::output::ndjson::print_report(report),
OutputFormat::Quiet => {}
}
}