use std::io;
use std::path::PathBuf;
use recall_hooks::{exit, foreign_memory_slug, is_memory_file, payload};
use crate::project;
pub async fn push() -> anyhow::Result<i32> {
let hook = payload::parse_post_tool_use(io::stdin().lock());
if hook.tool_input.file_path.is_empty() {
return Ok(exit::OK);
}
let triggered = PathBuf::from(&hook.tool_input.file_path);
let here = project::resolve();
if !is_memory_file(&here.memory_dir(), &triggered) {
if let Some(slug) = foreign_memory_slug(&here.memory_root(), &here.memory_dir(), &triggered)
{
eprintln!(
"recall-push: that file is memory for {slug}, not for this project, \
so nothing was pushed"
);
eprintln!(
"recall-push: standing in {}; a git worktree has its own memory directory",
here.root.display()
);
}
return Ok(exit::OK);
}
let cfg = here.config();
here.protect_device_key(&cfg, "recall-push");
let cfg = here.enroll_if_needed(cfg, "recall-push").await;
let ctx = here.hook_context_for(&cfg)?;
let result = match recall_hooks::push(&ctx, &triggered).await {
Err(err) => match err.server_error().filter(|e| e.device_gone()) {
Some(refusal) => match here.after_refusal(&cfg, "recall-push", refusal).await {
Some(cfg) => {
let ctx = here.hook_context_for(&cfg)?;
recall_hooks::push(&ctx, &triggered).await
}
None => Err(err),
},
None => Err(err),
},
ok => ok,
};
match result {
Ok(res) => {
if res.pushed.is_some() || !res.deleted.is_empty() {
eprintln!(
"recall-push: pushed {}, deleted {} for {}",
usize::from(res.pushed.is_some()),
res.deleted.len(),
ctx.project_key()
);
}
Ok(exit::OK)
}
Err(err) => {
eprintln!("recall-push: {err}");
Ok(exit::SERVER)
}
}
}
pub async fn pull() -> anyhow::Result<i32> {
let here = project::resolve();
let cfg = here.config();
here.protect_device_key(&cfg, "recall-pull");
let cfg = here.enroll_if_needed(cfg, "recall-pull").await;
if cfg.device_error.is_none()
&& cfg.device.is_none()
&& cfg.token.is_empty()
&& cfg.authkey.is_some()
{
eprintln!("recall-pull: no device key and no RECALL_TOKEN, leaving local memory untouched");
return Ok(exit::OK);
}
let ctx = match here.hook_context_for(&cfg) {
Ok(ctx) => ctx,
Err(err) => {
eprintln!("recall-pull: {err}, leaving local memory untouched");
return Ok(exit::OK);
}
};
let result = match recall_hooks::pull(&ctx).await {
Err(err) => match err.server_error().filter(|e| e.device_gone()) {
Some(refusal) => match here
.after_refusal(&cfg, "recall-pull", refusal)
.await
.and_then(|cfg| here.hook_context_for(&cfg).ok())
{
Some(ctx) => recall_hooks::pull(&ctx).await,
None => Err(err),
},
None => Err(err),
},
ok => ok,
};
match result {
Ok(res) => {
eprintln!("{}", res.describe(ctx.project_key()));
Ok(exit::OK)
}
Err(err) => {
eprintln!("recall-pull: fetch failed ({err}), leaving local memory untouched");
Ok(exit::OK)
}
}
}