use std::cell::RefCell;
use std::io::{Read, Write as _};
use std::path::{Path, PathBuf};
use std::process::{Child, Command, ExitStatus, Stdio};
use std::sync::mpsc;
use std::time::{Duration, Instant};
use super::{Delivery, DeliveryError};
pub(crate) const COMMAND_VAR: &str = "PLANNOTATOR_TUI_DELIVER_CMD";
pub(crate) const PATH_VAR: &str = "PLANNOTATOR_TUI_REVIEW_PATH";
pub(crate) const EXIT_BLOCKED: i32 = 75;
pub(crate) const EXIT_UNAVAILABLE: i32 = 69;
pub(crate) const TIMEOUT: Duration = Duration::from_secs(30);
const DRAIN: Duration = Duration::from_millis(200);
#[derive(Debug)]
pub(crate) struct DeliverCommand {
line: String,
path: Option<PathBuf>,
timeout: Duration,
notice: RefCell<Option<String>>,
}
impl DeliverCommand {
pub(crate) fn from_lookup(
env: impl Fn(&str) -> Option<String>,
configured: Option<&str>,
path: Option<&Path>,
) -> Option<Self> {
let blank = |line: &String| line.trim().is_empty();
let line = env(COMMAND_VAR)
.filter(|line| !blank(line))
.or_else(|| configured.map(str::to_owned).filter(|line| !blank(line)))?;
Some(Self { line, path: path.map(Path::to_path_buf), timeout: TIMEOUT, notice: RefCell::default() })
}
pub(crate) fn line(&self) -> &str {
&self.line
}
fn program(&self) -> &str {
let word = self.line.split_whitespace().find(|word| !word.contains('=')).unwrap_or("command");
let word = word.trim_matches(|c| c == '"' || c == '\'');
word.rsplit(['/', '\\']).next().filter(|name| !name.is_empty()).unwrap_or(word)
}
fn run(&self, feedback: &str) -> Result<(ExitStatus, String, String), DeliveryError> {
let mut command = shell(&self.line);
command.stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped());
if let Some(path) = &self.path {
command.env(PATH_VAR, path);
}
let mut child = command.spawn().map_err(|err| {
DeliveryError::Unavailable(format!("cannot run the delivery command {}: {err}", self.program()))
})?;
if let Some(mut stdin) = child.stdin.take() {
let text = feedback.to_owned();
std::thread::spawn(move || stdin.write_all(text.as_bytes()));
}
let stdout = drain(child.stdout.take());
let stderr = drain(child.stderr.take());
let status = wait(&mut child, self.timeout).ok_or_else(|| {
DeliveryError::Failed(anyhow::anyhow!(
"{} did not finish within {} s and was stopped",
self.program(),
self.timeout.as_secs_f32()
))
})?;
Ok((status, collect(&stdout), collect(&stderr)))
}
}
#[cfg(not(windows))]
fn shell(line: &str) -> Command {
let mut command = Command::new("sh");
command.arg("-c").arg(line);
command
}
#[cfg(windows)]
fn shell(line: &str) -> Command {
use std::os::windows::process::CommandExt as _;
let mut command = Command::new("cmd");
command.args(["/S", "/C"]).raw_arg(format!("\"{line}\""));
command
}
fn drain(pipe: Option<impl Read + Send + 'static>) -> mpsc::Receiver<Vec<u8>> {
let (tx, rx) = mpsc::channel();
if let Some(mut pipe) = pipe {
std::thread::spawn(move || {
let mut chunk = [0; 8192];
while let Ok(n @ 1..) = pipe.read(&mut chunk) {
if tx.send(chunk.get(..n).unwrap_or_default().to_vec()).is_err() {
break;
}
}
});
}
rx
}
fn collect(rx: &mpsc::Receiver<Vec<u8>>) -> String {
let mut bytes = Vec::new();
while let Ok(chunk) = rx.recv_timeout(DRAIN) {
bytes.extend(chunk);
}
String::from_utf8_lossy(&bytes).into_owned()
}
fn wait(child: &mut Child, timeout: Duration) -> Option<ExitStatus> {
let start = Instant::now();
loop {
match child.try_wait() {
Ok(Some(status)) => return Some(status),
Ok(None) if start.elapsed() < timeout => std::thread::sleep(Duration::from_millis(10)),
_ => {
let _ = child.kill();
let _ = child.wait();
return None;
}
}
}
}
fn first_line(text: &str) -> Option<String> {
text.lines().map(str::trim).find(|line| !line.is_empty()).map(str::to_owned)
}
fn outcome(
program: &str,
code: Option<i32>,
stdout: &str,
stderr: &str,
) -> Result<Option<String>, DeliveryError> {
let said = || first_line(stderr).or_else(|| first_line(stdout));
match code {
Some(0) => Ok(first_line(stdout)),
Some(EXIT_BLOCKED) => {
Err(DeliveryError::Blocked(said().unwrap_or_else(|| format!("{program} says the agent is busy"))))
}
Some(EXIT_UNAVAILABLE) => {
Err(DeliveryError::Unavailable(said().unwrap_or_else(|| format!("{program} found no agent"))))
}
Some(code) => Err(DeliveryError::Failed(match first_line(stderr) {
Some(line) => anyhow::anyhow!("{program} exited with {code}: {line}"),
None => anyhow::anyhow!("{program} exited with {code}"),
})),
None => Err(DeliveryError::Failed(anyhow::anyhow!("{program} was stopped by a signal"))),
}
}
impl Delivery for DeliverCommand {
fn describe(&self) -> String {
format!("cmd ยท {}", self.program())
}
fn is_agent(&self) -> bool {
true
}
fn deliver(&self, feedback: &str) -> Result<(), DeliveryError> {
self.notice.take();
let (status, stdout, stderr) = self.run(feedback)?;
let notice = outcome(self.program(), status.code(), &stdout, &stderr)?;
*self.notice.borrow_mut() = notice;
Ok(())
}
fn notice(&self) -> Option<String> {
self.notice.take()
}
}
#[cfg(test)]
mod tests;