use alloc::vec::Vec;
use crate::abb;
use crate::base::protocol::features::Feature;
use crate::base::session::Session;
use crate::error::Error;
use crate::shell::v2::{self as shell_v2, Shell};
const PROGRAM: &[u8] = b"cmd";
fn needs_shell(args: &[&str]) -> bool {
args.iter().any(|arg| arg.is_empty())
}
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) && !needs_shell(args) {
return abb::exec(session, args, rx).await;
}
let channel = shell_v2::open_argv(session, PROGRAM, args, rx).await?;
Ok(Shell::new(channel, rx).run_to_exit().await?.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) && !needs_shell(args) {
return abb::open(session, args, rx).await;
}
let channel = shell_v2::open_argv(session, PROGRAM, args, rx).await?;
Ok(Shell::new(channel, rx))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::base::destination::DestinationError;
use crate::base::mock::{now, one_slot, shell_frame, wrte, Mock};
use crate::base::protocol::command::Command;
use crate::shell::v2::FrameId;
use crate::Connection;
fn opened(conn: &Connection<Mock>) -> Vec<u8> {
let sent = conn.transport().sent();
let open = sent.iter().find(|(cmd, ..)| *cmd == Command::Open);
open.expect("a channel was opened").3.clone()
}
#[test]
fn exec_takes_the_shell_path_past_abb_for_an_empty_argument() {
let exit = wrte(1, &shell_frame(FrameId::Exit, &[0]));
let mut conn = one_slot("abb_exec,shell_v2", &[exit]);
let mut rx = [0u8; 64];
now(exec(&mut conn, &["set", "", "x"], &mut rx)).unwrap();
assert_eq!(opened(&conn), b"shell,v2,raw:cmd set '' x\0");
}
#[test]
fn open_takes_the_shell_path_past_abb_for_an_empty_argument() {
let mut conn = one_slot("abb,shell_v2", &[]);
let mut rx = [0u8; 64];
now(open(&mut conn, &["set", "", "x"], &mut rx))
.map(drop)
.unwrap();
assert_eq!(opened(&conn), b"shell,v2,raw:cmd set '' x\0");
}
fn write_shell_destination(buf: &mut [u8], args: &[&str]) -> Result<usize, DestinationError> {
shell_v2::write_argv_destination(buf, PROGRAM, args)
}
#[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)
);
}
}