use super::{
agy,
context::Context,
edit::{Edit, same},
files::{self, Failure},
hooks, owned, receipt,
refresh_parts::{Change, Part},
targets::{self, Target},
};
use serde_json::{Value, json};
pub const NAME: &str = "neosian";
const TEMPLATE: &str = include_str!(concat!(env!("NEOSIAN_ASSETS"), "/clients/agy-hooks.json"));
const PLACEHOLDER: &str = "__NEOSIAN_RECORD_COMMAND__";
fn filled(value: &Value, command: &str) -> Value {
match value {
Value::String(text) if text == PLACEHOLDER => json!(command),
Value::Array(items) => Value::Array(items.iter().map(|v| filled(v, command)).collect()),
Value::Object(members) => Value::Object(
members
.iter()
.map(|(k, v)| (k.clone(), filled(v, command)))
.collect(),
),
other => other.clone(),
}
}
pub fn group(command: &str) -> Value {
filled(
&serde_json::from_str(TEMPLATE).expect("agy-hooks.json is JSON"),
command,
)
}
fn commands(hook: &Value) -> Vec<&str> {
hook.as_object()
.into_iter()
.flatten()
.filter_map(|(_, handlers)| handlers.as_array())
.flatten()
.flat_map(hooks::commands)
.collect()
}
pub fn installed(target: &Target) -> Option<Vec<String>> {
let (_, document) = agy::load(&target.path).ok()?;
let command = commands(document.get(NAME)?)
.into_iter()
.find(|c| hooks::carries(c))?;
shlex::split(command)
}
fn ours(target: &Target, hook: &Value) -> bool {
let pointer = super::rename::jsonedit::join(&[NAME]);
let lines = commands(hook);
receipt::owns_in(&targets::book(target), &target.path, &pointer, hook)
|| (!lines.is_empty() && lines.iter().all(|c| hooks::carries(c)))
}
fn with_group(target: &Target, hook: &Value) -> Result<(Edit, Value), Failure> {
let (prior, mut document) = agy::load(&target.path)?;
let shown = target.path.display();
if let Some(found) = document.get(NAME)
&& !ours(target, found)
{
let message =
format!("the hook name neosian in {shown} is taken by another program's hook");
return Err(Failure::new(
message,
"rename that hook, then run setup again",
));
}
let members = document.as_object().expect("a JSON object");
if let Some((name, _)) = members
.iter()
.find(|(name, hook)| *name != NAME && commands(hook).iter().any(|c| hooks::carries(c)))
{
let message = format!(
"{shown} already runs neosian record under the hook name {name}; both would record"
);
return Err(Failure::new(
message,
"remove that hook's neosian record line, then run setup again",
));
}
let mut written = document
.get(NAME)
.and_then(Value::as_object)
.cloned()
.unwrap_or_default();
for (event, handlers) in hook.as_object().expect("the template is an object") {
written.insert(event.clone(), handlers.clone());
}
document[NAME] = Value::Object(written.clone());
let text = files::pretty(&document);
let path = target.path.clone();
Ok((
Edit {
path,
read: prior,
text,
},
Value::Object(written),
))
}
fn without(target: &Target) -> Result<Option<Edit>, Failure> {
let (prior, mut document) = agy::load(&target.path)?;
if let Some(found) = document.get(NAME)
&& !ours(target, found)
{
let message = format!(
"the neosian hook in {} also holds hooks that are not neosian's, so it is not moved",
target.path.display()
);
return Err(Failure::new(
message,
"remove the neosian hook there by hand, then run setup again",
));
}
let removed = document
.as_object_mut()
.and_then(|members| members.shift_remove(NAME));
let path = target.path.clone();
Ok(removed.map(|_| Edit {
path,
read: prior,
text: files::pretty(&document),
}))
}
pub fn install(
target: &Target,
context: &Context,
command: &str,
write: bool,
) -> Result<Value, Failure> {
files::evidence(target)?;
let (change, hook) = with_group(target, &group(command))?;
let level = if target.level == "user" {
"project"
} else {
"user"
};
let other = targets::hooks(&target.client, context, level);
let mut displaced = None;
if !same(context, &other.path, &target.path) && installed(&other).is_some() {
if target.level == "project" {
let message = format!(
"Antigravity CLI already carries the neosian hooks at the user level ({}); both would record",
other.path.display()
);
return Err(Failure::new(
message,
"keep the user hooks, or remove the neosian hook there by hand",
));
}
displaced = without(&other)?;
}
let created = write && !target.path.exists();
if write {
owned::atomically(|| {
change.write()?;
if let Some(displaced) = &displaced {
displaced.write()?;
}
let pointer = super::rename::jsonedit::join(&[NAME]);
receipt::record(&target.client, context, &target.path, &pointer, &hook)
})?;
}
Ok(
json!({"success": true, "client": target.client, "label": target.label, "level": target.level,
"config_path": target.path, "hooks": hook, "plugin": null, "command": command,
"displaced": displaced.map(|edit| edit.path), "written": write, "created": created,
"trust_hint": null}),
)
}
pub fn refresh(part: Part, target: &Target, argv: &[String]) -> Part {
let (read, mut document) = match agy::load(&target.path) {
Ok(loaded) => loaded,
Err(failure) => return part.refused(&failure),
};
let Some(present) = document.get_mut(NAME).and_then(Value::as_object_mut) else {
return part.left_alone("the neosian hook is not a JSON object; fix it by hand");
};
let command = commands(&Value::Object(present.clone()))
.into_iter()
.find(|c| hooks::carries(c))
.map(str::to_owned)
.unwrap_or_else(|| super::context::shell_join(argv));
let wanted = group(&command);
let mut changed = false;
for (event, handlers) in wanted.as_object().expect("the template is an object") {
if !present.contains_key(event) {
present.insert(event.clone(), handlers.clone());
changed = true;
}
}
if !changed {
return part;
}
part.update(Change::Json(document, false), read)
.guarded(std::slice::from_ref(&target.path))
}