Skip to main content

tmux_client/
command.rs

1//! Shell-free tmux command construction and results.
2
3use std::ffi::{OsStr, OsString};
4use std::fmt;
5use std::process::ExitStatus;
6
7use crate::{Error, Result, TmuxText};
8
9/// A redacted, human-readable command description.
10#[derive(Clone, Debug, Eq, Hash, PartialEq)]
11pub struct CommandSummary(String);
12
13impl CommandSummary {
14    /// Returns the redacted command text.
15    #[must_use]
16    pub fn as_str(&self) -> &str {
17        &self.0
18    }
19}
20
21impl fmt::Display for CommandSummary {
22    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
23        formatter.write_str(&self.0)
24    }
25}
26
27#[derive(Clone, Debug, Eq, PartialEq)]
28struct Argument {
29    value: OsString,
30    sensitive: bool,
31}
32
33/// A tmux subcommand and its arguments.
34///
35/// The tmux executable, socket, config, and color flags are supplied by
36/// [`Server`](crate::Server), not by this value.
37#[derive(Clone, Debug, Eq, PartialEq)]
38pub struct Command {
39    subcommand: OsString,
40    arguments: Vec<Argument>,
41    input: Option<TmuxText>,
42    sensitive_input: bool,
43}
44
45impl Command {
46    /// Creates a command for a tmux subcommand such as `list-sessions`.
47    #[must_use]
48    pub fn new(subcommand: impl Into<OsString>) -> Self {
49        Self {
50            subcommand: subcommand.into(),
51            arguments: Vec::new(),
52            input: None,
53            sensitive_input: false,
54        }
55    }
56
57    /// Adds a visible command argument.
58    #[must_use]
59    pub fn arg(mut self, argument: impl Into<OsString>) -> Self {
60        self.arguments.push(Argument {
61            value: argument.into(),
62            sensitive: false,
63        });
64        self
65    }
66
67    /// Adds several visible command arguments.
68    #[must_use]
69    pub fn args<I, S>(mut self, arguments: I) -> Self
70    where
71        I: IntoIterator<Item = S>,
72        S: Into<OsString>,
73    {
74        self.arguments
75            .extend(arguments.into_iter().map(|value| Argument {
76                value: value.into(),
77                sensitive: false,
78            }));
79        self
80    }
81
82    /// Adds an argument whose value is omitted from diagnostics.
83    #[must_use]
84    pub fn sensitive_arg(mut self, argument: impl Into<OsString>) -> Self {
85        self.arguments.push(Argument {
86            value: argument.into(),
87            sensitive: true,
88        });
89        self
90    }
91
92    /// Adds a conventional `-t <target>` pair.
93    #[must_use]
94    pub fn target(self, target: impl fmt::Display) -> Self {
95        self.arg("-t").arg(target.to_string())
96    }
97
98    /// Supplies byte-preserving standard input to the tmux process.
99    #[must_use]
100    pub fn input(mut self, input: impl Into<TmuxText>) -> Self {
101        self.input = Some(input.into());
102        self.sensitive_input = false;
103        self
104    }
105
106    /// Supplies standard input while marking its content sensitive.
107    #[must_use]
108    pub fn sensitive_input(mut self, input: impl Into<TmuxText>) -> Self {
109        self.input = Some(input.into());
110        self.sensitive_input = true;
111        self
112    }
113
114    /// Returns the tmux subcommand.
115    #[must_use]
116    pub fn subcommand(&self) -> &OsStr {
117        &self.subcommand
118    }
119
120    /// Returns the arguments in execution order.
121    #[must_use]
122    pub fn arguments(&self) -> impl ExactSizeIterator<Item = &OsStr> {
123        self.arguments
124            .iter()
125            .map(|argument| argument.value.as_os_str())
126    }
127
128    pub(crate) const fn standard_input(&self) -> Option<&TmuxText> {
129        self.input.as_ref()
130    }
131
132    /// Creates a redacted diagnostic description.
133    #[must_use]
134    pub fn summary(&self) -> CommandSummary {
135        let mut parts = Vec::with_capacity(self.arguments.len() + 1);
136        parts.push(self.subcommand.to_string_lossy().into_owned());
137        parts.extend(self.arguments.iter().map(|argument| {
138            if argument.sensitive {
139                "<redacted>".to_owned()
140            } else {
141                argument.value.to_string_lossy().into_owned()
142            }
143        }));
144        if self.input.is_some() {
145            parts.push(if self.sensitive_input {
146                "<stdin:redacted>".to_owned()
147            } else {
148                "<stdin>".to_owned()
149            });
150        }
151        CommandSummary(parts.join(" "))
152    }
153}
154
155/// The raw result of a completed tmux command.
156///
157/// A non-zero exit status is data at this layer. Call [`Self::ensure_success`]
158/// or use a typed operation to translate it into [`Error::CommandFailed`].
159#[derive(Clone, Debug)]
160pub struct CommandResult {
161    status: ExitStatus,
162    stdout: TmuxText,
163    stderr: TmuxText,
164    summary: CommandSummary,
165}
166
167impl CommandResult {
168    pub(crate) fn new(
169        status: ExitStatus,
170        stdout: Vec<u8>,
171        stderr: Vec<u8>,
172        summary: CommandSummary,
173    ) -> Self {
174        Self {
175            status,
176            stdout: stdout.into(),
177            stderr: stderr.into(),
178            summary,
179        }
180    }
181
182    /// Returns whether tmux exited successfully.
183    #[must_use]
184    pub fn success(&self) -> bool {
185        self.status.success()
186    }
187
188    /// Returns the operating-system exit status.
189    #[must_use]
190    pub const fn status(&self) -> ExitStatus {
191        self.status
192    }
193
194    /// Returns raw standard output.
195    #[must_use]
196    pub const fn stdout(&self) -> &TmuxText {
197        &self.stdout
198    }
199
200    /// Returns raw standard error.
201    #[must_use]
202    pub const fn stderr(&self) -> &TmuxText {
203        &self.stderr
204    }
205
206    /// Returns the redacted command summary.
207    #[must_use]
208    pub const fn summary(&self) -> &CommandSummary {
209        &self.summary
210    }
211
212    /// Iterates over standard-output lines without requiring UTF-8.
213    pub fn stdout_lines(&self) -> impl Iterator<Item = TmuxText> + '_ {
214        self.stdout
215            .as_bytes()
216            .split(|byte| *byte == b'\n')
217            .filter(|line| !line.is_empty())
218            .map(|line| TmuxText::new(line.strip_suffix(b"\r").unwrap_or(line).to_vec()))
219    }
220
221    /// Iterates over standard-error lines without requiring UTF-8.
222    pub fn stderr_lines(&self) -> impl Iterator<Item = TmuxText> + '_ {
223        self.stderr
224            .as_bytes()
225            .split(|byte| *byte == b'\n')
226            .filter(|line| !line.is_empty())
227            .map(|line| TmuxText::new(line.strip_suffix(b"\r").unwrap_or(line).to_vec()))
228    }
229
230    /// Turns a non-zero status into a typed error.
231    pub fn ensure_success(self, operation: &'static str) -> Result<Self> {
232        if self.success() {
233            Ok(self)
234        } else {
235            Err(Error::CommandFailed {
236                operation,
237                result: Box::new(self),
238            })
239        }
240    }
241}
242
243#[cfg(test)]
244mod tests {
245    use super::Command;
246
247    #[test]
248    fn redacts_sensitive_arguments() {
249        let command = Command::new("set-environment")
250            .arg("TOKEN")
251            .sensitive_arg("secret")
252            .sensitive_input("secret input");
253        assert_eq!(
254            command.summary().as_str(),
255            "set-environment TOKEN <redacted> <stdin:redacted>"
256        );
257        assert!(!command.summary().as_str().contains("secret"));
258    }
259}