use alloc::vec::Vec;
use crate::abb;
use crate::base::destination::{self, DestinationError};
use crate::base::error::Error;
use crate::base::protocol::features::Feature;
use crate::base::session::Session;
use crate::shell::v2::Shell;
fn write_shell_destination(buf: &mut [u8], args: &[&str]) -> Result<usize, DestinationError> {
destination::write_destination(buf, &[b"shell,v2,raw:cmd"], args)
}
pub async fn exec<S: Session>(
session: &mut S,
args: &[&str],
rx: &mut [u8],
) -> Result<Vec<u8>, Error<S::IoError>> {
if session.advertises(&Feature::AbbExec) == Some(true) {
return abb::exec(session, args, rx).await;
}
let dest_len = write_shell_destination(rx, args)?;
let channel = session.open(&rx[..dest_len]).await?;
let shell = Shell::new(channel, rx);
let output = shell.collect().await?;
Ok(output.stdout)
}
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>> {
if session.advertises(&Feature::Abb) == Some(true) {
return abb::open(session, args, rx).await;
}
let dest_len = write_shell_destination(rx, args)?;
let channel = session.open(&rx[..dest_len]).await?;
Ok(Shell::new(channel, rx))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn shell_destination_multiple_args() {
let mut buf = [0u8; 128];
let len = write_shell_destination(&mut buf, &["package", "list", "packages"]).unwrap();
assert_eq!(&buf[..len], b"shell,v2,raw:cmd package list packages\0");
}
#[test]
fn shell_destination_single_arg() {
let mut buf = [0u8; 128];
let len = write_shell_destination(&mut buf, &["connectivity"]).unwrap();
assert_eq!(&buf[..len], b"shell,v2,raw:cmd connectivity\0");
}
#[test]
fn shell_destination_no_args() {
let mut buf = [0u8; 128];
let len = write_shell_destination(&mut buf, &[]).unwrap();
assert_eq!(&buf[..len], b"shell,v2,raw:cmd\0");
}
#[test]
fn shell_destination_buffer_too_small() {
let mut buf = [0u8; 10];
assert_eq!(
write_shell_destination(&mut buf, &["package"]),
Err(DestinationError::TooLong)
);
}
}