summaryrefslogtreecommitdiffstats
path: root/src/tmux.rs
blob: 559242ba3a682683f9a3bbb8cd7bbe085a6bac66 (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
use std::{ffi::OsString, path::PathBuf, process::Command, time::Duration};

use crate::{parser::Parser, project::Project};

use self::error::Error;

pub mod error;

#[derive(Debug)]
pub struct Tmux;

impl Tmux {
    pub fn sessions() -> Result<Vec<PathBuf>, Error> {
        let stdout = Command::new("tmux")
            .arg("list-sessions")
            .arg("-F")
            .arg("#{session_path}")
            .output()?
            .stdout;

        Ok(std::str::from_utf8(&stdout)?
            .lines()
            .map(Into::into)
            .collect())
    }

    pub fn get_session(&self, path_buf: PathBuf) -> Result<Project, Error> {
        let mut filter = OsString::from("#{==:#{session_path},");
        filter.push(path_buf.as_os_str());
        filter.push("}");

        // tmux list-sessions -f '#{==:#{session_path},/home/tobyv/src/projectr}'
        let stdout = Command::new("tmux")
            .arg("list-sessions")
            .arg("-F")
            .arg("#{session_path},#{session_last_attached},#{session_created}")
            .arg("-f")
            .arg(filter)
            .output()?
            .stdout;

        std::str::from_utf8(&stdout)?
            .lines()
            .map(Self::parse_project)
            .inspect(|res| {
                if let Err(err) = res {
                    tracing::warn!(%err, "Skipping invalid format")
                }
            })
            .flatten()
            .max()
            .ok_or(Error::NotFound)
    }

    fn parse_project<T: AsRef<str>>(fmt_str: T) -> Result<Project, Error> {
        let mut split = fmt_str.as_ref().split(',');

        let path_buf = split
            .next()
            .ok_or(Error::PathFormat(fmt_str.as_ref().to_string()))?
            .into();

        let timestamp = split
            .next()
            .ok_or(Error::TimestampFormat(fmt_str.as_ref().to_string()))?
            .parse()
            .map(Duration::from_secs)?;

        Ok(Project {
            timestamp,
            path_buf,
        })
    }
}

impl Parser for Tmux {
    type Error = Error;

    fn parse(&self, path_buf: PathBuf) -> Result<Project, Self::Error> {
        self.get_session(path_buf)
    }
}