use std::{
io,
path::{Path, PathBuf},
};
use agent_harness_adapter_core::cli;
use serde::Serialize;
use sokf_core::{Error, RepoRoot, discover_root};
pub use agent_harness_adapter_core::cli::{EXIT_ERRORS, EXIT_FAILURE, EXIT_OK};
pub fn write_stdout(bytes: &[u8]) -> sokf_core::Result<()> {
cli::write_stdout(bytes).map_err(stdout_err)
}
pub fn stdout_err(e: io::Error) -> Error {
Error::io("<stdout>", e)
}
pub fn print_schema(output: sokf_core::Output) -> sokf_core::Result<u8> {
write_stdout(output.schema_text().as_bytes())?;
Ok(EXIT_OK)
}
pub fn json_line(value: &impl Serialize) -> sokf_core::Result<Vec<u8>> {
cli::json_line(value).map_err(|e| Error::Internal(e.to_string()))
}
pub fn cwd() -> sokf_core::Result<PathBuf> {
std::env::current_dir().map_err(|e| Error::io(".", e))
}
pub fn root(repo_root: Option<&Path>) -> sokf_core::Result<(PathBuf, RepoRoot)> {
let cwd = cwd()?;
let root = discover_root(&cwd, repo_root)?;
Ok((cwd, root))
}
pub fn required(value: Option<String>, name: &str) -> sokf_core::Result<String> {
value.ok_or_else(|| Error::Internal(format!("clap requires {name}")))
}
#[cfg(test)]
mod tests {
use super::*;
use agent_harness_adapter_core::cli::is_broken_pipe;
#[test]
fn broken_pipe_is_the_only_error_treated_as_clean() {
let epipe = stdout_err(io::Error::new(io::ErrorKind::BrokenPipe, "Broken pipe"));
assert!(is_broken_pipe(&epipe));
assert!(epipe.to_string().contains("<stdout>"), "{epipe}");
for kind in [
io::ErrorKind::PermissionDenied,
io::ErrorKind::NotFound,
io::ErrorKind::WriteZero,
] {
let e = stdout_err(io::Error::new(kind, "nope"));
assert!(!is_broken_pipe(&e), "{kind:?} must not be swallowed");
}
assert!(!is_broken_pipe(&Error::NoRepository));
}
#[test]
fn write_stdout_round_trips_bytes() {
assert!(write_stdout(b"sokf\n").is_ok());
assert!(write_stdout(b"").is_ok());
}
}