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
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
//! Reading and writing tmux options and hooks.
//!
//! Options are read one at a time through `show-options -v`, which prints the
//! stored bytes verbatim. The listing form is not used for values: tmux
//! renders them with `args_escape`, which picks bare-with-backslashes, double
//! quotes, or single quotes depending on content, so re-parsing it would be
//! guesswork. Names are read from the listing because a name is plain ASCII.
//!
//! Hooks live in the same option tables in supported tmux releases, so they
//! share this path. A hook is an array option, which is why its name carries
//! an index.

use std::collections::BTreeMap;
use std::ffi::OsString;
use std::os::unix::ffi::OsStringExt as _;

use crate::formats::TmuxText;
use crate::hooks::IndexedHooks;
use crate::hooks::ReplaceMode;
use crate::internal::core::Core;
use crate::options::{OptionScope, OptionValue};
use crate::{Command, CommandChain, Error};

/// Which option table an operation reads or writes.
#[derive(Clone, Copy, Debug)]
pub(crate) enum Scope<'target> {
    /// Server options, tmux's `-s`.
    Server,
    /// Global session options, tmux's `-g`.
    GlobalSession,
    /// Global window options, tmux's `-w -g`.
    GlobalWindow,
    /// One session's options.
    Session(&'target str),
    /// One window's options, tmux's `-w`.
    Window(&'target str),
    /// One pane's options, tmux's `-p`.
    Pane(&'target str),
}

impl Scope<'_> {
    /// Which of tmux's option tables this scope names.
    fn option_scope(self) -> OptionScope {
        match self {
            Self::Server => OptionScope::Server,
            Self::GlobalSession | Self::Session(_) => OptionScope::Session,
            Self::GlobalWindow | Self::Window(_) => OptionScope::Window,
            Self::Pane(_) => OptionScope::Pane,
        }
    }

    /// Apply this scope's flags to an option command.
    fn apply(self, command: Command) -> Command {
        match self {
            Self::Server => command.arg("-s"),
            Self::GlobalSession => command.arg("-g"),
            Self::GlobalWindow => command.arg("-w").arg("-g"),
            Self::Session(target) => command.arg("-t").arg(OsString::from(target)),
            Self::Window(target) => command.arg("-w").arg("-t").arg(OsString::from(target)),
            Self::Pane(target) => command.arg("-p").arg("-t").arg(OsString::from(target)),
        }
    }
}

/// Read one option's exact stored value.
///
/// Absence is reported two different ways because tmux stores two kinds of
/// option. A built-in option always exists, so an unset one prints nothing and
/// exits zero. A user option, whose name begins with `@`, exists only while it
/// is set, so an unset one is simply unknown and tmux fails. Both become
/// `None`; the name shape decides which rule applies, so no error text is
/// parsed.
///
/// An option deliberately set to the empty string cannot be told apart from an
/// unset one, because tmux prints nothing for either.
pub(crate) async fn get(
    core: &Core,
    scope: Scope<'_>,
    name: &str,
) -> Result<Option<TmuxText>, Error> {
    let command = scope
        .apply(Command::new("show-options"))
        .arg("-v")
        .arg("--")
        .arg(OsString::from(name));
    let result = core.execute(command).await?;

    if !result.success() {
        let failure = Error::from_refused_result("show-options", &result, None);

        // A user option that is not set is not merely empty, it is unknown to
        // tmux, so that one failure is the answer `None`.
        //
        // Only that one. The earlier version asked what the caller had named
        // and swallowed every failure for an `@` name, which made a pane that
        // had gone away read as a pane whose option was never set -- tmux says
        // "invalid option: @x" for the first and "no such pane: %1" for the
        // second, in the stderr this already holds.
        if name.starts_with('@')
            && matches!(
                failure,
                Error::OptionRejected {
                    kind: crate::OptionErrorKind::Unknown,
                    ..
                }
            )
        {
            return Ok(None);
        }

        return Err(failure);
    }

    let stdout = result.stdout();
    let value = stdout.strip_suffix(b"\n").unwrap_or(stdout);
    if value.is_empty() {
        return Ok(None);
    }

    Ok(Some(TmuxText::from(value.to_vec())))
}

/// List the option names present at one scope.
///
/// Array options repeat once per index, so a name may carry an `[n]` suffix
/// exactly as tmux writes it.
pub(crate) async fn names(core: &Core, scope: Scope<'_>) -> Result<Vec<String>, Error> {
    let result = core
        .execute(scope.apply(Command::new("show-options")))
        .await?;
    if !result.success() {
        return Err(Error::from_refused_result("show-options", &result, None));
    }

    Ok(result
        .stdout_lossy()
        .lines()
        // Only the name is taken. The rest of the line is tmux's display form,
        // which this module deliberately never re-parses.
        .filter_map(|line| line.split_whitespace().next())
        .map(ToOwned::to_owned)
        .collect())
}

/// Set one option to an exact value.
pub(crate) async fn set(
    core: &Core,
    scope: Scope<'_>,
    name: &str,
    value: impl Into<OsString>,
    append: bool,
) -> Result<(), Error> {
    let mut command = scope.apply(Command::new("set-option"));
    if append {
        command = command.arg("-a");
    }

    ensure_scope(core, scope, name).await?;

    run(
        core,
        "set-option",
        Some(name),
        command
            .arg("--")
            .arg(OsString::from(name))
            .sensitive_arg(value.into()),
    )
    .await
}

/// Remove one option, restoring whatever it inherits.
pub(crate) async fn unset(core: &Core, scope: Scope<'_>, name: &str) -> Result<(), Error> {
    ensure_scope(core, scope, name).await?;

    run(
        core,
        "set-option",
        None,
        scope
            .apply(Command::new("set-option"))
            .arg("-u")
            .arg("--")
            .arg(OsString::from(name)),
    )
    .await
}

/// Set one hook to a tmux command.
///
/// A hook is an array option, and tmux empties the whole array before storing
/// an unindexed write: setting `alert-bell` discards whatever `alert-bell[1]`
/// and up were running. Naming slot 0 explicitly takes the other branch of
/// `cmd_set_option_exec` and leaves its neighbours alone, which is what
/// setting one hook means. `set_hooks` already writes every slot by index for
/// the same reason.
///
/// A name that already claims index syntax is forwarded whole. Parsing it here
/// to check would have to decide what `alert-bell[x]` means, and tmux is the
/// one that gets to answer that.
pub(crate) async fn set_hook(
    core: &Core,
    scope: Scope<'_>,
    name: &str,
    command_text: impl Into<OsString>,
) -> Result<(), Error> {
    ensure_scope(core, scope, name).await?;

    let slot = if name.contains('[') {
        OsString::from(name)
    } else {
        OsString::from(format!("{name}[0]"))
    };

    run(
        core,
        "set-hook",
        None,
        scope
            .apply(Command::new("set-hook"))
            .arg("--")
            .arg(slot)
            .sensitive_arg(command_text.into()),
    )
    .await
}

/// Remove one hook.
pub(crate) async fn unset_hook(core: &Core, scope: Scope<'_>, name: &str) -> Result<(), Error> {
    ensure_scope(core, scope, name).await?;

    run(
        core,
        "set-hook",
        None,
        scope
            .apply(Command::new("set-hook"))
            .arg("-u")
            .arg("--")
            .arg(OsString::from(name)),
    )
    .await
}

/// Options tmux started keeping at a second scope after the supported floor.
///
/// Gating on the current table alone would allow a write that an older tmux
/// silently places at the other scope, which is the defect this guard exists
/// to stop.
const LATE_SCOPES: &[(&str, OptionScope, crate::version::ReleaseVersion)] = &[
    (
        "pane-border-format",
        OptionScope::Pane,
        crate::version::since::PANE_BORDER_FORMAT_PER_PANE,
    ),
    (
        "pane-active-border-style",
        OptionScope::Pane,
        crate::version::since::PANE_BORDER_STYLE_PER_PANE,
    ),
    (
        "pane-border-style",
        OptionScope::Pane,
        crate::version::since::PANE_BORDER_STYLE_PER_PANE,
    ),
];

/// Refuse a write tmux would carry out somewhere other than the handle says.
///
/// tmux picks an option's table from its name, not from the flags the command
/// carried, so a mismatch is not refused: `mouse` sent with `-p` becomes the
/// session's `mouse`, tmux exits 0, and reading it back through the same
/// handle resolves the same way and agrees. Nothing downstream can tell.
async fn ensure_scope(core: &Core, scope: Scope<'_>, name: &str) -> Result<(), Error> {
    // A user option has no entry in tmux's table, and tmux honours the flags
    // literally for one. Nothing to check, and nothing to get wrong.
    if name.starts_with('@') {
        return Ok(());
    }

    // `option_schema` resolves the name the way tmux does: it drops an index,
    // maps the legacy spellings, and takes an unambiguous prefix.
    let Some(schema) = crate::option_schema(name) else {
        // tmux will answer "unknown option" itself, and its message names what
        // it could not resolve better than a guess here would.
        return Ok(());
    };

    let requested = scope.option_scope();
    if !schema.accepts(requested) {
        return Err(Error::OptionScopeMismatch {
            option: schema.name().to_owned(),
            requested,
            declared: schema.scopes(),
        });
    }

    // The schema is built from one tmux. Where a scope arrived later than the
    // floor, the running server decides.
    for (option, late, needs) in LATE_SCOPES {
        if *option == schema.name() && *late == requested {
            let found = core.capabilities().await?.tmux_version();
            if !found.meets(needs) {
                return Err(Error::UnsupportedCapability {
                    capability: option,
                    needs: *needs,
                    found: found.clone(),
                });
            }
        }
    }

    Ok(())
}

/// Run an option mutation, requiring tmux to accept it.
async fn run(
    core: &Core,
    command_name: &'static str,
    option_name: Option<&str>,
    command: Command,
) -> Result<(), Error> {
    let result = core.execute(command).await?;
    if result.success() {
        return Ok(());
    }

    Err(mutation_failure(command_name, option_name, &result))
}

fn mutation_failure(
    command_name: &'static str,
    option_name: Option<&str>,
    result: &crate::CommandResult,
) -> Error {
    let exit_code = result.exit_code();
    if result.command().sensitive_argument_count() == 0 {
        return Error::from_refused_result(command_name, result, None);
    }

    let failure = Error::refused(
        command_name,
        exit_code,
        result.stderr_lossy().into_owned(),
        None,
    );
    match (option_name, failure) {
        (Some(name), Error::OptionRejected { kind, .. }) => Error::OptionRejected {
            kind,
            detail: name.to_owned(),
        },
        (Some(name), Error::CommandFailed { .. }) => Error::OptionRejected {
            kind: crate::OptionErrorKind::BadValue,
            detail: name.to_owned(),
        },
        _ => Error::refused_withheld(command_name, exit_code),
    }
}

/// List the hook slots that are set at one scope, as `name[index]`.
///
/// `show-hooks` prints every hook tmux knows, most of them bare because they
/// hold nothing. A slot that holds something is the one carrying an index, so
/// that is the whole test: no value is read here, for the reason this module
/// gives above.
pub(crate) async fn hook_slots(core: &Core, scope: Scope<'_>) -> Result<Vec<String>, Error> {
    let result = core
        .execute(scope.apply(Command::new("show-hooks")))
        .await?;
    if !result.success() {
        return Err(Error::from_refused_result("show-hooks", &result, None));
    }

    Ok(result
        .stdout_lossy()
        .lines()
        .filter_map(|line| line.split_whitespace().next())
        .filter(|slot| slot.contains('['))
        .map(ToOwned::to_owned)
        .collect())
}

/// Split a `name[index]` slot into its parts.
pub(crate) fn split_slot(slot: &str) -> Option<(&str, u32)> {
    let (name, rest) = slot.split_once('[')?;
    let index = rest.strip_suffix(']')?.parse().ok()?;
    Some((name, index))
}

/// Read every hook that is set at one scope.
///
/// Names come from the listing and values from `show-options -v`, one slot at
/// a time, for the reason this module gives above: the listing renders a value
/// through `args_escape` and re-parsing that would be guesswork.
pub(crate) async fn hooks(
    core: &Core,
    scope: Scope<'_>,
) -> Result<BTreeMap<String, IndexedHooks>, Error> {
    let mut collected: BTreeMap<String, BTreeMap<u32, TmuxText>> = BTreeMap::new();
    for slot in hook_slots(core, scope).await? {
        let Some((name, index)) = split_slot(&slot) else {
            continue;
        };
        if let Some(value) = get(core, scope, &slot).await? {
            collected
                .entry(name.to_owned())
                .or_default()
                .insert(index, value);
        }
    }

    Ok(collected
        .into_iter()
        .map(|(name, entries)| (name, IndexedHooks::from_entries(entries)))
        .collect())
}

/// Read every index one array option holds.
///
/// Values come back one slot at a time rather than from the listing, for the
/// reason this module gives above: the listing renders a value through
/// `args_escape`, and re-parsing that would be guesswork.
pub(crate) async fn indexed(
    core: &Core,
    scope: Scope<'_>,
    name: &str,
) -> Result<BTreeMap<u32, TmuxText>, Error> {
    let mut entries = BTreeMap::new();
    for slot in slots_of(core, scope, name).await? {
        let Some((_, index)) = split_slot(&slot) else {
            continue;
        };
        if let Some(value) = get(core, scope, &slot).await? {
            entries.insert(index, value);
        }
    }

    Ok(entries)
}

/// List the slots one hook name holds, as `name[index]`.
///
/// Asked for by name rather than taken from the full listing, because tmux
/// answers the two differently: it will not enumerate the hooks set on a
/// window or a pane, but it will list the slots of a hook it is asked about
/// by name at any scope.
async fn slots_of(core: &Core, scope: Scope<'_>, name: &str) -> Result<Vec<String>, Error> {
    let result = core
        .execute(
            scope
                .apply(Command::new("show-options"))
                .arg("--")
                .arg(OsString::from(name)),
        )
        .await?;
    if !result.success() {
        return Err(Error::from_refused_result("show-options", &result, None));
    }

    Ok(result
        .stdout_lossy()
        .lines()
        .filter_map(|line| line.split_whitespace().next())
        .filter(|slot| split_slot(slot).is_some_and(|(slot_name, _)| slot_name == name))
        .map(ToOwned::to_owned)
        .collect())
}

/// Read one hook's commands, or `None` when it holds nothing.
pub(crate) async fn hook(
    core: &Core,
    scope: Scope<'_>,
    name: &str,
) -> Result<Option<IndexedHooks>, Error> {
    let mut entries = BTreeMap::new();
    for slot in slots_of(core, scope, name).await? {
        let Some((_, index)) = split_slot(&slot) else {
            continue;
        };
        if let Some(value) = get(core, scope, &slot).await? {
            entries.insert(index, value);
        }
    }

    if entries.is_empty() {
        return Ok(None);
    }
    Ok(Some(IndexedHooks::from_entries(entries)))
}

/// Read every option set at one scope, decoded by its declared kind.
///
/// One command per option, because a value is read through `show-options -v`
/// for the reason this module gives above. That is the price of getting the
/// stored bytes rather than tmux's display form, and it is why the listing of
/// names is offered separately: a caller who only wants to know what is set
/// does not pay it.
///
/// An array option keeps the indexed name tmux lists it under, so
/// `command-alias[0]` and `command-alias[1]` are separate entries. Its kind is
/// looked up from the name without the index.
pub(crate) async fn typed_all(
    core: &Core,
    scope: Scope<'_>,
) -> Result<BTreeMap<String, OptionValue>, Error> {
    let mut decoded = BTreeMap::new();
    for name in names(core, scope).await? {
        if let Some(value) = get(core, scope, &name).await? {
            let kind_name = split_slot(&name).map_or(name.as_str(), |(base, _)| base);
            decoded.insert(name.clone(), OptionValue::decode(kind_name, value));
        }
    }

    Ok(decoded)
}

/// Write a whole hook with an exact replay boundary.
///
/// The first mutation is sent alone. A later failure follows an accepted
/// effect; a first-command failure remains its leaf error.
pub(crate) async fn set_hooks(
    core: &Core,
    scope: Scope<'_>,
    name: &str,
    hooks: &IndexedHooks,
    replace: ReplaceMode,
) -> Result<(), Error> {
    ensure_scope(core, scope, name).await?;

    let mut commands = Vec::with_capacity(hooks.len() + 1);
    if replace == ReplaceMode::Replace {
        // Clearing first is what makes this a replacement rather than a
        // merge: an index the caller did not name would otherwise survive.
        commands.push(
            scope
                .apply(Command::new("set-hook"))
                .arg("-u")
                .arg("--")
                .arg(OsString::from(name)),
        );
    }
    for (index, value) in hooks {
        commands.push(
            scope
                .apply(Command::new("set-hook"))
                .arg("--")
                .arg(OsString::from(format!("{name}[{index}]")))
                // A hook command is bytes, as everything tmux stores is. The
                // single-hook path forwards them; going through a `String`
                // here would replace whatever is not UTF-8 before tmux ever
                // sees it.
                .sensitive_arg(OsString::from_vec(value.as_bytes().to_vec())),
        );
    }

    let mut commands = commands.into_iter();
    let Some(first) = commands.next() else {
        return Ok(());
    };
    let Some(second) = commands.next() else {
        return run(core, "set-hook", None, first).await;
    };

    run(core, "set-hook", None, first).await?;
    let result = match commands.next() {
        None => core.execute(second).await,
        Some(third) => {
            let mut chain = CommandChain::new(second).then(third);
            for command in commands {
                chain = chain.then(command);
            }
            core.execute_chain(chain).await
        }
    };
    let result = result.map_err(|error| error.after_effect("set-hooks"))?;
    if result.success() {
        return Ok(());
    }

    Err(mutation_failure("set-hook", None, &result).after_effect("set-hooks"))
}