diff options
Diffstat (limited to 'src/tmux.rs')
-rw-r--r-- | src/tmux.rs | 81 |
1 files changed, 80 insertions, 1 deletions
diff --git a/src/tmux.rs b/src/tmux.rs index 6c53831..59420e7 100644 --- a/src/tmux.rs +++ b/src/tmux.rs @@ -1,4 +1,4 @@ -use std::process::Command; +use std::process::{Command, ExitStatus, Output}; use crate::{Session, SessionSource}; @@ -17,6 +17,85 @@ impl Tmux { pub fn new(socket_name: String) -> Self { Self { socket_name } } + + pub fn show(&self, name: &String) -> Result<Session, Error> { + let output = Command::new("tmux") + .arg("-L") + .arg(&self.socket_name) + .arg("display") + .arg("-p") + .arg("-t") + .arg(name) + .arg(Self::SESSION_FORMAT) + .output()? + .stdout; + + let output_str = std::str::from_utf8(&output)?; + + Ok(ron::from_str(output_str)?) + } + + pub fn list(&self) -> Result<Output, Error> { + Ok(Command::new("tmux") + .arg("-L") + .arg(&self.socket_name) + .arg("list-sessions") + .arg("-F") + .arg(Self::SESSION_FORMAT) + .output()?) + } + + pub fn switch(&self, host: &String) -> Result<ExitStatus, Error> { + if Command::new("tmux") + .arg("-L") + .arg(&self.socket_name) + .arg("has-session") + .arg("-t") + .arg(host) + .status()? + .success() + { + self.create(host)?; + } + + if std::env::var("TMUX").is_ok() { + self.attach(host) + } else { + self.detach_then_attach(host) + } + } + + fn create(&self, host: &String) -> Result<ExitStatus, Error> { + Ok(Command::new("tmux") + .arg("-L") + .arg(&self.socket_name) + .arg("new-session") + .arg("-ds") + .arg(host) + .arg("ssh") + .arg("-t") + .arg(host) + .arg("zsh -l -c 'tmux new -A'") + .status()?) + } + + fn attach(&self, host: &String) -> Result<ExitStatus, Error> { + Ok(Command::new("tmux") + .arg("-L") + .arg(&self.socket_name) + .arg("attach-session") + .arg("-t") + .arg(host) + .status()?) + } + + fn detach_then_attach(&self, host: &String) -> Result<ExitStatus, Error> { + Ok(Command::new("tmux") + .arg("detach") + .arg("-E") + .arg(format!("tmux -L ssh attach -t {host}")) + .status()?) + } } impl SessionSource for Tmux { |