use std::{
io::{self, Read},
path::Path,
};
use agent_harness_adapter_core::hook::emit;
use sokf_core::{
CacheMode, Error, HarnessDirs, HarnessOptions, HarnessReport, HarnessScope, discover_root,
harness,
};
use crate::{
cli::{HarnessArgs, HarnessCommand, HarnessScopeArg},
output,
};
pub fn harness(
repo_root: Option<&Path>,
cache: CacheMode,
args: HarnessArgs,
) -> sokf_core::Result<u8> {
match args.what {
HarnessCommand::Install(args) => {
let scope = scope(args.scope);
let dirs = dirs(repo_root, scope)?;
let opts = HarnessOptions::new(names(args.names)?, scope).force(args.force);
let result = sokf_core::harness_install(&dirs, &opts)?;
print(&result, args.json)
}
HarnessCommand::Status(args) => {
let scope = scope(args.scope);
let dirs = dirs(repo_root, scope)?;
let result = sokf_core::harness_status(&dirs, &names(args.names)?, scope)?;
print(&result, args.json)
}
HarnessCommand::Diff(args) => {
let scope = scope(args.scope);
let dirs = dirs(repo_root, scope)?;
let patch = sokf_core::harness_diff(&dirs, &names(args.names)?, scope)?;
output::write_stdout(patch.as_bytes())?;
Ok(output::EXIT_OK)
}
HarnessCommand::Hook(args) => {
hook(&output::cwd()?, repo_root, cache, &args.name, &args.hook)
}
}
}
fn scope(arg: HarnessScopeArg) -> HarnessScope {
match arg {
HarnessScopeArg::Project => HarnessScope::Project,
HarnessScopeArg::User => HarnessScope::User,
HarnessScopeArg::Local => HarnessScope::Local,
}
}
fn names(names: Vec<String>) -> sokf_core::Result<Vec<String>> {
if names.is_empty() {
return Err(Error::Internal("clap requires HARNESS".into()));
}
Ok(names)
}
fn dirs(repo_root: Option<&Path>, scope: HarnessScope) -> sokf_core::Result<HarnessDirs> {
let repo = match scope {
HarnessScope::User => discover_root(&output::cwd()?, repo_root).ok(),
_ => Some(output::root(repo_root)?.1),
};
Ok(HarnessDirs {
repo,
home: std::env::home_dir(),
})
}
fn print(result: &HarnessReport, json: bool) -> sokf_core::Result<u8> {
let buf = if json {
output::json_line(result)?
} else {
result.to_text().into_bytes()
};
output::write_stdout(&buf)?;
Ok(output::EXIT_OK)
}
fn hook(
cwd: &Path,
repo_root: Option<&Path>,
cache: CacheMode,
name: &str,
event: &str,
) -> sokf_core::Result<u8> {
let call = match harness::hook_call(name, event) {
Ok(call) => call,
Err(e) => {
eprintln!("error: {e}");
return Ok(output::EXIT_ERRORS);
}
};
let mut input = String::new();
let answer = match std::io::stdin().read_to_string(&mut input) {
Err(e) => Err(Error::io("<stdin>", e)),
Ok(_) => match discover_root(cwd, repo_root) {
Err(Error::NoRepository) => Ok(harness::Answer::Allow { stderr: None }),
root => root.and_then(|root| harness::hook(&root, &call, &input, cache)),
},
};
emit(
call.harness.as_ref(),
call.event,
answer,
&mut io::stdout().lock(),
&mut io::stderr(),
)
.map_err(output::stdout_err)
}