1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
|
use std::process::{Command, ExitStatus, Output};
use crate::{Session, SessionSource};
pub use error::Error;
mod error;
#[derive(Debug)]
pub struct Tmux {
socket_name: String,
}
impl Tmux {
const SESSION_FORMAT: &str = r##"Session(name: "#S", #{?session_last_attached,timestamp: #{session_last_attached}#, state: Updated,timestamp: #{session_created}#, state: Connected})"##;
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 {
type Error = Error;
type Iter = Vec<Session>;
fn sessions(&self) -> Result<Self::Iter, Self::Error> {
let output = Command::new("tmux")
.arg("-L")
.arg(&self.socket_name)
.arg("list-sessions")
.arg("-F")
.arg(Self::SESSION_FORMAT)
.output()?
.stdout;
let sessions = std::str::from_utf8(&output)?
.lines()
.filter_map(|s| match ron::from_str(s) {
Ok(session) => Some(session),
Err(err) => {
tracing::warn!(%err, "Invalid session format");
None
}
})
.collect();
Ok(sessions)
}
}
|