summaryrefslogtreecommitdiffstats
path: root/src/tmux.rs
blob: b1f1af2f979fdb5d56c7962a025fd6791625a998 (plain)
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
use std::process::Command;

use crate::Session;

use clap::Args;
pub use error::Error;

mod error;

#[derive(Debug, Clone, Args)]
#[group(skip)]
pub struct Tmux {
    /// tmux socket-name, equivelent to `tmux -L <socket-name>`
    #[arg(short = 'L', long = "tmux_socket", default_value = "ssh")]
    pub socket: String,

    #[arg(short = 'E', long)]
    pub exclude_attached: bool,
}

impl Tmux {
    const SESSION_FORMAT: &str = r##"Session(name: "#S", state: #{?session_last_attached,Attached(#{session_last_attached}),Created(#{session_created})})"##;

    pub fn list(&self) -> Result<Vec<Session>, Error> {
        let stdout = Command::new("tmux")
            .arg("-L")
            .arg(&self.socket)
            .arg("list-sessions")
            .arg("-F")
            .arg(Self::SESSION_FORMAT)
            .output()?
            .stdout;

        std::str::from_utf8(&stdout)?
            .lines()
            .map(ron::from_str)
            .collect::<Result<_, _>>()
            .map_err(Into::into)
    }

    pub fn attached(&self) -> Result<Session, Error> {
        let stdout = Command::new("tmux")
            .arg("-L")
            .arg(&self.socket)
            .arg("display")
            .arg("-p")
            .arg(Self::SESSION_FORMAT)
            .output()?
            .stdout;

        std::str::from_utf8(&stdout)?
            .lines()
            .map(ron::from_str)
            .last()
            .transpose()?
            .ok_or(Error::NotFound)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    const SOCKET: &str = "test";

    #[test]
    #[ignore]
    fn test_tmux_list() -> Result<(), Error> {
        let names = Vec::from(["test_1", "test_2", "test_3", "test_4"]);

        for name in names.iter().cloned() {
            Command::new("tmux")
                .arg("-L")
                .arg(SOCKET)
                .arg("new-session")
                .arg("-ds")
                .arg(name)
                .status()?;
        }

        let tmux = Tmux {
            socket: SOCKET.to_owned(),
            exclude_attached: false,
        };
        let sessions: Vec<_> = tmux.list()?.into_iter().map(|s| s.name).collect();

        Command::new("tmux")
            .arg("-L")
            .arg(SOCKET)
            .arg("kill-server")
            .status()?;

        assert_eq!(names, sessions);

        Ok(())
    }
}