Skip to main content

tmux_client/
options.rs

1//! Uniform option, hook, and sparse-array representations.
2
3use std::collections::BTreeMap;
4use std::ffi::OsString;
5
6use crate::{Error, OptionErrorKind, Result, TmuxText};
7
8/// The scope used by tmux option commands.
9#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
10pub enum OptionScope {
11    /// Server-global options (`set-option -s`).
12    Server,
13    /// Global defaults for session options (`set-option -g`).
14    GlobalSession,
15    /// Session options.
16    Session,
17    /// Global defaults for window options (`set-option -gw`).
18    GlobalWindow,
19    /// Window options (`set-window-option`).
20    Window,
21    /// Pane options (`set-option -p`).
22    Pane,
23}
24
25impl OptionScope {
26    pub(crate) fn show_flags(self) -> &'static [&'static str] {
27        match self {
28            Self::Server => &["-s"],
29            Self::GlobalSession => &["-g"],
30            Self::Session => &[],
31            Self::GlobalWindow => &["-g", "-w"],
32            Self::Window => &["-w"],
33            Self::Pane => &["-p"],
34        }
35    }
36}
37
38/// A value accepted by tmux's option and environment commands.
39#[derive(Clone, Debug, Eq, PartialEq)]
40pub enum OptionValue {
41    /// A tmux on/off flag.
42    Flag(bool),
43    /// A signed numeric value.
44    Number(i64),
45    /// Byte-preserving textual data.
46    Text(TmuxText),
47}
48
49impl OptionValue {
50    pub(crate) fn to_os_string(&self) -> OsString {
51        match self {
52            Self::Flag(value) => OsString::from(if *value { "on" } else { "off" }),
53            Self::Number(value) => OsString::from(value.to_string()),
54            Self::Text(value) => value.to_os_string(),
55        }
56    }
57
58    /// Returns the value as a boolean when tmux encoded a known flag value.
59    #[must_use]
60    pub fn as_flag(&self) -> Option<bool> {
61        match self {
62            Self::Flag(value) => Some(*value),
63            Self::Text(value) if value.as_bytes() == b"on" || value.as_bytes() == b"1" => {
64                Some(true)
65            }
66            Self::Text(value) if value.as_bytes() == b"off" || value.as_bytes() == b"0" => {
67                Some(false)
68            }
69            Self::Number(_) | Self::Text(_) => None,
70        }
71    }
72
73    /// Returns a signed number when one is available.
74    pub fn as_number(&self) -> Result<Option<i64>> {
75        match self {
76            Self::Number(value) => Ok(Some(*value)),
77            Self::Text(value) => {
78                let Ok(value) = value.to_str() else {
79                    return Ok(None);
80                };
81                Ok(value.parse().ok())
82            }
83            Self::Flag(_) => Ok(None),
84        }
85    }
86
87    /// Returns the byte-preserving textual representation when stored as text.
88    #[must_use]
89    pub fn as_text(&self) -> Option<&TmuxText> {
90        match self {
91            Self::Text(value) => Some(value),
92            Self::Flag(_) | Self::Number(_) => None,
93        }
94    }
95}
96
97impl From<bool> for OptionValue {
98    fn from(value: bool) -> Self {
99        Self::Flag(value)
100    }
101}
102
103impl From<i64> for OptionValue {
104    fn from(value: i64) -> Self {
105        Self::Number(value)
106    }
107}
108
109impl From<&str> for OptionValue {
110    fn from(value: &str) -> Self {
111        Self::Text(value.into())
112    }
113}
114
115impl From<String> for OptionValue {
116    fn from(value: String) -> Self {
117        Self::Text(value.into())
118    }
119}
120
121impl From<TmuxText> for OptionValue {
122    fn from(value: TmuxText) -> Self {
123        Self::Text(value)
124    }
125}
126
127/// A deterministic map of tmux option names to values.
128#[derive(Clone, Debug, Default, Eq, PartialEq)]
129pub struct OptionMap(BTreeMap<String, OptionValue>);
130
131impl OptionMap {
132    /// Creates an empty map.
133    #[must_use]
134    pub const fn new() -> Self {
135        Self(BTreeMap::new())
136    }
137
138    /// Returns an option by name.
139    #[must_use]
140    pub fn get(&self, name: &str) -> Option<&OptionValue> {
141        self.0.get(name)
142    }
143
144    /// Inserts an option value.
145    pub fn insert(
146        &mut self,
147        name: impl Into<String>,
148        value: impl Into<OptionValue>,
149    ) -> Option<OptionValue> {
150        self.0.insert(name.into(), value.into())
151    }
152
153    /// Iterates in lexical option-name order.
154    pub fn iter(&self) -> impl Iterator<Item = (&str, &OptionValue)> {
155        self.0.iter().map(|(name, value)| (name.as_str(), value))
156    }
157
158    /// Returns the number of entries.
159    #[must_use]
160    pub fn len(&self) -> usize {
161        self.0.len()
162    }
163
164    /// Returns whether the map is empty.
165    #[must_use]
166    pub fn is_empty(&self) -> bool {
167        self.0.is_empty()
168    }
169
170    pub(crate) fn parse(bytes: &[u8]) -> Result<Self> {
171        let mut map = Self::new();
172        for line in bytes
173            .split(|byte| *byte == b'\n')
174            .filter(|line| !line.is_empty())
175        {
176            let split = line
177                .iter()
178                .position(|byte| *byte == b' ')
179                .unwrap_or(line.len());
180            let name = std::str::from_utf8(&line[..split]).map_err(|source| Error::Option {
181                kind: OptionErrorKind::Parse,
182                message: format!("option name is not UTF-8: {source}"),
183            })?;
184            let value_start = usize::min(split.saturating_add(1), line.len());
185            map.insert(name, TmuxText::new(line[value_start..].to_vec()));
186        }
187        Ok(map)
188    }
189}
190
191/// Sparse indexed option values such as hooks and `command-alias[]`.
192#[derive(Clone, Debug, Default, Eq, PartialEq)]
193pub struct SparseOptionMap(BTreeMap<String, BTreeMap<u32, OptionValue>>);
194
195impl SparseOptionMap {
196    /// Creates an empty sparse map.
197    #[must_use]
198    pub const fn new() -> Self {
199        Self(BTreeMap::new())
200    }
201
202    /// Returns all populated indexes for a base option name.
203    #[must_use]
204    pub fn get(&self, name: &str) -> Option<&BTreeMap<u32, OptionValue>> {
205        self.0.get(name)
206    }
207
208    /// Sets one sparse value.
209    pub fn insert(
210        &mut self,
211        name: impl Into<String>,
212        index: u32,
213        value: impl Into<OptionValue>,
214    ) -> Option<OptionValue> {
215        self.0
216            .entry(name.into())
217            .or_default()
218            .insert(index, value.into())
219    }
220
221    /// Iterates over base names in lexical order.
222    pub fn iter(&self) -> impl Iterator<Item = (&str, &BTreeMap<u32, OptionValue>)> {
223        self.0.iter().map(|(name, values)| (name.as_str(), values))
224    }
225
226    pub(crate) fn parse(bytes: &[u8]) -> Result<Self> {
227        let options = OptionMap::parse(bytes)?;
228        let mut sparse = Self::new();
229        for (name, value) in options.0 {
230            let Some(open) = name.rfind('[') else {
231                continue;
232            };
233            let Some(index) = name.strip_suffix(']').and_then(|name| name.get(open + 1..)) else {
234                return Err(Error::Option {
235                    kind: OptionErrorKind::SparseIndex,
236                    message: format!("malformed indexed option `{name}`"),
237                });
238            };
239            let base = &name[..open];
240            let index = index.parse().map_err(|_| Error::Option {
241                kind: OptionErrorKind::SparseIndex,
242                message: format!("invalid index in `{name}`"),
243            })?;
244            sparse.insert(base, index, value);
245        }
246        Ok(sparse)
247    }
248}
249
250#[cfg(test)]
251mod tests {
252    use super::{OptionMap, SparseOptionMap};
253
254    #[test]
255    fn parses_option_output_without_losing_spaces() {
256        let Ok(options) = OptionMap::parse(b"status-left hello world\nbase-index 1\n") else {
257            return;
258        };
259        assert_eq!(
260            options
261                .get("status-left")
262                .and_then(super::OptionValue::as_text)
263                .map(crate::TmuxText::as_bytes),
264            Some(b"hello world".as_slice())
265        );
266    }
267
268    #[test]
269    fn parses_sparse_arrays() {
270        let Ok(options) = SparseOptionMap::parse(b"hook[1] first\nhook[9] ninth\n") else {
271            return;
272        };
273        assert_eq!(
274            options.get("hook").map(std::collections::BTreeMap::len),
275            Some(2)
276        );
277    }
278}