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
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
//! This module provides a few types and functions to handle Tmux sessions.
//!
//! The main use cases are running Tmux commands & parsing Tmux session
//! information.

use std::{path::PathBuf, str::FromStr};

use async_std::process::Command;
use nom::{
    character::complete::{char, not_line_ending},
    combinator::all_consuming,
    sequence::tuple,
    IResult,
};
use serde::{Deserialize, Serialize};

use crate::{
    error::{map_add_intent, Error},
    pane::Pane,
    pane_id::{parse::pane_id, PaneId},
    parse::quoted_nonempty_string,
    session_id::{parse::session_id, SessionId},
    window::Window,
    window_id::{parse::window_id, WindowId},
    Result,
};

/// A Tmux session.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Session {
    /// Session identifier, e.g. `$3`.
    pub id: SessionId,
    /// Name of the session.
    pub name: String,
    /// Working directory of the session.
    pub dirpath: PathBuf,
}

impl FromStr for Session {
    type Err = Error;

    /// Parse a string containing tmux session status into a new `Session`.
    ///
    /// This returns a `Result<Session, Error>` as this call can obviously
    /// fail if provided an invalid format.
    ///
    /// The expected format of the tmux status is
    ///
    /// ```text
    /// $1:'pytorch':/Users/graelo/dl/pytorch
    /// $2:'rust':/Users/graelo/rust
    /// $3:'server: $~':/Users/graelo/swift
    /// $4:'tmux-hacking':/Users/graelo/tmux
    /// ```
    ///
    /// This status line is obtained with
    ///
    /// ```text
    /// tmux list-sessions -F "#{session_id}:'#{session_name}':#{session_path}"
    /// ```
    ///
    /// For definitions, look at `Session` type and the tmux man page for
    /// definitions.
    fn from_str(input: &str) -> std::result::Result<Self, Self::Err> {
        let desc = "Session";
        let intent = "#{session_id}:'#{session_name}':#{session_path}";

        let (_, sess) =
            all_consuming(parse::session)(input).map_err(|e| map_add_intent(desc, intent, e))?;

        Ok(sess)
    }
}

pub(crate) mod parse {
    use super::*;

    pub(crate) fn session(input: &str) -> IResult<&str, Session> {
        let (input, (id, _, name, _, dirpath)) = tuple((
            session_id,
            char(':'),
            quoted_nonempty_string,
            char(':'),
            not_line_ending,
        ))(input)?;

        Ok((
            input,
            Session {
                id,
                name: name.to_string(),
                dirpath: dirpath.into(),
            },
        ))
    }
}

// ------------------------------
// Ops
// ------------------------------

/// Return a list of all `Session` from the current tmux session.
pub async fn available_sessions() -> Result<Vec<Session>> {
    let args = vec![
        "list-sessions",
        "-F",
        "#{session_id}:'#{session_name}':#{session_path}",
    ];

    let output = Command::new("tmux").args(&args).output().await?;
    let buffer = String::from_utf8(output.stdout)?;

    // Each call to `Session::parse` returns a `Result<Session, _>`. All results
    // are collected into a Result<Vec<Session>, _>, thanks to `collect()`.
    let result: Result<Vec<Session>> = buffer
        .trim_end() // trim last '\n' as it would create an empty line
        .split('\n')
        .map(Session::from_str)
        .collect();

    result
}

/// Create a Tmux session (and thus a window & pane).
///
/// The new session attributes:
///
/// - the session name is taken from the passed `session`
/// - the working directory is taken from the pane's working directory.
///
pub async fn new_session(
    session: &Session,
    window: &Window,
    pane: &Pane,
    pane_command: Option<&str>,
) -> Result<(SessionId, WindowId, PaneId)> {
    let mut args = vec![
        "new-session",
        "-d",
        "-c",
        pane.dirpath.to_str().unwrap(),
        "-s",
        &session.name,
        "-n",
        &window.name,
        "-P",
        "-F",
        "#{session_id}:#{window_id}:#{pane_id}",
    ];
    if let Some(pane_command) = pane_command {
        args.push(pane_command);
    }

    let output = Command::new("tmux").args(&args).output().await?;
    let buffer = String::from_utf8(output.stdout)?;
    let buffer = buffer.trim_end();

    let desc = "new-session";
    let intent = "#{session_id}:#{window_id}:#{pane_id}";
    let (_, (new_session_id, _, new_window_id, _, new_pane_id)) = all_consuming(tuple((
        session_id,
        char(':'),
        window_id,
        char(':'),
        pane_id,
    )))(buffer)
    .map_err(|e| map_add_intent(desc, intent, e))?;

    Ok((new_session_id, new_window_id, new_pane_id))
}

#[cfg(test)]
mod tests {
    use super::Session;
    use super::SessionId;
    use crate::Result;
    use std::path::PathBuf;
    use std::str::FromStr;

    #[test]
    fn parse_list_sessions() {
        let output = vec![
            "$1:'pytorch':/Users/graelo/ml/pytorch",
            "$2:'rust':/Users/graelo/rust",
            "$3:'server: $':/Users/graelo/swift",
            "$4:'tmux-hacking':/Users/graelo/tmux",
        ];
        let sessions: Result<Vec<Session>> =
            output.iter().map(|&line| Session::from_str(line)).collect();
        let sessions = sessions.expect("Could not parse tmux sessions");

        let expected = vec![
            Session {
                id: SessionId::from_str("$1").unwrap(),
                name: String::from("pytorch"),
                dirpath: PathBuf::from("/Users/graelo/ml/pytorch"),
            },
            Session {
                id: SessionId::from_str("$2").unwrap(),
                name: String::from("rust"),
                dirpath: PathBuf::from("/Users/graelo/rust"),
            },
            Session {
                id: SessionId::from_str("$3").unwrap(),
                name: String::from("server: $"),
                dirpath: PathBuf::from("/Users/graelo/swift"),
            },
            Session {
                id: SessionId::from_str("$4").unwrap(),
                name: String::from("tmux-hacking"),
                dirpath: PathBuf::from("/Users/graelo/tmux"),
            },
        ];

        assert_eq!(sessions, expected);
    }
}