tmux_lib/
server.rs

1//! Server management.
2
3use std::{collections::HashMap, time::Duration};
4
5use smol::{future, process::Command, Timer};
6
7use crate::{
8    error::{check_empty_process_output, Error},
9    Result,
10};
11
12/// Maximum time to wait for the server to become ready.
13const SERVER_READY_TIMEOUT: Duration = Duration::from_secs(5);
14
15/// Delay between readiness checks.
16const SERVER_READY_POLL_INTERVAL: Duration = Duration::from_millis(50);
17
18// ------------------------------
19// Ops
20// ------------------------------
21
22/// Start the Tmux server if needed, creating a session named `"[placeholder]"` in order to keep the server
23/// running.
24///
25/// This function waits for the server to be fully ready before returning, ensuring
26/// subsequent commands can be executed immediately.
27///
28/// It is ok-ish to already have an existing session named `"[placeholder]"`.
29pub async fn start(initial_session_name: &str) -> Result<()> {
30    let args = vec!["new-session", "-d", "-s", initial_session_name];
31
32    let output = Command::new("tmux").args(&args).output().await?;
33    check_empty_process_output(&output, "new-session")?;
34
35    // Wait for the server to be fully ready to accept commands.
36    wait_for_server_ready().await
37}
38
39/// Wait for the tmux server to be ready to accept commands.
40///
41/// This polls the server using `tmux list-sessions` until it succeeds or times out.
42async fn wait_for_server_ready() -> Result<()> {
43    let poll = async {
44        loop {
45            let output = Command::new("tmux")
46                .args(["list-sessions", "-F", "#{session_name}"])
47                .output()
48                .await?;
49
50            if output.status.success() {
51                return Ok(());
52            }
53
54            Timer::after(SERVER_READY_POLL_INTERVAL).await;
55        }
56    };
57
58    let timeout = async {
59        Timer::after(SERVER_READY_TIMEOUT).await;
60        Err(Error::UnexpectedTmuxOutput {
61            intent: "wait-for-server-ready",
62            stdout: String::new(),
63            stderr: format!(
64                "server did not become ready within {:?}",
65                SERVER_READY_TIMEOUT
66            ),
67        })
68    };
69
70    future::or(poll, timeout).await
71}
72
73/// Remove the session named `"[placeholder]"` used to keep the server alive.
74pub async fn kill_session(name: &str) -> Result<()> {
75    let exact_name = format!("={name}");
76    let args = vec!["kill-session", "-t", &exact_name];
77
78    let output = Command::new("tmux").args(&args).output().await?;
79    check_empty_process_output(&output, "kill-session")
80}
81
82/// Return the value of a Tmux option. For instance, this can be used to get Tmux's default
83/// command.
84pub async fn show_option(option_name: &str, global: bool) -> Result<Option<String>> {
85    let mut args = vec!["show-options", "-w", "-q"];
86    if global {
87        args.push("-g");
88    }
89    args.push(option_name);
90
91    let output = Command::new("tmux").args(&args).output().await?;
92    let buffer = String::from_utf8(output.stdout)?;
93    let buffer = buffer.trim_end();
94
95    if buffer.is_empty() {
96        return Ok(None);
97    }
98    Ok(Some(buffer.to_string()))
99}
100
101/// Return all Tmux options as a `std::haosh::HashMap`.
102pub async fn show_options(global: bool) -> Result<HashMap<String, String>> {
103    let args = if global {
104        vec!["show-options", "-g"]
105    } else {
106        vec!["show-options"]
107    };
108
109    let output = Command::new("tmux").args(&args).output().await?;
110    let buffer = String::from_utf8(output.stdout)?;
111    let pairs: HashMap<String, String> = buffer
112        .trim_end()
113        .split('\n')
114        .map(|s| s.split_at(s.find(' ').unwrap()))
115        .map(|(k, v)| (k, v.trim_start()))
116        .filter(|(_, v)| !v.is_empty() && v != &"''")
117        .map(|(k, v)| (k.to_string(), v.to_string()))
118        .collect();
119
120    Ok(pairs)
121}
122
123/// Return the `"default-command"` used to start a pane, falling back to `"default shell"` if none.
124///
125/// In case of bash, a `-l` flag is added.
126pub async fn default_command() -> Result<String> {
127    let all_options = show_options(true).await?;
128
129    let default_shell = all_options
130        .get("default-shell")
131        .ok_or(Error::TmuxConfig("no default-shell"))
132        .map(|cmd| cmd.to_owned())
133        .map(|cmd| {
134            if cmd.ends_with("bash") {
135                format!("-l {cmd}")
136            } else {
137                cmd
138            }
139        })?;
140
141    all_options
142        .get("default-command")
143        // .map(|cmd| {
144        //     if cmd.trim_end() == "''" {
145        //         &default_shell
146        //     } else {
147        //         cmd
148        //     }
149        // })
150        .or(Some(&default_shell))
151        .ok_or(Error::TmuxConfig("no default-command nor default-shell"))
152        .map(|cmd| cmd.to_owned())
153}