1use 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
12const SERVER_READY_TIMEOUT: Duration = Duration::from_secs(5);
14
15const SERVER_READY_POLL_INTERVAL: Duration = Duration::from_millis(50);
17
18pub 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_server_ready().await
37}
38
39async 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
73pub 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
82pub 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
101pub 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
123pub 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 .or(Some(&default_shell))
151 .ok_or(Error::TmuxConfig("no default-command nor default-shell"))
152 .map(|cmd| cmd.to_owned())
153}