Skip to main content

tmux_client/
server.rs

1//! Server configuration, command execution, discovery, and server-level operations.
2
3use std::collections::BTreeMap;
4use std::ffi::OsString;
5use std::fmt;
6use std::future::Future;
7use std::path::{Path, PathBuf};
8use std::process::Stdio;
9use std::sync::Arc;
10use std::time::Duration;
11
12use tokio::io::AsyncWriteExt;
13use tokio::process::Command as ProcessCommand;
14use tokio::sync::OnceCell;
15
16use crate::formats::{fields_for_listing, parse_rows, render_format};
17use crate::{
18    AttachedClient, Client, Command, CommandResult, Error, FormatScope, NativeFilter, ObjectKind,
19    OptionMap, OptionScope, OptionValue, Pane, PaneId, Result, Session, SessionId, SessionName,
20    SessionTarget, SparseOptionMap, TmuxText, TmuxVersion, Window, WindowId,
21};
22
23/// The tmux socket identity used by a server handle.
24#[derive(Clone, Debug, Default, Eq, PartialEq)]
25pub enum Socket {
26    /// Let tmux use its default socket.
27    #[default]
28    Default,
29    /// Select a named socket with `-L`.
30    Name(OsString),
31    /// Select an exact socket path with `-S`.
32    Path(PathBuf),
33}
34
35/// A tmux client color mode supplied on each command.
36#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
37pub enum ColorMode {
38    /// Let tmux detect color support.
39    #[default]
40    Default,
41    /// Request 88-color mode (`-8`).
42    Colors88,
43    /// Request 256-color mode (`-2`).
44    Colors256,
45}
46
47/// Immutable process and socket configuration shared by all object handles.
48#[derive(Clone, Eq, PartialEq)]
49pub struct ServerConfig {
50    executable: PathBuf,
51    socket: Socket,
52    config_file: Option<PathBuf>,
53    color_mode: ColorMode,
54    environment: BTreeMap<OsString, OsString>,
55    clear_environment: bool,
56    timeout: Duration,
57}
58
59impl ServerConfig {
60    /// Returns the configured tmux executable.
61    #[must_use]
62    pub fn executable(&self) -> &Path {
63        &self.executable
64    }
65
66    /// Returns the socket selector.
67    #[must_use]
68    pub const fn socket(&self) -> &Socket {
69        &self.socket
70    }
71
72    /// Returns the optional tmux configuration file.
73    #[must_use]
74    pub fn config_file(&self) -> Option<&Path> {
75        self.config_file.as_deref()
76    }
77
78    /// Returns the requested color mode.
79    #[must_use]
80    pub const fn color_mode(&self) -> ColorMode {
81        self.color_mode
82    }
83
84    /// Returns process-environment overrides.
85    #[must_use]
86    pub const fn environment(&self) -> &BTreeMap<OsString, OsString> {
87        &self.environment
88    }
89
90    /// Returns whether the child environment is cleared before overrides.
91    #[must_use]
92    pub const fn clears_environment(&self) -> bool {
93        self.clear_environment
94    }
95
96    /// Returns the command timeout.
97    #[must_use]
98    pub const fn timeout(&self) -> Duration {
99        self.timeout
100    }
101}
102
103impl fmt::Debug for ServerConfig {
104    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
105        formatter
106            .debug_struct("ServerConfig")
107            .field("executable", &self.executable)
108            .field("socket", &self.socket)
109            .field("config_file", &self.config_file)
110            .field("color_mode", &self.color_mode)
111            .field(
112                "environment_keys",
113                &self.environment.keys().collect::<Vec<_>>(),
114            )
115            .field("clear_environment", &self.clear_environment)
116            .field("timeout", &self.timeout)
117            .finish()
118    }
119}
120
121/// Builder for [`Server`].
122#[derive(Clone, Debug)]
123pub struct ServerBuilder {
124    config: ServerConfig,
125}
126
127impl Default for ServerBuilder {
128    fn default() -> Self {
129        Self {
130            config: ServerConfig {
131                executable: PathBuf::from("tmux"),
132                socket: Socket::Default,
133                config_file: None,
134                color_mode: ColorMode::Default,
135                environment: BTreeMap::new(),
136                clear_environment: false,
137                timeout: Duration::from_secs(30),
138            },
139        }
140    }
141}
142
143impl ServerBuilder {
144    /// Creates a builder with production defaults.
145    #[must_use]
146    pub fn new() -> Self {
147        Self::default()
148    }
149
150    /// Sets the tmux executable path.
151    #[must_use]
152    pub fn executable(mut self, executable: impl Into<PathBuf>) -> Self {
153        self.config.executable = executable.into();
154        self
155    }
156
157    /// Uses a named tmux socket.
158    #[must_use]
159    pub fn socket_name(mut self, name: impl Into<OsString>) -> Self {
160        self.config.socket = Socket::Name(name.into());
161        self
162    }
163
164    /// Uses an exact tmux socket path.
165    #[must_use]
166    pub fn socket_path(mut self, path: impl Into<PathBuf>) -> Self {
167        self.config.socket = Socket::Path(path.into());
168        self
169    }
170
171    /// Selects a socket explicitly.
172    #[must_use]
173    pub fn socket(mut self, socket: Socket) -> Self {
174        self.config.socket = socket;
175        self
176    }
177
178    /// Sets the tmux configuration file.
179    #[must_use]
180    pub fn config_file(mut self, path: impl Into<PathBuf>) -> Self {
181        self.config.config_file = Some(path.into());
182        self
183    }
184
185    /// Sets the color mode.
186    #[must_use]
187    pub const fn color_mode(mut self, color_mode: ColorMode) -> Self {
188        self.config.color_mode = color_mode;
189        self
190    }
191
192    /// Sets one child-process environment override.
193    #[must_use]
194    pub fn environment(mut self, name: impl Into<OsString>, value: impl Into<OsString>) -> Self {
195        self.config.environment.insert(name.into(), value.into());
196        self
197    }
198
199    /// Clears the inherited environment before applying overrides.
200    #[must_use]
201    pub const fn clear_environment(mut self, clear: bool) -> Self {
202        self.config.clear_environment = clear;
203        self
204    }
205
206    /// Sets the maximum duration for ordinary commands.
207    pub fn timeout(mut self, timeout: Duration) -> Result<Self> {
208        if timeout.is_zero() {
209            return Err(Error::InvalidArgument {
210                argument: "timeout",
211                message: "must be greater than zero".to_owned(),
212            });
213        }
214        self.config.timeout = timeout;
215        Ok(self)
216    }
217
218    /// Builds a cheap, cloneable server handle.
219    #[must_use]
220    pub fn build(self) -> Server {
221        Server {
222            inner: Arc::new(ServerInner {
223                config: self.config,
224                version: OnceCell::new(),
225            }),
226        }
227    }
228}
229
230pub(crate) struct ServerInner {
231    config: ServerConfig,
232    version: OnceCell<TmuxVersion>,
233}
234
235impl fmt::Debug for ServerInner {
236    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
237        formatter
238            .debug_struct("ServerInner")
239            .field("config", &self.config)
240            .finish_non_exhaustive()
241    }
242}
243
244/// A cheap handle to one tmux server configuration.
245#[derive(Clone, Debug)]
246pub struct Server {
247    pub(crate) inner: Arc<ServerInner>,
248}
249
250impl Default for Server {
251    fn default() -> Self {
252        Self::new()
253    }
254}
255
256impl Server {
257    /// Creates a handle using the `tmux` executable and default socket.
258    #[must_use]
259    pub fn new() -> Self {
260        ServerBuilder::new().build()
261    }
262
263    /// Starts configuring a server handle.
264    #[must_use]
265    pub fn builder() -> ServerBuilder {
266        ServerBuilder::new()
267    }
268
269    /// Creates a server for the socket recorded in the `TMUX` environment variable.
270    pub fn from_environment() -> Result<Self> {
271        let value = std::env::var_os("TMUX").ok_or(Error::NotInsideTmux)?;
272        let path = value
273            .to_string_lossy()
274            .split(',')
275            .next()
276            .filter(|value| !value.is_empty())
277            .map(PathBuf::from)
278            .ok_or(Error::NotInsideTmux)?;
279        Ok(Self::builder().socket_path(path).build())
280    }
281
282    /// Returns shared immutable configuration.
283    #[must_use]
284    pub fn config(&self) -> &ServerConfig {
285        &self.inner.config
286    }
287
288    fn process(&self) -> ProcessCommand {
289        let config = &self.inner.config;
290        let mut process = ProcessCommand::new(&config.executable);
291        process.kill_on_drop(true);
292        if config.clear_environment {
293            process.env_clear();
294        }
295        process.envs(&config.environment);
296        match &config.socket {
297            Socket::Default => {}
298            Socket::Name(name) => {
299                process.arg("-L").arg(name);
300            }
301            Socket::Path(path) => {
302                process.arg("-S").arg(path);
303            }
304        }
305        if let Some(path) = &config.config_file {
306            process.arg("-f").arg(path);
307        }
308        match config.color_mode {
309            ColorMode::Default => {}
310            ColorMode::Colors88 => {
311                process.arg("-8");
312            }
313            ColorMode::Colors256 => {
314                process.arg("-2");
315            }
316        }
317        process
318    }
319
320    /// Executes a command without treating a non-zero tmux exit status as an error.
321    pub async fn cmd(&self, command: Command) -> Result<CommandResult> {
322        let summary = command.summary();
323        let input = command.standard_input().cloned();
324        let mut process = self.process();
325        process
326            .arg(command.subcommand())
327            .args(command.arguments())
328            .stdin(if input.is_some() {
329                Stdio::piped()
330            } else {
331                Stdio::null()
332            })
333            .stdout(Stdio::piped())
334            .stderr(Stdio::piped());
335        #[cfg(feature = "tracing")]
336        tracing::debug!(command = %summary, "executing tmux command");
337        let mut child = process.spawn().map_err(|source| {
338            if source.kind() == std::io::ErrorKind::NotFound {
339                Error::ExecutableNotFound {
340                    executable: self.inner.config.executable.clone(),
341                }
342            } else {
343                Error::Io {
344                    operation: "spawn tmux",
345                    source,
346                }
347            }
348        })?;
349        let timeout = self.inner.config.timeout;
350        let execution = async move {
351            if let Some(input) = input {
352                let mut stdin = child.stdin.take().ok_or_else(|| Error::Io {
353                    operation: "open tmux stdin",
354                    source: std::io::Error::other("Tokio did not provide piped stdin"),
355                })?;
356                stdin
357                    .write_all(input.as_bytes())
358                    .await
359                    .map_err(|source| Error::Io {
360                        operation: "write tmux stdin",
361                        source,
362                    })?;
363                stdin.shutdown().await.map_err(|source| Error::Io {
364                    operation: "close tmux stdin",
365                    source,
366                })?;
367            }
368            child.wait_with_output().await.map_err(|source| Error::Io {
369                operation: "wait for tmux",
370                source,
371            })
372        };
373        let output = tokio::time::timeout(timeout, execution)
374            .await
375            .map_err(|_| Error::Timeout {
376                summary: summary.clone(),
377                timeout,
378            })??;
379        Ok(CommandResult::new(
380            output.status,
381            output.stdout,
382            output.stderr,
383            summary,
384        ))
385    }
386
387    pub(crate) async fn checked(
388        &self,
389        operation: &'static str,
390        command: Command,
391    ) -> Result<CommandResult> {
392        self.cmd(command).await?.ensure_success(operation)
393    }
394
395    /// Reads and caches the version reported by the configured executable.
396    pub async fn version(&self) -> Result<&TmuxVersion> {
397        self.inner
398            .version
399            .get_or_try_init(|| async {
400                let result = self.checked("read version", Command::new("-V")).await?;
401                let text = result.stdout().to_str().map_err(|source| Error::Decode {
402                    context: "tmux version",
403                    message: source.to_string(),
404                })?;
405                let version = TmuxVersion::parse(text)?;
406                version.require("tmux-client", crate::ReleaseVersion::MINIMUM)?;
407                Ok(version)
408            })
409            .await
410    }
411
412    pub(crate) async fn list_rows(
413        &self,
414        subcommand: &'static str,
415        scopes: &[FormatScope],
416        arguments: impl IntoIterator<Item = OsString>,
417        filter: Option<&NativeFilter>,
418    ) -> Result<Vec<BTreeMap<&'static str, TmuxText>>> {
419        let fields = fields_for_listing(scopes, self.version().await?);
420        let mut command = Command::new(subcommand).args(arguments);
421        if let Some(filter) = filter {
422            command = command.arg("-f").arg(filter.as_str());
423        }
424        command = command.arg("-F").arg(render_format(&fields));
425        let result = self.checked(subcommand, command).await?;
426        parse_rows(result.stdout().as_bytes(), &fields)
427    }
428
429    /// Lists sessions, preserving an error when the server is unavailable.
430    pub async fn sessions(&self) -> Result<Vec<Session>> {
431        self.sessions_filtered(None).await
432    }
433
434    /// Lists sessions with an optional native tmux filter.
435    pub async fn sessions_filtered(&self, filter: Option<&NativeFilter>) -> Result<Vec<Session>> {
436        self.list_rows("list-sessions", &[FormatScope::Session], [], filter)
437            .await?
438            .into_iter()
439            .map(|row| Session::from_row(self.clone(), row))
440            .collect()
441    }
442
443    /// Lists sessions, returning an empty collection on discovery failure.
444    pub async fn sessions_or_empty(&self) -> Vec<Session> {
445        self.sessions().await.unwrap_or_default()
446    }
447
448    /// Lists sessions with at least one attached client.
449    pub async fn attached_sessions(&self) -> Result<Vec<Session>> {
450        let mut sessions = Vec::new();
451        for session in self.sessions().await? {
452            if session
453                .snapshot()
454                .attached_clients()?
455                .is_some_and(|count| count > 0)
456            {
457                sessions.push(session);
458            }
459        }
460        Ok(sessions)
461    }
462
463    /// Resolves a session ID to a fresh snapshot.
464    pub async fn session(&self, id: SessionId) -> Result<Session> {
465        self.sessions()
466            .await?
467            .into_iter()
468            .find(|session| session.id() == id)
469            .ok_or_else(|| Error::ObjectNotFound {
470                kind: ObjectKind::Session,
471                target: id.to_string(),
472            })
473    }
474
475    /// Resolves an exact session name to a fresh snapshot.
476    pub async fn session_by_name(&self, name: &SessionName) -> Result<Session> {
477        let matches = self
478            .sessions()
479            .await?
480            .into_iter()
481            .filter(|session| session.name() == Some(name))
482            .collect::<Vec<_>>();
483        match matches.len() {
484            0 => Err(Error::ObjectNotFound {
485                kind: ObjectKind::Session,
486                target: name.to_string(),
487            }),
488            1 => matches.into_iter().next().ok_or_else(|| Error::Decode {
489                context: "session lookup",
490                message: "single match disappeared".to_owned(),
491            }),
492            count => Err(Error::MultipleObjects {
493                kind: ObjectKind::Session,
494                count,
495                query: format!("session_name == {name}"),
496            }),
497        }
498    }
499
500    /// Lists every window link. A window linked into two sessions appears twice.
501    pub async fn windows(&self) -> Result<Vec<Window>> {
502        self.windows_filtered(None).await
503    }
504
505    /// Lists window links with an optional native tmux filter.
506    pub async fn windows_filtered(&self, filter: Option<&NativeFilter>) -> Result<Vec<Window>> {
507        self.list_rows(
508            "list-windows",
509            &[FormatScope::Session, FormatScope::Window],
510            [OsString::from("-a")],
511            filter,
512        )
513        .await?
514        .into_iter()
515        .map(|row| Window::from_row(self.clone(), row))
516        .collect()
517    }
518
519    /// Lists window links, returning an empty collection on discovery failure.
520    pub async fn windows_or_empty(&self) -> Vec<Window> {
521        self.windows().await.unwrap_or_default()
522    }
523
524    /// Resolves a window ID. Fails loudly when the window has multiple links.
525    pub async fn window(&self, id: WindowId) -> Result<Window> {
526        let matches = self
527            .windows()
528            .await?
529            .into_iter()
530            .filter(|window| window.id() == id)
531            .collect::<Vec<_>>();
532        match matches.len() {
533            0 => Err(Error::ObjectNotFound {
534                kind: ObjectKind::Window,
535                target: id.to_string(),
536            }),
537            1 => matches.into_iter().next().ok_or_else(|| Error::Decode {
538                context: "window lookup",
539                message: "single match disappeared".to_owned(),
540            }),
541            count => Err(Error::MultipleObjects {
542                kind: ObjectKind::Window,
543                count,
544                query: format!("window_id == {id}; select a WindowLink instead"),
545            }),
546        }
547    }
548
549    /// Lists every pane with its parent identities.
550    pub async fn panes(&self) -> Result<Vec<Pane>> {
551        self.panes_filtered(None).await
552    }
553
554    /// Lists panes with an optional native tmux filter.
555    pub async fn panes_filtered(&self, filter: Option<&NativeFilter>) -> Result<Vec<Pane>> {
556        self.list_rows(
557            "list-panes",
558            &[FormatScope::Session, FormatScope::Window, FormatScope::Pane],
559            [OsString::from("-a")],
560            filter,
561        )
562        .await?
563        .into_iter()
564        .map(|row| Pane::from_row(self.clone(), row))
565        .collect()
566    }
567
568    /// Lists panes, returning an empty collection on discovery failure.
569    pub async fn panes_or_empty(&self) -> Vec<Pane> {
570        self.panes().await.unwrap_or_default()
571    }
572
573    /// Resolves a pane ID to a fresh snapshot.
574    pub async fn pane(&self, id: PaneId) -> Result<Pane> {
575        self.panes()
576            .await?
577            .into_iter()
578            .find(|pane| pane.id() == id)
579            .ok_or_else(|| Error::ObjectNotFound {
580                kind: ObjectKind::Pane,
581                target: id.to_string(),
582            })
583    }
584
585    /// Lists attached tmux clients.
586    pub async fn clients(&self) -> Result<Vec<Client>> {
587        self.list_rows(
588            "list-clients",
589            &[
590                FormatScope::Session,
591                FormatScope::Window,
592                FormatScope::Pane,
593                FormatScope::Client,
594            ],
595            [],
596            None,
597        )
598        .await?
599        .into_iter()
600        .map(|row| Client::from_row(self.clone(), row))
601        .collect()
602    }
603
604    /// Lists clients, returning an empty collection on discovery failure.
605    pub async fn clients_or_empty(&self) -> Vec<Client> {
606        self.clients().await.unwrap_or_default()
607    }
608
609    /// Returns whether an exact session name exists.
610    pub async fn has_session(&self, name: &SessionName) -> Result<bool> {
611        let target = format!("={name}");
612        let result = self
613            .cmd(Command::new("has-session").arg("-t").arg(target))
614            .await?;
615        Ok(result.success())
616    }
617
618    /// Kills a selected session target.
619    pub async fn kill_session(&self, target: impl Into<SessionTarget>) -> Result<()> {
620        self.checked(
621            "kill session",
622            Command::new("kill-session").target(target.into()),
623        )
624        .await
625        .map(|_| ())
626    }
627
628    /// Creates a session and hydrates its initial snapshot.
629    pub async fn new_session(&self, options: NewSession) -> Result<Session> {
630        let mut command = Command::new("new-session")
631            .arg("-P")
632            .arg("-F")
633            .arg("#{session_id}");
634        if options.detached {
635            command = command.arg("-d");
636        }
637        if options.attach_if_exists {
638            command = command.arg("-A");
639        }
640        if let Some(name) = options.name {
641            command = command.arg("-s").arg(name.to_string());
642        }
643        if let Some(window_name) = options.window_name {
644            command = command.arg("-n").arg(window_name);
645        }
646        if let Some(cwd) = options.cwd {
647            command = command.arg("-c").arg(cwd);
648        }
649        if let Some((width, height)) = options.size {
650            command = command
651                .arg("-x")
652                .arg(width.to_string())
653                .arg("-y")
654                .arg(height.to_string());
655        }
656        if let Some(group) = options.group {
657            command = command.arg("-t").arg(group.to_string());
658        }
659        for (name, value) in options.environment {
660            command =
661                command
662                    .arg("-e")
663                    .sensitive_arg(format!("{}={}", name, value.to_string_lossy()));
664        }
665        if let Some(shell_command) = options.shell_command {
666            command = command.sensitive_arg(shell_command);
667        }
668        let result = self.checked("create session", command).await?;
669        let id = single_line(result.stdout(), "new-session session ID")?.parse()?;
670        self.session(id).await
671    }
672
673    /// Creates a temporary session, runs an async operation, and always attempts cleanup.
674    pub async fn with_session<F, Fut, T>(&self, options: NewSession, operation: F) -> Result<T>
675    where
676        F: FnOnce(Session) -> Fut,
677        Fut: Future<Output = Result<T>>,
678    {
679        let session = self.new_session(options).await?;
680        let cleanup = session.clone();
681        let outcome = operation(session).await;
682        let cleanup_result = cleanup.kill().await;
683        match (outcome, cleanup_result) {
684            (Ok(value), Ok(())) => Ok(value),
685            (Ok(_), Err(source)) => Err(Error::Cleanup {
686                operation: "with_session",
687                source: Box::new(source),
688            }),
689            (Err(source), _) => Err(source),
690        }
691    }
692
693    /// Kills the tmux server. A missing server is treated as already killed.
694    pub async fn kill(&self) -> Result<()> {
695        let result = self.cmd(Command::new("kill-server")).await?;
696        if result.success() || daemon_not_running(result.stderr().as_bytes()) {
697            Ok(())
698        } else {
699            result.ensure_success("kill server").map(|_| ())
700        }
701    }
702
703    /// Returns whether the configured tmux server responds.
704    pub async fn is_alive(&self) -> Result<bool> {
705        Ok(self.cmd(Command::new("list-sessions")).await?.success())
706    }
707
708    /// Returns a server-unavailable error unless tmux responds successfully.
709    pub async fn ensure_alive(&self) -> Result<()> {
710        let result = self.cmd(Command::new("list-sessions")).await?;
711        if result.success() {
712            Ok(())
713        } else {
714            Err(Error::ServerUnavailable {
715                message: result.stderr().to_string_lossy().into_owned(),
716            })
717        }
718    }
719
720    /// Resolves `TMUX_PANE` using this server's socket configuration.
721    pub async fn pane_from_environment(&self) -> Result<Pane> {
722        let value = std::env::var("TMUX_PANE").map_err(|_| Error::NotInsideTmux)?;
723        let id = value.parse()?;
724        self.pane(id).await
725    }
726
727    /// Sources a tmux configuration file.
728    pub async fn source_file(&self, path: impl AsRef<Path>) -> Result<()> {
729        self.checked(
730            "source config",
731            Command::new("source-file").arg(path.as_ref()),
732        )
733        .await
734        .map(|_| ())
735    }
736
737    /// Sources or validates a config file with explicit flags.
738    pub async fn source_file_with(
739        &self,
740        path: impl AsRef<Path>,
741        quiet: bool,
742        parse_only: bool,
743        verbose: bool,
744    ) -> Result<()> {
745        let mut command = Command::new("source-file");
746        for (enabled, flag) in [(quiet, "-q"), (parse_only, "-n"), (verbose, "-v")] {
747            if enabled {
748                command = command.arg(flag);
749            }
750        }
751        self.checked("source config", command.arg(path.as_ref()))
752            .await
753            .map(|_| ())
754    }
755
756    /// Displays a message and returns tmux's byte-preserving expansion.
757    pub async fn display_message(&self, message: impl Into<OsString>) -> Result<TmuxText> {
758        self.checked(
759            "display message",
760            Command::new("display-message").arg("-p").arg(message),
761        )
762        .await
763        .map(|result| result.stdout().clone())
764    }
765
766    /// Shows options at a scope and optional target.
767    pub async fn show_options(
768        &self,
769        scope: OptionScope,
770        target: Option<&str>,
771    ) -> Result<OptionMap> {
772        let mut command = Command::new("show-options")
773            .args(scope.show_flags())
774            .arg("-A");
775        if let Some(target) = target {
776            command = command.arg("-t").arg(target);
777        }
778        let result = self.checked("show options", command).await?;
779        OptionMap::parse(result.stdout().as_bytes())
780    }
781
782    /// Shows indexed options and hooks as sparse arrays.
783    pub async fn show_sparse_options(
784        &self,
785        scope: OptionScope,
786        target: Option<&str>,
787    ) -> Result<SparseOptionMap> {
788        let mut command = Command::new("show-options").args(scope.show_flags());
789        if let Some(target) = target {
790            command = command.arg("-t").arg(target);
791        }
792        let result = self.checked("show sparse options", command).await?;
793        SparseOptionMap::parse(result.stdout().as_bytes())
794    }
795
796    /// Sets an option or hook value.
797    pub async fn set_option(
798        &self,
799        scope: OptionScope,
800        target: Option<&str>,
801        name: &str,
802        value: &OptionValue,
803        append: bool,
804    ) -> Result<()> {
805        validate_name("option name", name)?;
806        let mut command = Command::new("set-option").args(scope.show_flags());
807        if append {
808            command = command.arg("-a");
809        }
810        if let Some(target) = target {
811            command = command.arg("-t").arg(target);
812        }
813        command = command.arg(name).arg(value.to_os_string());
814        self.checked("set option", command).await.map(|_| ())
815    }
816
817    /// Unsets an option or hook.
818    pub async fn unset_option(
819        &self,
820        scope: OptionScope,
821        target: Option<&str>,
822        name: &str,
823    ) -> Result<()> {
824        validate_name("option name", name)?;
825        let mut command = Command::new("set-option")
826            .args(scope.show_flags())
827            .arg("-u");
828        if let Some(target) = target {
829            command = command.arg("-t").arg(target);
830        }
831        self.checked("unset option", command.arg(name))
832            .await
833            .map(|_| ())
834    }
835
836    /// Shows the global tmux environment. Removed entries have a `None` value.
837    pub async fn environment(&self) -> Result<BTreeMap<String, Option<TmuxText>>> {
838        let result = self
839            .checked(
840                "show environment",
841                Command::new("show-environment").arg("-g"),
842            )
843            .await?;
844        parse_environment(result.stdout().as_bytes())
845    }
846
847    /// Returns one global environment entry.
848    ///
849    /// The outer option distinguishes an unknown name; the inner option is
850    /// `None` when tmux records the name as explicitly removed.
851    pub async fn environment_entry(&self, name: &str) -> Result<Option<Option<TmuxText>>> {
852        validate_name("environment name", name)?;
853        Ok(self.environment().await?.remove(name))
854    }
855
856    /// Sets a global tmux environment variable.
857    pub async fn set_environment(&self, name: &str, value: impl Into<OsString>) -> Result<()> {
858        self.set_environment_with(name, value, false, false).await
859    }
860
861    /// Sets a global environment variable with format expansion or hidden storage.
862    pub async fn set_environment_with(
863        &self,
864        name: &str,
865        value: impl Into<OsString>,
866        expand_formats: bool,
867        hidden: bool,
868    ) -> Result<()> {
869        validate_name("environment name", name)?;
870        let mut command = Command::new("set-environment").arg("-g");
871        if expand_formats {
872            command = command.arg("-F");
873        }
874        if hidden {
875            command = command.arg("-h");
876        }
877        self.checked("set environment", command.arg(name).sensitive_arg(value))
878            .await
879            .map(|_| ())
880    }
881
882    /// Unsets a global tmux environment variable.
883    pub async fn unset_environment(&self, name: &str) -> Result<()> {
884        validate_name("environment name", name)?;
885        self.checked(
886            "unset environment",
887            Command::new("set-environment")
888                .arg("-g")
889                .arg("-u")
890                .arg(name),
891        )
892        .await
893        .map(|_| ())
894    }
895
896    /// Removes a global variable while retaining it in tmux's update list.
897    pub async fn remove_environment(&self, name: &str) -> Result<()> {
898        validate_name("environment name", name)?;
899        self.checked(
900            "remove environment",
901            Command::new("set-environment")
902                .arg("-g")
903                .arg("-r")
904                .arg(name),
905        )
906        .await
907        .map(|_| ())
908    }
909
910    /// Spawns an interactive tmux attachment with inherited standard streams.
911    pub fn attach(
912        &self,
913        target: impl Into<SessionTarget>,
914        read_only: bool,
915    ) -> Result<AttachedClient> {
916        let mut command = Command::new("attach-session");
917        if read_only {
918            command = command.arg("-r");
919        }
920        command = command.arg("-t").arg(target.into().to_string());
921        let summary = command.summary();
922        let mut process = self.process();
923        process
924            .arg(command.subcommand())
925            .args(command.arguments())
926            .stdin(Stdio::inherit())
927            .stdout(Stdio::inherit())
928            .stderr(Stdio::inherit());
929        let child = process.spawn().map_err(|source| Error::Io {
930            operation: "attach tmux client",
931            source,
932        })?;
933        Ok(AttachedClient::new(child, summary))
934    }
935}
936
937/// Typed arguments for creating a session.
938#[derive(Clone, Debug)]
939pub struct NewSession {
940    name: Option<SessionName>,
941    detached: bool,
942    attach_if_exists: bool,
943    window_name: Option<OsString>,
944    cwd: Option<PathBuf>,
945    size: Option<(u32, u32)>,
946    group: Option<SessionTarget>,
947    environment: BTreeMap<String, OsString>,
948    shell_command: Option<OsString>,
949}
950
951impl Default for NewSession {
952    fn default() -> Self {
953        Self {
954            name: None,
955            detached: true,
956            attach_if_exists: false,
957            window_name: None,
958            cwd: None,
959            size: None,
960            group: None,
961            environment: BTreeMap::new(),
962            shell_command: None,
963        }
964    }
965}
966
967impl NewSession {
968    /// Creates default detached-session arguments.
969    #[must_use]
970    pub fn new() -> Self {
971        Self::default()
972    }
973
974    /// Validates and sets the session name.
975    pub fn name(mut self, name: impl Into<String>) -> Result<Self> {
976        self.name = Some(SessionName::new(name)?);
977        Ok(self)
978    }
979
980    /// Chooses whether tmux should create the session detached.
981    #[must_use]
982    pub const fn detached(mut self, detached: bool) -> Self {
983        self.detached = detached;
984        self
985    }
986
987    /// Enables tmux's attach-or-create behavior (`-A`).
988    #[must_use]
989    pub const fn attach_if_exists(mut self, enabled: bool) -> Self {
990        self.attach_if_exists = enabled;
991        self
992    }
993
994    /// Sets the first window's name.
995    #[must_use]
996    pub fn window_name(mut self, name: impl Into<OsString>) -> Self {
997        self.window_name = Some(name.into());
998        self
999    }
1000
1001    /// Sets the starting directory.
1002    #[must_use]
1003    pub fn cwd(mut self, path: impl Into<PathBuf>) -> Self {
1004        self.cwd = Some(path.into());
1005        self
1006    }
1007
1008    /// Sets an initial terminal size.
1009    pub fn size(mut self, width: u32, height: u32) -> Result<Self> {
1010        if width == 0 || height == 0 {
1011            return Err(Error::InvalidArgument {
1012                argument: "session size",
1013                message: "width and height must be non-zero".to_owned(),
1014            });
1015        }
1016        self.size = Some((width, height));
1017        Ok(self)
1018    }
1019
1020    /// Adds the session to a session group.
1021    #[must_use]
1022    pub fn group(mut self, target: impl Into<SessionTarget>) -> Self {
1023        self.group = Some(target.into());
1024        self
1025    }
1026
1027    /// Sets an initial session environment variable. Values are redacted in diagnostics.
1028    pub fn environment(
1029        mut self,
1030        name: impl Into<String>,
1031        value: impl Into<OsString>,
1032    ) -> Result<Self> {
1033        let name = name.into();
1034        validate_name("environment name", &name)?;
1035        self.environment.insert(name, value.into());
1036        Ok(self)
1037    }
1038
1039    /// Sets the tmux shell command for the first pane.
1040    #[must_use]
1041    pub fn shell_command(mut self, command: impl Into<OsString>) -> Self {
1042        self.shell_command = Some(command.into());
1043        self
1044    }
1045}
1046
1047pub(crate) fn single_line<'a>(text: &'a TmuxText, context: &'static str) -> Result<&'a str> {
1048    let value = text.to_str().map_err(|source| Error::Decode {
1049        context,
1050        message: source.to_string(),
1051    })?;
1052    let value = value.trim_end_matches(['\r', '\n']);
1053    if value.is_empty() || value.contains('\n') {
1054        return Err(Error::Decode {
1055            context,
1056            message: "expected exactly one non-empty output line".to_owned(),
1057        });
1058    }
1059    Ok(value)
1060}
1061
1062pub(crate) fn validate_name(argument: &'static str, name: &str) -> Result<()> {
1063    if name.is_empty() || name.contains(['=', '\0', '\n']) {
1064        return Err(Error::InvalidArgument {
1065            argument,
1066            message: "must be non-empty and contain no '=', NUL, or newline".to_owned(),
1067        });
1068    }
1069    Ok(())
1070}
1071
1072pub(crate) fn parse_environment(bytes: &[u8]) -> Result<BTreeMap<String, Option<TmuxText>>> {
1073    let mut environment = BTreeMap::new();
1074    for line in bytes
1075        .split(|byte| *byte == b'\n')
1076        .filter(|line| !line.is_empty())
1077    {
1078        if let Some(name) = line.strip_prefix(b"-") {
1079            let name = std::str::from_utf8(name).map_err(|source| Error::Decode {
1080                context: "environment name",
1081                message: source.to_string(),
1082            })?;
1083            environment.insert(name.to_owned(), None);
1084            continue;
1085        }
1086        let Some(split) = line.iter().position(|byte| *byte == b'=') else {
1087            return Err(Error::Decode {
1088                context: "tmux environment",
1089                message: "entry had no '=' separator".to_owned(),
1090            });
1091        };
1092        let name = std::str::from_utf8(&line[..split]).map_err(|source| Error::Decode {
1093            context: "environment name",
1094            message: source.to_string(),
1095        })?;
1096        environment.insert(
1097            name.to_owned(),
1098            Some(TmuxText::new(line[split + 1..].to_vec())),
1099        );
1100    }
1101    Ok(environment)
1102}
1103
1104fn daemon_not_running(stderr: &[u8]) -> bool {
1105    contains_bytes(stderr, b"no server running")
1106        || (contains_bytes(stderr, b"error connecting to")
1107            && contains_bytes(stderr, b"No such file or directory"))
1108}
1109
1110fn contains_bytes(haystack: &[u8], needle: &[u8]) -> bool {
1111    haystack
1112        .windows(needle.len())
1113        .any(|window| window == needle)
1114}
1115
1116#[cfg(test)]
1117mod tests {
1118    use std::time::Duration;
1119
1120    use super::{Server, parse_environment};
1121
1122    #[test]
1123    fn builder_redacts_environment_values() {
1124        let server = Server::builder().environment("TOKEN", "secret").build();
1125        let debug = format!("{:?}", server.config());
1126        assert!(debug.contains("TOKEN"));
1127        assert!(!debug.contains("secret"));
1128    }
1129
1130    #[test]
1131    fn zero_timeout_is_rejected() {
1132        assert!(Server::builder().timeout(Duration::ZERO).is_err());
1133    }
1134
1135    #[test]
1136    fn environment_parser_preserves_values() {
1137        let Ok(values) = parse_environment(b"A=x=y\n-B\n") else {
1138            return;
1139        };
1140        assert_eq!(
1141            values
1142                .get("A")
1143                .and_then(Option::as_ref)
1144                .map(crate::TmuxText::as_bytes),
1145            Some(b"x=y".as_slice())
1146        );
1147        assert_eq!(values.get("B"), Some(&None));
1148    }
1149}