libtmux 0.1.0-alpha.5

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
//! Running a plan, and saying honestly how each operation ended.
//!
//! What a run can claim depends on how it dispatched. One invocation per
//! operation gives one exit status per operation. A shared invocation gives
//! one exit status for the group, and tmux runs a shared group up to the first
//! failure and drops the rest -- so a failed group says *that* something
//! failed and never *which*. This module reports that difference rather than
//! guessing past it.

use std::collections::HashMap;
use std::ffi::OsString;

use super::planner::Planner;
use super::{Op, Part, Plan, Step};
use crate::{Command, CommandChain, Error, Server};

/// How an operation ended.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Outcome {
    /// tmux ran it and accepted it.
    Complete,
    /// tmux ran it and refused it.
    Failed,
    /// tmux never ran it, because something before it in the same invocation
    /// failed and tmux dropped the rest.
    Skipped,
    /// It shared an invocation with a failure and nothing distinguishes it.
    ///
    /// This is not a soft failure, it is the absence of evidence: the merged
    /// result carries one exit status and one stderr whichever member failed.
    /// Re-run with [`Planner::Sequential`] to get an answer per operation.
    Unknown,
}

impl Outcome {
    /// Whether tmux is known to have accepted this operation.
    #[must_use]
    pub const fn is_complete(self) -> bool {
        matches!(self, Self::Complete)
    }
}

/// How much a run could tell about each operation's outcome.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Attribution {
    /// Each operation had its own exit status.
    PerCommand,
    /// Operations shared an exit status, so a failure is not attributable.
    Merged,
}

/// What one dispatched invocation produced.
#[derive(Clone, Debug)]
pub struct StepOutcome {
    step: Step,
    outcomes: Vec<Outcome>,
    attribution: Attribution,
    command: &'static str,
    stdout: Vec<u8>,
    stderr: Vec<u8>,
}

impl StepOutcome {
    /// The invocation this describes.
    #[must_use]
    pub const fn step(&self) -> &Step {
        &self.step
    }

    /// One outcome per operation in the invocation, in order.
    #[must_use]
    pub fn outcomes(&self) -> &[Outcome] {
        &self.outcomes
    }

    /// Whether the outcomes are per-operation evidence or a shared verdict.
    #[must_use]
    pub const fn attribution(&self) -> Attribution {
        self.attribution
    }

    /// The invocation's stdout, exactly as tmux wrote it.
    #[must_use]
    pub fn stdout(&self) -> &[u8] {
        &self.stdout
    }

    /// The invocation's stderr, exactly as tmux wrote it.
    #[must_use]
    pub fn stderr(&self) -> &[u8] {
        &self.stderr
    }

    /// Why tmux refused this invocation, in the crate's error vocabulary.
    ///
    /// A refusal is data rather than an error here, because a plan may expect
    /// one. This classifies it the same way a direct call would, so a caller
    /// can match on [`Error::SessionExists`] rather than reading stderr, and
    /// does not have to check for a name being taken *before* asking -- a
    /// check that races with anything else creating sessions.
    ///
    /// `None` when the invocation succeeded.
    #[must_use]
    pub fn refusal(&self) -> Option<Error> {
        if self.outcomes.iter().copied().all(Outcome::is_complete) {
            return None;
        }

        Some(Error::refused(
            self.command,
            None,
            String::from_utf8_lossy(&self.stderr).into_owned(),
            None,
        ))
    }
}

/// What running a plan produced.
#[derive(Clone, Debug)]
pub struct PlanResult {
    outcomes: Vec<Outcome>,
    steps: Vec<StepOutcome>,
    bound: HashMap<(usize, Part), OsString>,
    dispatches: usize,
}

impl PlanResult {
    /// One outcome per recorded operation, in plan order.
    #[must_use]
    pub fn outcomes(&self) -> &[Outcome] {
        &self.outcomes
    }

    /// What each dispatched invocation produced.
    #[must_use]
    pub fn steps(&self) -> &[StepOutcome] {
        &self.steps
    }

    /// How many tmux invocations the run cost.
    ///
    /// This is the number the planner changes, and the reason to change it.
    #[must_use]
    pub const fn dispatches(&self) -> usize {
        self.dispatches
    }

    /// Whether every operation is known to have succeeded.
    ///
    /// An [`Outcome::Unknown`] is not success: it is the absence of evidence,
    /// so this is false while any remains.
    #[must_use]
    pub fn is_complete(&self) -> bool {
        self.outcomes.iter().copied().all(Outcome::is_complete)
    }

    /// The concrete id a creating operation produced, if it bound one.
    #[must_use]
    pub fn created(&self, step: usize) -> Option<&OsString> {
        self.bound.get(&(step, Part::Created))
    }
}

impl Plan {
    /// Run this plan, grouping it with `planner`.
    ///
    /// The result does not depend on the planner; the number of tmux
    /// invocations, and how precisely a failure can be attributed, do.
    ///
    /// # Errors
    ///
    /// Returns an error when tmux cannot be reached or a process cannot be
    /// captured. A command tmux *refuses* is reported through the returned
    /// [`PlanResult`], not as an error, because a plan may expect one.
    pub async fn run(&self, server: &Server, planner: Planner) -> Result<PlanResult, Error> {
        let steps = planner.steps(self);
        let mut bound: HashMap<(usize, Part), OsString> = HashMap::new();
        let mut outcomes = vec![Outcome::Skipped; self.len()];
        let mut reported = Vec::with_capacity(steps.len());
        let mut dispatches = 0;

        for step in steps {
            let (result, marked_creation) = self.dispatch(server, &step, &bound).await?;
            dispatches += 1;

            let succeeded = result.success();
            let step_outcomes = attribute(step.indices().len(), succeeded);
            for (position, index) in step.indices().iter().enumerate() {
                outcomes[*index] = step_outcomes[position];
            }
            if succeeded || marked_creation {
                bind(&mut bound, self.steps(), &step, result.stdout());
            }

            reported.push(StepOutcome {
                attribution: if step.indices().len() == 1 {
                    Attribution::PerCommand
                } else {
                    Attribution::Merged
                },
                command: step
                    .indices()
                    .first()
                    .and_then(|index| self.steps().get(*index))
                    .map_or("plan", Op::name),
                step,
                outcomes: step_outcomes,
                stdout: result.stdout().to_vec(),
                stderr: result.stderr().to_vec(),
            });

            if !succeeded {
                break;
            }
        }

        Ok(PlanResult {
            outcomes,
            steps: reported,
            bound,
            dispatches,
        })
    }

    /// Send one invocation, sharing it when the step carries several.
    async fn dispatch(
        &self,
        server: &Server,
        step: &Step,
        bound: &HashMap<(usize, Part), OsString>,
    ) -> Result<(crate::CommandResult, bool), Error> {
        let commands = self.render_step(step, bound)?;
        let marked = step.is_marked();
        let mut commands = commands.into_iter();
        let Some(first) = commands.next() else {
            return Err(Error::CommandFailed {
                command: "plan",
                exit_code: None,
                stderr: String::from("a plan step carried no commands"),
            });
        };

        let result = match commands.next() {
            None => server.cmd(first).await?,
            Some(second) => {
                let mut chain = CommandChain::new(first).then(second);
                for command in commands {
                    chain = chain.then(command);
                }
                server.chain(chain).await?
            }
        };
        Ok((result, marked))
    }

    /// Lower one invocation's operations into commands.
    fn render_step(
        &self,
        step: &Step,
        bound: &HashMap<(usize, Part), OsString>,
    ) -> Result<Vec<Command>, Error> {
        // In a marked fold the decorations address a pane that has no id yet,
        // so they resolve to tmux's `{marked}` register instead of to a bound
        // value. Which slot part names that pane is the creating operation's
        // answer, and it is the same one the planner folded on: `Created` for
        // a split, the created window's `FirstPane` for a new window.
        let marked = step
            .is_marked()
            .then(|| step.indices()[0])
            .and_then(|index| {
                self.steps()
                    .get(index)
                    .and_then(Op::focused_pane)
                    .map(|part| (index, part))
            });
        let resolve = |slot: usize, part: Part| -> Option<OsString> {
            if marked == Some((slot, part)) {
                return Some(OsString::from("{marked}"));
            }
            bound.get(&(slot, part)).cloned()
        };

        let mut commands = Vec::with_capacity(step.len() + 2);
        for (position, index) in step.indices().iter().enumerate() {
            let op = &self.steps()[*index];
            let command = op
                .render(&resolve, ())
                .ok_or_else(|| Error::CommandFailed {
                    command: op.name(),
                    exit_code: None,
                    stderr: format!(
                        "step {index} targets an object no earlier step created; \
                     a plan cannot address what it has not made"
                    ),
                })?;
            commands.push(command);
            // Mark the new pane straight after creating it, so the
            // decorations that follow have a register to address.
            if step.is_marked() && position == 0 {
                commands.push(Command::new("select-pane").arg("-m"));
            }
        }
        if step.is_marked() {
            commands.push(Command::new("select-pane").arg("-M"));
        }
        Ok(commands)
    }
}

/// Decide each operation's outcome from one invocation's exit status.
///
/// A shared invocation that succeeded proves every member ran, so every member
/// is `Complete`. A shared invocation that failed proves only that one member
/// did: tmux reports the same status and stderr whichever it was, so blaming
/// the first would be a guess that is wrong whenever the failure was later.
fn attribute(members: usize, succeeded: bool) -> Vec<Outcome> {
    if succeeded {
        return vec![Outcome::Complete; members];
    }
    if members == 1 {
        return vec![Outcome::Failed];
    }
    vec![Outcome::Unknown; members]
}

/// Record the ids a creating operation printed.
fn bind(bound: &mut HashMap<(usize, Part), OsString>, ops: &[Op], step: &Step, stdout: &[u8]) {
    let Some(index) = step.indices().first().copied() else {
        return;
    };
    let Some(op) = ops.get(index) else {
        return;
    };
    if op.effects().creates.is_none() {
        return;
    }

    // A creating operation prints its ids on the first line, most specific
    // last: `$1 @2 %3`. Reading them positionally is what makes a session's
    // first window and pane addressable without a second round trip.
    let Some(line) = String::from_utf8_lossy(stdout)
        .lines()
        .next()
        .map(str::to_owned)
    else {
        return;
    };
    let ids: Vec<&str> = line.split_whitespace().collect();
    let parts: &[Part] = match ids.len() {
        3 => &[Part::Created, Part::FirstWindow, Part::FirstPane],
        2 => &[Part::Created, Part::FirstPane],
        1 => &[Part::Created],
        _ => return,
    };
    for (id, part) in ids.iter().zip(parts) {
        bound.insert((index, *part), OsString::from(*id));
    }
}

#[cfg(feature = "control-mode")]
impl Plan {
    /// Run this plan over an open control-mode connection.
    ///
    /// Control mode is the one transport that separates *how many commands*
    /// from *how many processes*: every operation is its own protocol block
    /// over one connection, so a plan costs one process however long it is and
    /// every operation still reports its own outcome. That is the combination
    /// a subprocess cannot offer -- there, sharing an invocation is what buys
    /// the process back, and it is exactly what costs the attribution.
    ///
    /// There is no planner argument because there is nothing to trade: blocks
    /// are per command already.
    ///
    /// # Errors
    ///
    /// Returns an error when the connection is closed or a command cannot be
    /// written. A command tmux refuses is reported in the [`PlanResult`].
    pub async fn run_over_control_mode(
        &self,
        sender: &crate::control::ControlSender,
    ) -> Result<PlanResult, Error> {
        let mut bound: HashMap<(usize, Part), OsString> = HashMap::new();
        let mut outcomes = vec![Outcome::Skipped; self.len()];
        let mut reported = Vec::with_capacity(self.len());
        let mut dispatches = 0;

        for (index, op) in self.steps().iter().enumerate() {
            let resolve = |slot: usize, part: Part| bound.get(&(slot, part)).cloned();
            let command = op
                .render(&resolve, ())
                .ok_or_else(|| Error::CommandFailed {
                    command: op.name(),
                    exit_code: None,
                    stderr: format!(
                        "step {index} targets an object no earlier step created; \
                     a plan cannot address what it has not made"
                    ),
                })?;

            let block = sender.send(command).await?;
            dispatches += 1;

            let outcome = if block.succeeded() {
                Outcome::Complete
            } else {
                Outcome::Failed
            };
            outcomes[index] = outcome;

            let stdout = block
                .output()
                .iter()
                .flat_map(|line| {
                    let mut bytes = line.as_bytes().to_vec();
                    bytes.push(b'\n');
                    bytes
                })
                .collect::<Vec<u8>>();
            if block.succeeded() {
                let step = Step::single(index);
                bind(&mut bound, self.steps(), &step, &stdout);
            }

            reported.push(StepOutcome {
                step: Step::single(index),
                command: op.name(),
                outcomes: vec![outcome],
                // One block per command, so tmux says which one failed.
                attribution: Attribution::PerCommand,
                stdout,
                stderr: Vec::new(),
            });

            if !block.succeeded() {
                break;
            }
        }

        Ok(PlanResult {
            outcomes,
            steps: reported,
            bound,
            dispatches,
        })
    }
}