use serde_json::Value;
use super::args;
use super::parse::act;
use crate::boundary::{Action, Gesture, Query};
use crate::registry::mailbox::stream::piece_of;
use crate::registry::mailbox::{Call, Completion, Post, Verb, capture_of};
pub(super) fn route(verb: &str, tail: &str) -> Result<Gesture, String> {
match verb {
"invoke" => invoke(tail, verb),
_ => complete(tail, verb),
}
}
fn invoke(tail: &str, verb: &str) -> Result<Gesture, String> {
let (client, rest) = args::first_word(tail);
let (tool, mut input) = args::first_word(&rest);
if client.is_empty() || tool.is_empty() {
return Err(format!(
"/{verb}: usage: /{verb} <client> <tool> [--cwd <dir>] <json>"
));
}
let mut cwd = None;
let (flag, rest) = args::first_word(&input);
if flag == "--cwd" {
let (dir, tail) = args::first_word(&rest);
if dir.is_empty() {
return Err(format!("/{verb}: --cwd names no directory"));
}
cwd = Some(dir);
input = tail;
}
Ok(act(Action::Route(Verb::Invoke(Call {
client,
tool,
input: document(&input, verb)?,
cwd,
}))))
}
fn complete(tail: &str, verb: &str) -> Result<Gesture, String> {
let (invocation, document) = args::first_word(tail);
if invocation.is_empty() {
return Err(format!(
"/{verb}: usage: /{verb} <invocation> [--partial] <json>"
));
}
let (flag, rest) = args::first_word(&document);
let post = if flag == "--partial" {
Post::Partial(read(&rest, verb, piece_of)?)
} else {
Post::Capture(read(&document, verb, capture_of)?)
};
Ok(act(Action::Route(Verb::Complete(Completion {
invocation,
post,
}))))
}
fn document(tail: &str, verb: &str) -> Result<Value, String> {
let text = args::required(tail, verb, "the JSON document")?;
serde_json::from_str(&text).map_err(|e| format!("/{verb}: {e}"))
}
fn read<T>(tail: &str, verb: &str, of: fn(&Value) -> Result<T, String>) -> Result<T, String> {
of(&document(tail, verb)?).map_err(|e| format!("/{verb}: {e}"))
}
pub(super) fn capture(tail: &str, verb: &str) -> Result<Gesture, String> {
let usage = || format!("/{verb}: usage: /{verb} <invocation> [<stdout bytes> <stderr bytes>]");
let words: Vec<&str> = tail.split_whitespace().collect();
let count = |word: &&str| word.parse::<u64>().map_err(|_| usage());
let (invocation, since) = match words.as_slice() {
[invocation] => (invocation, None),
[invocation, stdout, stderr] => (
invocation,
Some(crate::registry::mailbox::Offsets {
stdout: count(stdout)?,
stderr: count(stderr)?,
}),
),
_ => return Err(usage()),
};
Ok(Gesture::Ask(Query::Capture {
invocation: (*invocation).to_owned(),
since,
}))
}