use alloc::vec::Vec;
use crate::base::channel::Channel;
use crate::base::destination::build_nul_destination;
use crate::base::error::Error;
use crate::base::protocol::features::Feature;
use crate::base::session::Session;
use crate::shell::v2::Shell;
pub async fn open_exec<'a, S: Session>(
session: &'a mut S,
args: &[&str],
) -> Result<Channel<'a, S>, Error<S::IoError>> {
session.require_feature(Feature::AbbExec)?;
let dest = build_nul_destination("abb_exec:", args)?;
session.open(&dest).await
}
pub async fn exec<S: Session>(
session: &mut S,
args: &[&str],
rx: &mut [u8],
) -> Result<Vec<u8>, Error<S::IoError>> {
let mut channel = open_exec(session, args).await?;
let mut output = Vec::new();
loop {
match channel.read(rx).await {
Ok(n) => output.extend_from_slice(&rx[..n]),
Err(Error::ChannelClosed) => break,
Err(e) => return Err(e),
}
}
let _ = channel.close().await;
Ok(output)
}
pub async fn open<'a, 'b, S: Session>(
session: &'a mut S,
args: &[&str],
rx: &'b mut [u8],
) -> Result<Shell<'a, 'b, S>, Error<S::IoError>> {
session.require_feature(Feature::Abb)?;
let dest = build_nul_destination("abb:", args)?;
let channel = session.open(&dest).await?;
Ok(Shell::new(channel, rx))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn destination_abb_exec_multiple_args() {
let dest = build_nul_destination("abb_exec:", &["package", "list", "packages"]).unwrap();
assert_eq!(dest, b"abb_exec:package\0list\0packages\0");
}
#[test]
fn destination_abb_single_arg() {
let dest = build_nul_destination("abb:", &["connectivity"]).unwrap();
assert_eq!(dest, b"abb:connectivity\0");
}
#[test]
fn destination_no_args() {
let dest = build_nul_destination("abb_exec:", &[]).unwrap();
assert_eq!(dest, b"abb_exec:\0");
}
#[test]
fn destination_rejects_nul_in_arg() {
use crate::base::error::ProtocolError;
assert_eq!(
build_nul_destination("abb_exec:", &["bad\0arg"]),
Err(ProtocolError::InvalidDestination)
);
}
}