summaryrefslogtreecommitdiffstats
path: root/src/tmux.rs
blob: 129b4d3562fae82edbd29bd216008d6ea2e16a34 (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
use std::{collections::BTreeMap, ffi::OsStr, process::Command, str::FromStr};

use tokio::sync::mpsc::Sender;

use crate::Host;

pub async fn sessions<S>(tx: Sender<Host>, socket: S) -> Result<(), anyhow::Error>
where
    S: AsRef<OsStr>,
{
    let stdout = Command::new("tmux")
        .arg("-L")
        .arg(socket)
        .arg("list-sessions")
        .arg("-F")
        .arg("#{?session_last_attached,#{session_last_attached},#{session_created}}:#S")
        .output()?
        .stdout;

    let mut btree_map = std::str::from_utf8(&stdout)?
        .lines()
        .flat_map(|s| s.split_once(':'))
        .flat_map(|(t, s)| Some((FromStr::from_str(t).ok()?, s.to_string())))
        .collect::<BTreeMap<usize, String>>();

    let stdout = Command::new("tmux")
        .arg("-L")
        .arg("default")
        .arg("list-sessions")
        .arg("-F")
        .arg("#{?session_last_attached,#{session_last_attached},#{session_created}}:#{host}")
        .output()?
        .stdout;

    if let Some((t, s)) = std::str::from_utf8(&stdout)?
        .lines()
        .flat_map(|s| s.split_once(':'))
        .flat_map(|(t, s)| Some((FromStr::from_str(t).ok()?, s.to_string())))
        .max_by_key(|t| t.0)
    {
        btree_map.insert(t, s);
    }

    for name in btree_map.into_values() {
        tx.send(name.replace('_', ".").into()).await?;
    }

    Ok(())
}