Skip to main content

tmux_client/
target.rs

1//! Validated tmux identities and command targets.
2
3use std::ffi::OsString;
4use std::fmt;
5use std::str::FromStr;
6
7use crate::{Error, Result, TmuxText};
8
9macro_rules! id_type {
10    ($name:ident, $prefix:literal, $kind:literal) => {
11        #[doc = concat!("A validated tmux ", $kind, " identity.")]
12        #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
13        pub struct $name(u64);
14
15        impl $name {
16            #[doc = concat!("Creates a ", $kind, " identity from its numeric component.")]
17            #[must_use]
18            pub const fn new(value: u64) -> Self {
19                Self(value)
20            }
21
22            /// Returns the numeric component.
23            #[must_use]
24            pub const fn get(self) -> u64 {
25                self.0
26            }
27        }
28
29        impl fmt::Display for $name {
30            fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
31                write!(formatter, concat!($prefix, "{}"), self.0)
32            }
33        }
34
35        impl FromStr for $name {
36            type Err = Error;
37
38            fn from_str(value: &str) -> Result<Self> {
39                let numeric = value
40                    .strip_prefix($prefix)
41                    .ok_or_else(|| Error::InvalidId {
42                        kind: $kind,
43                        value: value.to_owned(),
44                    })?;
45                let parsed = numeric.parse().map_err(|_| Error::InvalidId {
46                    kind: $kind,
47                    value: value.to_owned(),
48                })?;
49                Ok(Self(parsed))
50            }
51        }
52    };
53}
54
55id_type!(SessionId, "$", "session");
56id_type!(WindowId, "@", "window");
57id_type!(PaneId, "%", "pane");
58
59/// A validated tmux session name.
60#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
61pub struct SessionName(String);
62
63impl SessionName {
64    /// Validates a session name.
65    pub fn new(value: impl Into<String>) -> Result<Self> {
66        let value = value.into();
67        if value.is_empty() || value.contains('.') || value.contains(':') {
68            return Err(Error::InvalidSessionName(value));
69        }
70        Ok(Self(value))
71    }
72
73    /// Returns the session name.
74    #[must_use]
75    pub fn as_str(&self) -> &str {
76        &self.0
77    }
78}
79
80impl fmt::Display for SessionName {
81    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
82        formatter.write_str(&self.0)
83    }
84}
85
86impl FromStr for SessionName {
87    type Err = Error;
88
89    fn from_str(value: &str) -> Result<Self> {
90        Self::new(value)
91    }
92}
93
94/// The server-visible name of an attached tmux client.
95#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
96pub struct ClientName(TmuxText);
97
98impl ClientName {
99    /// Creates a client name, rejecting empty values.
100    pub fn new(value: impl Into<TmuxText>) -> Result<Self> {
101        let value = value.into();
102        if value.is_empty() {
103            return Err(Error::InvalidArgument {
104                argument: "client name",
105                message: "must not be empty".to_owned(),
106            });
107        }
108        Ok(Self(value))
109    }
110
111    /// Returns the byte-preserving name.
112    #[must_use]
113    pub const fn as_text(&self) -> &TmuxText {
114        &self.0
115    }
116
117    pub(crate) fn to_os_string(&self) -> OsString {
118        self.0.to_os_string()
119    }
120}
121
122impl fmt::Display for ClientName {
123    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
124        self.0.fmt(formatter)
125    }
126}
127
128/// A target that identifies a session.
129#[derive(Clone, Debug, Eq, Hash, PartialEq)]
130pub enum SessionTarget {
131    /// An immutable tmux session ID.
132    Id(SessionId),
133    /// A session name.
134    Name(SessionName),
135}
136
137impl fmt::Display for SessionTarget {
138    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
139        match self {
140            Self::Id(id) => id.fmt(formatter),
141            Self::Name(name) => name.fmt(formatter),
142        }
143    }
144}
145
146impl From<SessionId> for SessionTarget {
147    fn from(value: SessionId) -> Self {
148        Self::Id(value)
149    }
150}
151
152impl From<SessionName> for SessionTarget {
153    fn from(value: SessionName) -> Self {
154        Self::Name(value)
155    }
156}
157
158/// A target that identifies a window or a window link.
159#[derive(Clone, Debug, Eq, Hash, PartialEq)]
160pub enum WindowTarget {
161    /// An immutable tmux window ID.
162    Id(WindowId),
163    /// A window index in a session.
164    Link(WindowLink),
165}
166
167impl fmt::Display for WindowTarget {
168    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
169        match self {
170            Self::Id(id) => id.fmt(formatter),
171            Self::Link(link) => link.fmt(formatter),
172        }
173    }
174}
175
176impl From<WindowId> for WindowTarget {
177    fn from(value: WindowId) -> Self {
178        Self::Id(value)
179    }
180}
181
182impl From<WindowLink> for WindowTarget {
183    fn from(value: WindowLink) -> Self {
184        Self::Link(value)
185    }
186}
187
188/// A target that identifies a pane.
189#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
190pub enum PaneTarget {
191    /// An immutable tmux pane ID.
192    Id(PaneId),
193}
194
195impl fmt::Display for PaneTarget {
196    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
197        match self {
198            Self::Id(id) => id.fmt(formatter),
199        }
200    }
201}
202
203impl From<PaneId> for PaneTarget {
204    fn from(value: PaneId) -> Self {
205        Self::Id(value)
206    }
207}
208
209/// A session-specific link to a window.
210#[derive(Clone, Debug, Eq, Hash, PartialEq)]
211pub struct WindowLink {
212    session: SessionTarget,
213    index: u32,
214}
215
216impl WindowLink {
217    /// Creates a window link target.
218    #[must_use]
219    pub fn new(session: impl Into<SessionTarget>, index: u32) -> Self {
220        Self {
221            session: session.into(),
222            index,
223        }
224    }
225
226    /// Returns the owning session target.
227    #[must_use]
228    pub const fn session(&self) -> &SessionTarget {
229        &self.session
230    }
231
232    /// Returns the window index in that session.
233    #[must_use]
234    pub const fn index(&self) -> u32 {
235        self.index
236    }
237}
238
239impl fmt::Display for WindowLink {
240    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
241        write!(formatter, "{}:{}", self.session, self.index)
242    }
243}
244
245#[cfg(test)]
246mod tests {
247    use std::str::FromStr;
248
249    use super::{PaneId, SessionId, SessionName, WindowId};
250
251    #[test]
252    fn ids_round_trip() {
253        assert_eq!(
254            SessionId::from_str("$4")
255                .ok()
256                .map(|id| id.to_string())
257                .as_deref(),
258            Some("$4")
259        );
260        assert_eq!(
261            WindowId::from_str("@3")
262                .ok()
263                .map(|id| id.to_string())
264                .as_deref(),
265            Some("@3")
266        );
267        assert_eq!(
268            PaneId::from_str("%2")
269                .ok()
270                .map(|id| id.to_string())
271                .as_deref(),
272            Some("%2")
273        );
274    }
275
276    #[test]
277    fn invalid_session_names_are_rejected() {
278        assert!(SessionName::new("").is_err());
279        assert!(SessionName::new("bad:name").is_err());
280        assert!(SessionName::new("bad.name").is_err());
281    }
282}