use std::path::PathBuf;
use teter_common::command::{Command, Outcome};
#[derive(clap::Args)]
pub struct LsArgs {
machine: String,
#[arg(long)]
ca_cert: Option<PathBuf>,
}
#[derive(clap::Args)]
pub struct NewArgs {
target: String,
#[arg(long)]
ca_cert: Option<PathBuf>,
}
fn split(target: &str) -> std::io::Result<(&str, &str)> {
target
.split_once(':')
.filter(|(machine, session)| !machine.is_empty() && !session.is_empty())
.ok_or_else(|| {
std::io::Error::new(
std::io::ErrorKind::InvalidInput,
format!("{target:?} is not machine:session"),
)
})
}
async fn run(
machine: &str,
ca_cert: Option<PathBuf>,
command: Command,
) -> std::io::Result<Outcome> {
let (mut channel, keys) = crate::sessions::command_channel(machine, ca_cert).await?;
channel.run(&keys, command).await
}
fn done(outcome: Outcome) -> std::io::Result<()> {
match outcome {
Outcome::Done => Ok(()),
Outcome::Failed { reason } => Err(std::io::Error::other(reason)),
Outcome::Sessions { .. } => Err(std::io::Error::other("the machine answered a list")),
}
}
fn ls_line(
session: &teter_common::command::SessionInfo,
clients: &std::collections::HashMap<String, u32>,
) -> String {
if !session.running {
return format!("{}\tstopped\t-\t-", session.name);
}
let clients = clients.get(&session.id).map_or_else(
|| "-".to_owned(),
|count| {
let noun = if *count == 1 { "client" } else { "clients" };
format!("{count} {noun}")
},
);
let size = session.size.map_or_else(
|| "-".to_owned(),
|(columns, rows)| format!("{columns}x{rows}"),
);
format!("{}\trunning\t{clients}\t{size}", session.name)
}
pub async fn ls(args: LsArgs) -> std::io::Result<()> {
let (mut channel, keys, clients) =
crate::sessions::command_channel_and_clients(&args.machine, args.ca_cert).await?;
match channel.run(&keys, Command::List).await? {
Outcome::Sessions { sessions } => {
for session in sessions {
println!("{}", ls_line(&session, &clients));
}
Ok(())
}
Outcome::Failed { reason } => Err(std::io::Error::other(reason)),
Outcome::Done => Err(std::io::Error::other("the machine answered no list")),
}
}
pub async fn new(args: NewArgs) -> std::io::Result<()> {
let (machine, session) = split(&args.target)?;
let command = Command::New {
name: session.to_owned(),
};
let (mut channel, keys) =
crate::sessions::command_channel_for_new(machine, args.ca_cert).await?;
done(channel.run(&keys, command).await?)?;
println!("created {machine}:{session}");
Ok(())
}
pub async fn kill(target: &str, ca_cert: Option<PathBuf>) -> std::io::Result<()> {
let (machine, session) = split(target)?;
let command = Command::Kill {
name: session.to_owned(),
};
match run(machine, ca_cert, command).await? {
Outcome::Failed { reason } if reason.starts_with("no session named") => {
return Err(std::io::Error::other(format!(
"{machine} has no session named {session:?} (see `teter ls {machine}`)"
)));
}
outcome @ (Outcome::Done | Outcome::Sessions { .. } | Outcome::Failed { .. }) => {
done(outcome)?;
}
}
println!("ended {machine}:{session}");
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use teter_common::command::SessionInfo;
fn info(running: bool, size: Option<(u16, u16)>) -> SessionInfo {
SessionInfo {
name: "main".to_owned(),
id: "c1".to_owned(),
running,
size,
}
}
#[test]
fn an_ls_line_keeps_its_columns_whatever_is_known() {
let mut clients = std::collections::HashMap::new();
assert_eq!(ls_line(&info(true, None), &clients), "main\trunning\t-\t-");
assert_eq!(ls_line(&info(false, None), &clients), "main\tstopped\t-\t-");
clients.insert("c1".to_owned(), 1);
assert_eq!(
ls_line(&info(true, Some((80, 24))), &clients),
"main\trunning\t1 client\t80x24"
);
clients.insert("c1".to_owned(), 2);
assert_eq!(
ls_line(&info(true, None), &clients),
"main\trunning\t2 clients\t-"
);
}
}