use std::error::Error;
use std::fs;
use std::process::Output;
use agentstacks::types::SubPath;
use agentstacks::types::protocol::{Blocking, HookCommand, HookKind, RUNTIME_LUA};
use tempfile::TempDir;
use crate::common::hook::{module, run_piped};
use crate::common::tree::copy_tree;
use crate::common::{fixture, skip_without_airsl};
pub(crate) struct Run<'a> {
hook: &'a str,
payload: &'a str,
blocking: Blocking,
pub(crate) kind: HookKind,
}
impl<'a> Run<'a> {
pub(crate) const fn new(hook: &'a str, payload: &'a str) -> Self {
Self {
hook,
payload,
blocking: Blocking::MayNot,
kind: HookKind::Neutral,
}
}
pub(crate) const fn may_block(mut self) -> Self {
self.blocking = Blocking::May;
self
}
}
fn translator_project(tool: &str, root: &str) -> Result<TempDir, Box<dyn Error>> {
let dir = tempfile::tempdir()?;
let at = dir.path().join(root);
fs::create_dir_all(at.join("core/hooks"))?;
fs::write(at.join("runtime.lua"), RUNTIME_LUA)?;
fs::copy(
fixture(tool, "full")
.join("expected")
.join(root)
.join("translate.lua"),
at.join("translate.lua"),
)?;
copy_tree(
&fixture(tool, "payloads").join("hooks"),
&at.join("core/hooks"),
None,
)?;
Ok(dir)
}
fn run_hook(tool: &str, root: &str, case: &Run<'_>) -> Result<Option<Output>, Box<dyn Error>> {
if skip_without_airsl()? {
return Ok(None);
}
let dir = translator_project(tool, root)?;
let argv = HookCommand::new(
SubPath::new(root)?,
module(case.hook)?,
case.blocking,
case.kind,
)
.argv();
let payload = fs::read(fixture(tool, "payloads/input").join(format!("{}.json", case.payload)))?;
Ok(Some(run_piped(&argv, dir.path(), &payload)?))
}
fn recorded(tool: &str, name: &str) -> Result<String, Box<dyn Error>> {
Ok(fs::read_to_string(
fixture(tool, "payloads/expected").join(name),
)?)
}
pub(crate) fn check(
tool: &str,
root: &str,
case: &Run<'_>,
out: &str,
err: Option<&str>,
) -> Result<(), Box<dyn Error>> {
let Some(output) = run_hook(tool, root, case)? else {
return Ok(());
};
assert_eq!(
String::from_utf8_lossy(&output.stdout),
recorded(tool, &format!("{out}.out"))?
);
let want_err = match err {
Some(name) => recorded(tool, &format!("{name}.err"))?,
None => String::new(),
};
assert_eq!(String::from_utf8_lossy(&output.stderr), want_err);
assert!(output.status.success());
Ok(())
}