libtmux 0.1.0-alpha.9

Async typed tmux client and object model (alpha)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
//! The shared path from a list command to hydrated snapshots.
//!
//! Every public listing follows the same four steps: build a format plan for
//! the detected tmux version, render its template into a list command, parse
//! the transport bytes, and hydrate rows. Keeping that here means the public
//! handles differ only in the target they scope to.

use std::ffi::{OsStr, OsString};

use crate::error::ListingDecodeError;
use crate::formats::{FormatCodecError, FormatPlan, ListProfile};
use crate::internal::core::Core;
use crate::snapshot::{
    ClientInfo, PaneProjection, SessionInfo, WindowProjection, hydrate_client_infos_from_stdout,
    hydrate_pane_projections_from_stdout, hydrate_session_infos_from_stdout,
    hydrate_window_projections_from_stdout, pane_projection_plan, window_projection_plan,
};
use crate::{Command, Error};

/// How a listing is scoped.
///
/// tmux spells "everything on the server" and "everything under this object"
/// with different flags, so the two are distinguished here rather than by
/// passing an optional target that callers could forget.
#[derive(Clone, Copy, Debug)]
pub(crate) enum Scope<'target> {
    /// Every object on the server, using tmux's `-a` flag.
    Server,
    /// Only objects under one target, using tmux's `-t` flag.
    ///
    /// For `list-panes` the target is a window; tmux resolves a session target
    /// to that session's current window, which is rarely what a caller means.
    Target(&'target str),
    /// Every pane in one session, using tmux's `-s -t` flags.
    ///
    /// `list-panes` needs `-s` to widen a session target from the current
    /// window to the whole session.
    SessionTarget(&'target str),
    /// No scoping flag, for commands that are already server-wide.
    ///
    /// `list-sessions` and `list-clients` cover the whole server and reject
    /// `-a`, so they take neither flag.
    Unscoped,
}

impl<'target> Scope<'target> {
    /// Return the target this scope names, if it names one.
    const fn target(self) -> Option<&'target str> {
        match self {
            Self::Target(target) | Self::SessionTarget(target) => Some(target),
            Self::Server | Self::Unscoped => None,
        }
    }

    /// Apply this scope's flags to a list command.
    fn apply(self, command: Command) -> Command {
        match self {
            Self::Server => command.arg("-a"),
            Self::Target(target) => command.arg("-t").arg(OsString::from(target)),
            Self::SessionTarget(target) => command.arg("-s").arg("-t").arg(OsString::from(target)),
            Self::Unscoped => command,
        }
    }
}

/// A value that may be interpolated into a tmux `-f` predicate.
///
/// tmux documents no escaping for a predicate, so a value that could contain
/// `#`, `}`, or a comma would change what the predicate means. Only values
/// drawn from a validated domain implement this: an id is a sigil followed by
/// digits, and an index is an integer. A name is user-chosen text and is
/// deliberately absent, which is what keeps the rule enforced by the compiler
/// rather than by remembering it.
pub(crate) trait Pushdown {
    /// Render this value as a tmux predicate comparing one format field.
    fn predicate(&self, field: &str) -> String;
}

macro_rules! pushdown_via_display {
    ($($type:ty),+ $(,)?) => {
        $(impl Pushdown for $type {
            fn predicate(&self, field: &str) -> String {
                format!("#{{==:#{{{field}}},{self}}}")
            }
        })+
    };
}

pushdown_via_display!(crate::SessionId, crate::WindowId, crate::PaneId, i32, u32,);

/// Run one list command and return its raw stdout.
async fn list(
    core: &Core,
    list_command: &'static str,
    scope: Scope<'_>,
    filter: Option<&str>,
    template: &str,
) -> Result<Vec<u8>, Error> {
    let mut command = scope.apply(Command::new(list_command));
    // tmux evaluates the predicate per row, so a filtered listing returns only
    // matching rows rather than every row for the caller to scan.
    if let Some(filter) = filter {
        command = command.arg("-f").arg(OsString::from(filter));
    }
    let result = core
        .execute(command.arg("-F").arg(OsString::from(template)))
        .await?;
    if !result.success() {
        let stderr = result.stderr_lossy().into_owned();
        // A server holding no sessions has no current target, and tmux says
        // so even for `-a`, which asks for everything. A server-wide listing
        // has nothing to list; a listing under a target could not resolve it,
        // which the classifier reports as the target being gone.
        if scope.target().is_none() && stderr.trim_end() == crate::error::NO_CURRENT_TARGET {
            return Ok(Vec::new());
        }

        // Anything else is not an empty listing. The lenient accessors turn
        // this back into an empty Vec; the loud forms exist so a caller who
        // must not guess gets the reason instead.
        return Err(Error::from_refused_result(
            list_command,
            &result,
            scope.target().map(OsStr::new),
        ));
    }

    Ok(result.stdout().to_vec())
}

/// Convert a private codec failure into the public listing error.
fn decode_error(list_command: &'static str) -> impl Fn(FormatCodecError) -> Error {
    move |error| Error::DecodeListing {
        list_command,
        detail: ListingDecodeError::new(error),
    }
}

/// List sessions.
/// Record that a lenient listing threw a failure away.
///
/// The lenient forms return an empty vector for "nothing there" and for "the
/// listing failed", which is the trade they exist for. A caller who chose them
/// has said the reason does not change what they do -- but somebody reading a
/// log later still needs to be able to tell the two apart, and an empty vector
/// cannot.
///
/// This lives here rather than beside any one caller because all eleven of
/// them need it. As a private associated function on `Server` it was reachable
/// only from that file, so five listings recorded their discard and six did
/// not, split by nothing but where the helper happened to sit.
#[cfg_attr(
    not(feature = "tracing"),
    expect(
        unused_variables,
        reason = "the cause has no sink when tracing is disabled"
    )
)]
pub(crate) fn trace_discarded(list_command: &'static str, error: &Error) {
    #[cfg(feature = "tracing")]
    tracing::debug!(
        list_command,
        error = %error,
        "a lenient listing discarded a failure and returned empty",
    );
}

pub(crate) async fn sessions(core: &Core, filter: Option<&str>) -> Result<Vec<SessionInfo>, Error> {
    const LIST_COMMAND: &str = "list-sessions";

    let version = core.capabilities().await?.tmux_version().clone();
    let plan = FormatPlan::for_profile(ListProfile::Sessions, &version);
    let stdout = list(core, LIST_COMMAND, Scope::Unscoped, filter, plan.template()).await?;

    hydrate_session_infos_from_stdout(&plan, &stdout).map_err(decode_error(LIST_COMMAND))
}

/// List windows, either server-wide or under one target.
pub(crate) async fn windows(
    core: &Core,
    scope: Scope<'_>,
    filter: Option<&str>,
) -> Result<Vec<WindowProjection>, Error> {
    const LIST_COMMAND: &str = "list-windows";

    let version = core.capabilities().await?.tmux_version().clone();
    let plan = window_projection_plan(&version).map_err(decode_error(LIST_COMMAND))?;
    let stdout = list(core, LIST_COMMAND, scope, filter, plan.template()).await?;

    hydrate_window_projections_from_stdout(core.configuration().identity(), &plan, &stdout)
        .map_err(decode_error(LIST_COMMAND))
}

/// Resolve one pane and hydrate its containing window from the same tmux row.
pub(crate) async fn window_for_pane(
    core: &Core,
    pane: &crate::PaneId,
) -> Result<Option<WindowProjection>, Error> {
    const LIST_COMMAND: &str = "list-panes";

    let version = core.capabilities().await?.tmux_version().clone();
    let plan = window_projection_plan(&version).map_err(decode_error(LIST_COMMAND))?;
    let target = pane.to_string();
    let filter = pane.predicate("pane_id");
    let stdout = match list(
        core,
        LIST_COMMAND,
        Scope::Target(&target),
        Some(&filter),
        plan.template(),
    )
    .await
    {
        Err(error) if error.is_object_gone() => return Ok(None),
        result => result?,
    };

    Ok(
        hydrate_window_projections_from_stdout(core.configuration().identity(), &plan, &stdout)
            .map_err(decode_error(LIST_COMMAND))?
            .into_iter()
            .next(),
    )
}

/// List panes, either server-wide or under one target.
pub(crate) async fn panes(
    core: &Core,
    scope: Scope<'_>,
    filter: Option<&str>,
) -> Result<Vec<PaneProjection>, Error> {
    const LIST_COMMAND: &str = "list-panes";

    let version = core.capabilities().await?.tmux_version().clone();
    let plan = pane_projection_plan(&version).map_err(decode_error(LIST_COMMAND))?;
    let stdout = list(core, LIST_COMMAND, scope, filter, plan.template()).await?;

    hydrate_pane_projections_from_stdout(core.configuration().identity(), &plan, &stdout)
        .map_err(decode_error(LIST_COMMAND))
}

/// List attached clients.
pub(crate) async fn clients(core: &Core, filter: Option<&str>) -> Result<Vec<ClientInfo>, Error> {
    const LIST_COMMAND: &str = "list-clients";

    let version = core.capabilities().await?.tmux_version().clone();
    let plan = FormatPlan::for_profile(ListProfile::Clients, &version);
    let stdout = list(core, LIST_COMMAND, Scope::Unscoped, filter, plan.template()).await?;

    hydrate_client_infos_from_stdout(&plan, &stdout).map_err(decode_error(LIST_COMMAND))
}

/// Run a creating command that prints its new object, and hydrate it.
///
/// tmux's `-P -F` prints the created object through the same format machinery
/// as a listing, so creation costs one round trip rather than a create
/// followed by a lookup.
async fn create_one<T>(
    core: &Core,
    command_name: &'static str,
    build: impl FnOnce(&str) -> Command,
    template: &str,
    hydrate: impl FnOnce(&[u8]) -> Result<Vec<T>, Error>,
) -> Result<T, Error> {
    // The builder places `-P -F` itself, because tmux stops parsing flags at
    // the first positional and these commands end with a shell command.
    let command = build(template);
    let target = command.target().map(OsStr::to_os_string);
    let result = core.execute(command).await?;
    if !result.success() {
        return Err(Error::from_refused_result(
            command_name,
            &result,
            target.as_deref(),
        ));
    }

    hydrate(result.stdout())
        .map_err(|error| error.after_effect(command_name))?
        .into_iter()
        .next()
        .ok_or_else(|| {
            Error::CommandFailed {
                command: command_name,
                exit_code: result.exit_code(),
                stderr: String::from("tmux printed no object for a creating command"),
            }
            .after_effect(command_name)
        })
}

/// Create one session and return its hydrated snapshot.
pub(crate) async fn create_session(
    core: &Core,
    build: impl FnOnce(&str) -> Command,
) -> Result<SessionInfo, Error> {
    let version = core.capabilities().await?.tmux_version().clone();
    let plan = FormatPlan::for_profile(ListProfile::Sessions, &version);
    let template = plan.template().to_owned();

    create_one(core, "new-session", build, &template, |stdout| {
        hydrate_session_infos_from_stdout(&plan, stdout).map_err(decode_error("new-session"))
    })
    .await
}

/// Create one window and return its hydrated projection.
pub(crate) async fn create_window(
    core: &Core,
    build: impl FnOnce(&str) -> Command,
) -> Result<WindowProjection, Error> {
    let version = core.capabilities().await?.tmux_version().clone();
    let plan = window_projection_plan(&version).map_err(decode_error("new-window"))?;
    let template = plan.template().to_owned();
    let identity = core.configuration().identity();

    create_one(core, "new-window", build, &template, |stdout| {
        hydrate_window_projections_from_stdout(identity, &plan, stdout)
            .map_err(decode_error("new-window"))
    })
    .await
}

/// Create one pane and return its hydrated projection.
pub(crate) async fn create_pane(
    core: &Core,
    build: impl FnOnce(&str) -> Command,
) -> Result<PaneProjection, Error> {
    let version = core.capabilities().await?.tmux_version().clone();
    let plan = pane_projection_plan(&version).map_err(decode_error("split-window"))?;
    let template = plan.template().to_owned();
    let identity = core.configuration().identity();

    create_one(core, "split-window", build, &template, |stdout| {
        hydrate_pane_projections_from_stdout(identity, &plan, stdout)
            .map_err(decode_error("split-window"))
    })
    .await
}

/// Run a mutation that returns nothing, requiring tmux to accept it.
pub(crate) async fn mutate(
    core: &Core,
    command_name: &'static str,
    command: Command,
) -> Result<(), Error> {
    let target = command.target().map(OsStr::to_os_string);
    let result = core.execute(command).await?;
    if result.success() {
        return Ok(());
    }

    Err(mutation_failure(command_name, &result, target.as_deref()))
}

fn mutation_failure(
    command_name: &'static str,
    result: &crate::CommandResult,
    target: Option<&OsStr>,
) -> Error {
    Error::from_refused_result(command_name, result, target)
}

#[cfg(test)]
mod tests {
    use std::os::unix::process::ExitStatusExt as _;
    use std::process::ExitStatus;
    use std::sync::Arc;
    use std::sync::atomic::{AtomicUsize, Ordering};

    use super::{create_session, mutation_failure};
    use crate::command::{CommandRequest, CommandResult, ProcessStatus, RequestId};
    use crate::internal::core::Core;
    use crate::internal::executor::{DispatchFuture, Executor, ShutdownFuture};
    use crate::{Command, Error, ErrorKind};

    struct CreationExecutor {
        calls: AtomicUsize,
        stdout: &'static [u8],
    }

    impl Executor for CreationExecutor {
        fn execute(&self, request: CommandRequest) -> DispatchFuture {
            let call = self.calls.fetch_add(1, Ordering::SeqCst);
            let stdout = if call == 0 {
                b"tmux 3.7b\n".to_vec()
            } else {
                assert_eq!(call, 1, "one probe and one creating command");
                self.stdout.to_vec()
            };
            DispatchFuture::new(async move {
                Ok(CommandResult::new(
                    request.request_id(),
                    request.summary().clone(),
                    ProcessStatus::from_exit_status(ExitStatus::from_raw(0)),
                    stdout,
                    Vec::new(),
                ))
            })
        }

        fn shutdown(&self) -> ShutdownFuture {
            ShutdownFuture::new(async { Ok(()) })
        }
    }

    #[test]
    fn sensitive_mutation_failure_withholds_tmux_output() {
        let secret = "sentinel-mutation-secret";
        let command = Command::new("set-option")
            .arg("--")
            .arg("mouse")
            .sensitive_arg(secret);
        let result = CommandResult::new(
            RequestId::new(1),
            command.summary(),
            ProcessStatus::from_exit_status(ExitStatus::from_raw(1 << 8)),
            Vec::new(),
            format!("bad value: {secret}\n").into_bytes(),
        );

        let error = mutation_failure("set-option", &result, None);
        assert!(matches!(&error, Error::CommandFailed { .. }));
        let diagnostic = format!("{error:?} {error}");
        assert!(!diagnostic.contains(secret), "{diagnostic}");
    }

    #[tokio::test]
    async fn successful_creation_marks_decode_and_missing_object_failures() {
        for stdout in [b"malformed\n".as_slice(), b"".as_slice()] {
            let executor = Arc::new(CreationExecutor {
                calls: AtomicUsize::new(0),
                stdout,
            });
            let core = Core::from_executor_for_test(executor.clone());

            let error = create_session(&core, |_format| Command::new("new-session"))
                .await
                .expect_err("tmux succeeded but did not describe the created session");

            assert_eq!(executor.calls.load(Ordering::SeqCst), 2);
            assert_eq!(error.kind(), ErrorKind::PartialEffect);
            assert!(matches!(
                error,
                Error::AfterEffect {
                    operation: "new-session",
                    ..
                }
            ));
        }
    }
}