#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub(crate) struct Request {
pub(crate) tool: String,
pub(crate) path: Option<String>,
pub(crate) cwd: Option<String>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Decision {
Allow,
Deny,
}
impl Decision {
fn label(self) -> &'static str {
match self {
Self::Allow => "allow",
Self::Deny => "deny",
}
}
}
#[must_use]
pub(crate) fn request(stdin: &str) -> Request {
Request {
tool: string_field(stdin, "tool_name").unwrap_or_default(),
path: string_field(stdin, "file_path"),
cwd: string_field(stdin, "cwd"),
}
}
fn string_field(text: &str, key: &str) -> Option<String> {
let at = text.find(&format!("\"{key}\":"))?;
let tail = text.get(at.checked_add(key.len().checked_add(3)?)?..)?;
let inner = tail.trim_start().strip_prefix('"')?;
let end = inner.find('"')?;
inner.get(..end).map(str::to_owned)
}
#[must_use]
pub(crate) fn response(d: Decision, why: &str) -> String {
let msg = if why.is_empty() {
String::new()
} else {
format!(",\"systemMessage\":\"{}\"", crate::json::escape(why))
};
format!(
"{{\"hookSpecificOutput\":{{\"permissionDecision\":\"{}\"}}{msg}}}\n",
d.label()
)
}
#[cfg(test)]
mod tests {
use super::*;
const PAYLOAD: &str = r#"{"session_id":"s1","transcript_path":"/t.jsonl",
"cwd":"/repo","permission_mode":"ask","hook_event_name":"PreToolUse",
"tool_name":"Read","tool_input":{"file_path":"/repo/big.rs"}}"#;
#[test]
fn a_pretooluse_payload_maps_to_a_request() {
assert_eq!(
request(PAYLOAD),
Request {
tool: "Read".to_owned(),
path: Some("/repo/big.rs".to_owned()),
cwd: Some("/repo".to_owned()),
}
);
}
#[test]
fn a_call_without_a_file_has_no_path() {
let bash = r#"{"tool_name":"Bash","cwd":"/repo",
"tool_input":{"command":"ls -la"}}"#;
let got = request(bash);
assert_eq!(got.tool, "Bash");
assert_eq!(got.path, None, "no file named, so none reported");
}
#[test]
fn an_unknown_field_is_ignored() {
let extra = r#"{"tool_name":"Read","brand_new_field":"whatever",
"tool_input":{"file_path":"a.rs"}}"#;
assert_eq!(request(extra).path, Some("a.rs".to_owned()));
}
#[test]
fn every_decision_renders_in_the_json() {
for (d, word) in [(Decision::Allow, "allow"), (Decision::Deny, "deny")]
{
let out = response(d, "");
assert!(out.contains(&format!("\"permissionDecision\":\"{word}\"")));
}
}
#[test]
fn a_reason_appears_only_when_there_is_one() {
assert!(!response(Decision::Allow, "").contains("systemMessage"));
let out = response(Decision::Deny, "over \"budget\"");
assert!(out.contains("systemMessage"), "{out}");
assert!(out.contains(r#"over \"budget\""#), "escaped: {out}");
}
#[test]
fn the_response_is_one_line() {
let out = response(Decision::Deny, "a reason");
assert_eq!(out.lines().count(), 1, "{out}");
assert!(out.ends_with('\n'));
}
}