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
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
//! Errors returned by libtmux.
use std::fmt;
use std::io;
use std::time::Duration;
use crate::CommandSummary;
use crate::version::{ReleaseVersion, TmuxVersion};
/// The category of an invalid [`crate::ServerBuilder`] configuration.
///
/// Rejected path and environment bytes are never retained by this value.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum ServerConfigurationErrorKind {
/// A socket name and an explicit socket path were both configured.
ConflictingSocketSelectors,
/// A socket name was not one non-empty path component.
InvalidSocketName,
/// An explicit socket path was empty or contained a NUL byte.
InvalidSocketPath,
/// A config path was empty or contained a NUL byte.
InvalidConfigPath,
/// The requested color mode was neither 88 nor 256 colors.
InvalidColorMode,
/// The process working directory could not be captured.
WorkingDirectoryUnavailable,
/// A stable socket root could not be captured.
SocketRootUnavailable,
/// The `TMUX` variable was absent, empty, or not tmux's triple.
NotInsideTmux,
}
/// Why a control-mode connection failed.
///
/// The distinction matters to a caller: a connection that never opened is a
/// setup problem, whereas one that closed mid-command may simply mean the
/// session it was attached to has ended.
#[cfg(feature = "control-mode")]
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum ControlModeErrorKind {
/// The tmux client could not be started, or its pipes failed.
Transport,
/// tmux started without giving the crate the pipes it asked for.
///
/// Nothing a caller does causes this; it means the process could not be
/// set up as requested.
MissingPipes,
/// The connection closed before the command was answered.
Closed,
/// The command contains an argument no control-mode line can carry.
///
/// Control mode is a text protocol, so an argument that is not UTF-8
/// cannot be sent over it even though the same command would run fine as
/// a subprocess.
UnrepresentableCommand,
}
/// What tmux says when it holds no session to resolve a target against.
pub(crate) const NO_CURRENT_TARGET: &str = "no current target";
/// What a failure means for the caller.
///
/// [`Error`] carries the detail; this carries the decision. Each variant is a
/// different thing to do about it, which is why there are fewer of these than
/// there are error variants.
///
/// New kinds may be added, so match with a `_` arm.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
#[non_exhaustive]
pub enum ErrorKind {
/// The object is not on the server. Look it up again, or create it.
ObjectGone,
/// tmux ran the command and refused it. The arguments were wrong.
Refused,
/// The command did not finish in time. Retry, or allow longer.
Timeout,
/// tmux could not be run at all: not installed, or not where the server
/// was told to look. Nothing about the request will change this.
Unreachable,
/// The tmux that answered is older than this crate supports.
UnsupportedVersion,
/// The caller passed something that cannot be sent to tmux.
InvalidInput,
/// The process or connection carrying the command failed. Usually the
/// environment rather than the request, so retrying may work.
Transport,
/// tmux answered in a shape the crate could not read. Worth reporting.
Decode,
}
/// An invalid scope-specific tmux object ID.
///
/// The error records the expected sigil but never retains the rejected input.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
#[non_exhaustive]
pub struct IdParseError {
expected_sigil: char,
}
impl IdParseError {
pub(crate) const fn new(expected_sigil: char) -> Self {
Self { expected_sigil }
}
/// Return the sigil required by the requested ID scope.
///
/// # Examples
///
/// ```
/// use libtmux::SessionId;
///
/// let error = "@1".parse::<SessionId>().expect_err("@ denotes a window");
/// assert_eq!(error.expected_sigil(), '$');
/// ```
#[must_use]
pub const fn expected_sigil(self) -> char {
self.expected_sigil
}
}
impl fmt::Display for IdParseError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
formatter,
"invalid tmux ID: expected {} followed by an integer from 0 through {}",
self.expected_sigil,
u32::MAX,
)
}
}
impl std::error::Error for IdParseError {}
/// An error returned by libtmux.
///
/// Request-bearing variants expose a Core-scoped dispatch-request identity.
/// The Core allocates it before validation, so an error may carry an identity
/// even when no process was spawned. Clones of one [`crate::Server`] share the
/// allocating Core; independently constructed servers do not share its scope.
/// The identity is not globally unique, a process ID, an internal attempt ID,
/// or a control-mode protocol-block ID.
#[derive(thiserror::Error)]
#[non_exhaustive]
pub enum Error {
/// A server builder value was invalid.
#[non_exhaustive]
#[error("invalid server configuration ({kind:?})")]
InvalidServerConfiguration {
/// The path-free failure category.
kind: ServerConfigurationErrorKind,
},
/// The output from `tmux -V` did not match a supported shape.
#[error("invalid tmux version output")]
InvalidVersionOutput {
/// The number of bytes returned by tmux.
output_len: usize,
},
/// The detected tmux version does not meet the supported floor.
#[error("tmux {found} is below the minimum supported version {minimum}")]
UnsupportedTmuxVersion {
/// The detected tmux version.
found: TmuxVersion,
/// The minimum supported release.
minimum: ReleaseVersion,
},
/// The version probe process returned a non-zero status.
#[non_exhaustive]
#[error(
"tmux version probe request {request_id} ({command}) failed with exit code {exit_code:?} and signal {signal:?}"
)]
VersionProbeFailed {
/// The Core-scoped dispatch-request identity.
request_id: u64,
/// The sanitized logical version-probe command.
command: CommandSummary,
/// The process exit code, when it exited normally.
exit_code: Option<i32>,
/// The terminating signal, when it did not exit normally.
signal: Option<i32>,
},
/// A command or executable contained a byte that cannot be passed to a process.
#[non_exhaustive]
#[error("invalid {input} for tmux request {request_id}")]
InvalidCommandInput {
/// The Core-scoped dispatch-request identity.
request_id: u64,
/// The validated input category.
input: &'static str,
},
/// The configured tmux executable was not found.
#[non_exhaustive]
#[error("tmux executable was not found for request {request_id} ({command})")]
ExecutableNotFound {
/// The Core-scoped dispatch-request identity.
request_id: u64,
/// The sanitized logical command.
command: CommandSummary,
/// The operating-system spawn error.
#[source]
source: io::Error,
},
/// The tmux process could not be started.
#[non_exhaustive]
#[error("failed to start tmux request {request_id} ({command})")]
Spawn {
/// The Core-scoped dispatch-request identity.
request_id: u64,
/// The sanitized logical command.
command: CommandSummary,
/// The operating-system spawn error.
#[source]
source: io::Error,
},
/// A captured output stream could not be drained.
#[non_exhaustive]
#[error("failed to read {stream} for tmux request {request_id} ({command})")]
ReadOutput {
/// The Core-scoped dispatch-request identity.
request_id: u64,
/// The sanitized logical command.
command: CommandSummary,
/// The output stream that failed.
stream: &'static str,
/// The source error category without its potentially unsafe message.
kind: io::ErrorKind,
},
/// The direct tmux child could not be awaited.
#[non_exhaustive]
#[error("failed to wait for tmux request {request_id} ({command})")]
WaitChild {
/// The Core-scoped dispatch-request identity.
request_id: u64,
/// The sanitized logical command.
command: CommandSummary,
/// The operating-system wait error.
#[source]
source: io::Error,
},
/// A tmux request exceeded its configured deadline.
#[non_exhaustive]
#[error("tmux request {request_id} ({command}) timed out after {timeout:?}")]
Timeout {
/// The Core-scoped dispatch-request identity.
request_id: u64,
/// The sanitized logical command.
command: CommandSummary,
/// The configured deadline.
timeout: Duration,
},
/// The executor has stopped accepting requests.
#[non_exhaustive]
#[error("tmux executor is shut down for request {request_id} ({command})")]
ExecutorShutdown {
/// The Core-scoped dispatch-request identity.
request_id: u64,
/// The sanitized logical command.
command: CommandSummary,
},
/// A Core-scoped dispatch-request identity is already active in this
/// executor.
#[non_exhaustive]
#[error("tmux request {request_id} is already active ({command})")]
DuplicateRequest {
/// The duplicate Core-scoped dispatch-request identity.
request_id: u64,
/// The sanitized logical command.
command: CommandSummary,
},
/// The independent supervisor ended unexpectedly after cleaning up its child.
#[non_exhaustive]
#[error("tmux supervisor was lost for request {request_id} ({command})")]
SupervisorLost {
/// The Core-scoped dispatch-request identity.
request_id: u64,
/// The sanitized logical command.
command: CommandSummary,
},
/// A refresh could not find the object it was asked to update.
///
/// This is distinct from a connection failure: tmux answered, and the
/// object was not among the results. It has been closed or killed since
/// the handle was created.
#[non_exhaustive]
#[error("tmux no longer has {kind} {id}")]
ObjectGone {
/// The kind of object that disappeared.
kind: ObjectKind,
/// The tmux identity that is no longer present.
id: String,
},
/// A control-mode connection failed.
#[cfg(feature = "control-mode")]
#[non_exhaustive]
#[error("control mode connection failed ({kind:?})")]
ControlMode {
/// Which stage of the connection failed.
kind: ControlModeErrorKind,
/// The operating-system error, when there was one.
#[source]
source: Option<io::Error>,
},
/// A blocking runtime could not be created.
#[non_exhaustive]
#[error("could not build a runtime")]
RuntimeUnavailable {
/// The operating-system error.
#[source]
source: io::Error,
},
/// tmux rejected a command that the crate requires to succeed.
///
/// The raw [`crate::Server::cmd`] boundary keeps a nonzero status as data.
/// This variant is for operations whose whole purpose is the effect, so a
/// refusal is a failure rather than a result.
#[non_exhaustive]
#[error("tmux rejected {command} (exit {exit_code:?}): {stderr}")]
CommandFailed {
/// The tmux command that was rejected.
command: &'static str,
/// The process exit code, when it exited normally.
exit_code: Option<i32>,
/// The message tmux printed, which explains the refusal.
stderr: String,
},
/// tmux listing output could not be decoded into typed snapshots.
///
/// This reports a disagreement between the crate and the tmux that
/// answered, not an ordinary tmux failure. A command that merely reports a
/// nonzero status stays raw data at the [`crate::Server::cmd`] boundary.
#[non_exhaustive]
#[error("failed to decode {list_command} output: {detail}")]
DecodeListing {
/// The tmux list command whose output failed to decode.
list_command: &'static str,
/// Payload-free decoding metadata.
detail: ListingDecodeError,
},
}
/// The kind of tmux object a failure refers to.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum ObjectKind {
/// A tmux session.
Session,
/// A tmux window.
Window,
/// A tmux pane.
Pane,
/// A client attached to the server.
Client,
}
impl fmt::Display for ObjectKind {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(match self {
Self::Session => "session",
Self::Window => "window",
Self::Pane => "pane",
Self::Client => "client",
})
}
}
/// Payload-free metadata describing why tmux output could not be decoded.
///
/// This never retains row bytes, snapshot text, or decoded values, so it is
/// safe to log wherever the rest of [`Error`] is.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct ListingDecodeError {
inner: crate::formats::FormatCodecError,
}
impl ListingDecodeError {
pub(crate) const fn new(inner: crate::formats::FormatCodecError) -> Self {
Self { inner }
}
/// Return the zero-based row that failed, when the failure reached a row.
///
/// Plan-construction failures happen before any row is read and report
/// `None`.
#[must_use]
pub const fn row(&self) -> Option<usize> {
self.inner.row()
}
/// Return the stable tmux format name that failed, when one is known.
#[must_use]
pub const fn field_name(&self) -> Option<&'static str> {
self.inner.field_name()
}
}
impl fmt::Display for ListingDecodeError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
self.inner.fmt(formatter)
}
}
impl std::error::Error for ListingDecodeError {}
impl Error {
/// Classify a refused tmux command, recognizing a target that has gone.
///
/// tmux reports a missing target as `can't find <kind>: <target>` and
/// exits 1, the same status it uses for an argument it did not like, so
/// the message is the only thing that separates them. It is not
/// localized -- tmux has no message catalogue -- and the wording has been
/// stable across every supported release.
///
/// Anything that does not match stays a refusal, so a future rewording
/// costs the distinction rather than correctness.
/// `target` is the request's own `-t`, when it had one. tmux reports a
/// server holding no sessions as `no current target` even for a target it
/// was given, so the request is what recovers the name.
pub(crate) fn refused(
command: &'static str,
exit_code: Option<i32>,
stderr: String,
target: Option<&std::ffi::OsStr>,
) -> Self {
const MISSING: [(&str, ObjectKind); 4] = [
("can't find session:", ObjectKind::Session),
("can't find window:", ObjectKind::Window),
("can't find pane:", ObjectKind::Pane),
("can't find client:", ObjectKind::Client),
];
if let Some(target) = target.filter(|_| stderr.trim_end() == NO_CURRENT_TARGET) {
return Self::object_gone(&target.to_string_lossy());
}
for (prefix, kind) in MISSING {
if let Some(id) = stderr.trim_end().strip_prefix(prefix) {
return Self::ObjectGone {
kind,
id: id.trim().to_owned(),
};
}
}
Self::CommandFailed {
command,
exit_code,
stderr,
}
}
/// Report a tmux target that could not be resolved.
///
/// The kind comes from the sigil, which is how tmux names its objects.
/// A target that is a name rather than an ID is reported as a session,
/// because a name is what `-t` accepts for one.
fn object_gone(target: &str) -> Self {
Self::ObjectGone {
kind: match target.as_bytes().first() {
Some(b'@') => ObjectKind::Window,
Some(b'%') => ObjectKind::Pane,
_ => ObjectKind::Session,
},
id: target.to_owned(),
}
}
/// Return what this failure means for the caller.
///
/// # Examples
///
/// ```
/// # async fn example(server: &libtmux::Server) -> Result<(), libtmux::Error> {
/// use libtmux::ErrorKind;
///
/// // The shape this exists for: use it if it is there, make it if not.
/// let session = match server.session("work").await? {
/// Some(session) => session,
/// None => server.new_session("work").await?,
/// };
///
/// // And when an operation races something else removing it. The handle
/// // is cloned because killing consumes one, which is how the crate
/// // stops you from using a window you just destroyed.
/// let window = session.new_window("doomed").await?;
/// let mut stale = window.clone();
/// window.kill().await?;
///
/// let error = stale.rename("gone").await.expect_err("the window was killed");
/// assert_eq!(error.kind(), ErrorKind::ObjectGone);
/// assert!(error.is_object_gone());
/// # Ok(())
/// # }
/// ```
#[must_use]
pub fn kind(&self) -> ErrorKind {
match self {
Self::ObjectGone { .. } => ErrorKind::ObjectGone,
Self::CommandFailed { .. } => ErrorKind::Refused,
Self::Timeout { .. } => ErrorKind::Timeout,
Self::ExecutableNotFound { .. }
| Self::InvalidServerConfiguration { .. }
| Self::RuntimeUnavailable { .. } => ErrorKind::Unreachable,
Self::UnsupportedTmuxVersion { .. } => ErrorKind::UnsupportedVersion,
Self::InvalidCommandInput { .. } => ErrorKind::InvalidInput,
Self::Spawn { .. }
| Self::ReadOutput { .. }
| Self::WaitChild { .. }
| Self::VersionProbeFailed { .. }
| Self::ExecutorShutdown { .. }
| Self::DuplicateRequest { .. }
| Self::SupervisorLost { .. } => ErrorKind::Transport,
Self::InvalidVersionOutput { .. } | Self::DecodeListing { .. } => ErrorKind::Decode,
#[cfg(feature = "control-mode")]
Self::ControlMode { kind, .. } => match kind {
ControlModeErrorKind::UnrepresentableCommand => ErrorKind::InvalidInput,
ControlModeErrorKind::Transport
| ControlModeErrorKind::MissingPipes
| ControlModeErrorKind::Closed => ErrorKind::Transport,
},
}
}
/// Report whether tmux no longer has the object the call named.
///
/// The most common branch a caller writes, and the one that is easy to
/// get wrong: an object disappearing is an ordinary race, not a failure
/// of the request.
#[must_use]
pub fn is_object_gone(&self) -> bool {
self.kind() == ErrorKind::ObjectGone
}
/// Report whether making the same call again could succeed.
///
/// True for a timeout and for a transport failure, which are usually the
/// machine rather than the request. False for anything tmux answered,
/// which will be answered the same way again.
#[must_use]
pub fn is_transient(&self) -> bool {
matches!(self.kind(), ErrorKind::Timeout | ErrorKind::Transport)
}
#[cfg(feature = "control-mode")]
pub(crate) const fn control_mode(source: io::Error) -> Self {
Self::ControlMode {
kind: ControlModeErrorKind::Transport,
source: Some(source),
}
}
/// tmux started but did not provide the pipes to talk over.
#[cfg(feature = "control-mode")]
pub(crate) const fn control_mode_pipes() -> Self {
Self::ControlMode {
kind: ControlModeErrorKind::MissingPipes,
source: None,
}
}
/// tmux closed the connection before answering.
#[cfg(feature = "control-mode")]
/// A command carries an argument no control-mode line can express.
#[cfg(feature = "control-mode")]
pub(crate) const fn control_mode_unrepresentable() -> Self {
Self::ControlMode {
kind: ControlModeErrorKind::UnrepresentableCommand,
source: None,
}
}
/// The connection closed before the command was answered.
#[cfg(feature = "control-mode")]
pub(crate) const fn control_mode_closed() -> Self {
Self::ControlMode {
kind: ControlModeErrorKind::Closed,
source: None,
}
}
#[cfg(feature = "blocking")]
pub(crate) const fn runtime_unavailable(source: io::Error) -> Self {
Self::RuntimeUnavailable { source }
}
pub(crate) const fn invalid_server_configuration(kind: ServerConfigurationErrorKind) -> Self {
Self::InvalidServerConfiguration { kind }
}
pub(crate) fn version_probe_failed(
request_id: u64,
command: CommandSummary,
exit_code: Option<i32>,
signal: Option<i32>,
) -> Self {
Self::VersionProbeFailed {
request_id,
command,
exit_code,
signal,
}
}
pub(crate) fn from_invalid_version_output(output_len: usize) -> Self {
Self::InvalidVersionOutput { output_len }
}
pub(crate) fn unsupported_tmux_version(found: TmuxVersion, minimum: ReleaseVersion) -> Self {
Self::UnsupportedTmuxVersion { found, minimum }
}
pub(crate) fn invalid_command_input(request_id: u64, input: &'static str) -> Self {
Self::InvalidCommandInput { request_id, input }
}
pub(crate) fn spawn(
request_id: u64,
command: CommandSummary,
source: io::Error,
executable_not_found: bool,
) -> Self {
if executable_not_found {
Self::ExecutableNotFound {
request_id,
command,
source,
}
} else {
Self::Spawn {
request_id,
command,
source,
}
}
}
pub(crate) fn read_output(
request_id: u64,
command: CommandSummary,
stream: &'static str,
kind: io::ErrorKind,
) -> Self {
Self::ReadOutput {
request_id,
command,
stream,
kind,
}
}
pub(crate) fn wait_child(request_id: u64, command: CommandSummary, source: io::Error) -> Self {
Self::WaitChild {
request_id,
command,
source,
}
}
pub(crate) fn timeout(request_id: u64, command: CommandSummary, timeout: Duration) -> Self {
Self::Timeout {
request_id,
command,
timeout,
}
}
pub(crate) fn executor_shutdown(request_id: u64, command: CommandSummary) -> Self {
Self::ExecutorShutdown {
request_id,
command,
}
}
pub(crate) fn duplicate_request(request_id: u64, command: CommandSummary) -> Self {
Self::DuplicateRequest {
request_id,
command,
}
}
pub(crate) fn supervisor_lost(request_id: u64, command: CommandSummary) -> Self {
Self::SupervisorLost {
request_id,
command,
}
}
/// Return the length of the invalid `tmux -V` output, when present.
///
/// The error never retains the process output itself.
///
/// # Examples
///
/// ```
/// use libtmux::TmuxVersion;
///
/// let output = b"invalid\n";
/// let error = TmuxVersion::parse_output(output).expect_err("output is invalid");
/// assert_eq!(error.invalid_version_output_len(), Some(output.len()));
/// ```
#[must_use]
pub fn invalid_version_output_len(&self) -> Option<usize> {
match self {
Self::InvalidVersionOutput { output_len } => Some(*output_len),
_ => None,
}
}
/// Return the detected version for a minimum-version error.
///
/// # Examples
///
/// ```
/// use libtmux::TmuxVersion;
///
/// let version = TmuxVersion::parse_output(b"tmux 3.2\n")?;
/// let error = version.ensure_supported().expect_err("3.2 is unsupported");
/// assert_eq!(error.found_version(), Some(&version));
/// # Ok::<(), libtmux::Error>(())
/// ```
#[must_use]
pub fn found_version(&self) -> Option<&TmuxVersion> {
match self {
Self::UnsupportedTmuxVersion { found, .. } => Some(found),
_ => None,
}
}
/// Return the required release for a minimum-version error.
///
/// # Examples
///
/// ```
/// use libtmux::TmuxVersion;
///
/// let version = TmuxVersion::parse_output(b"tmux 3.2\n")?;
/// let error = version.ensure_supported().expect_err("3.2 is unsupported");
/// assert_eq!(error.minimum_version(), Some(&TmuxVersion::MIN_SUPPORTED));
/// # Ok::<(), libtmux::Error>(())
/// ```
#[must_use]
pub fn minimum_version(&self) -> Option<&ReleaseVersion> {
match self {
Self::UnsupportedTmuxVersion { minimum, .. } => Some(minimum),
_ => None,
}
}
}
impl fmt::Debug for Error {
#[allow(
clippy::too_many_lines,
reason = "exhaustive safe formatting keeps every public error variant byte-free"
)]
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::InvalidServerConfiguration { kind } => formatter
.debug_struct("InvalidServerConfiguration")
.field("kind", kind)
.finish(),
Self::InvalidVersionOutput { output_len } => formatter
.debug_struct("InvalidVersionOutput")
.field("output_len", output_len)
.finish(),
Self::UnsupportedTmuxVersion { found, minimum } => formatter
.debug_struct("UnsupportedTmuxVersion")
.field("found", found)
.field("minimum", minimum)
.finish(),
Self::VersionProbeFailed {
request_id,
command,
exit_code,
signal,
} => formatter
.debug_struct("VersionProbeFailed")
.field("request_id", request_id)
.field("command", command)
.field("exit_code", exit_code)
.field("signal", signal)
.finish_non_exhaustive(),
Self::InvalidCommandInput { request_id, input } => formatter
.debug_struct("InvalidCommandInput")
.field("request_id", request_id)
.field("input", input)
.finish(),
Self::ExecutableNotFound {
request_id,
command,
source,
} => formatter
.debug_struct("ExecutableNotFound")
.field("request_id", request_id)
.field("command", command)
.field("source", source)
.finish(),
Self::Spawn {
request_id,
command,
source,
} => formatter
.debug_struct("Spawn")
.field("request_id", request_id)
.field("command", command)
.field("source", source)
.finish(),
Self::ReadOutput {
request_id,
command,
stream,
kind,
} => formatter
.debug_struct("ReadOutput")
.field("request_id", request_id)
.field("command", command)
.field("stream", stream)
.field("kind", kind)
.finish(),
Self::WaitChild {
request_id,
command,
source,
} => formatter
.debug_struct("WaitChild")
.field("request_id", request_id)
.field("command", command)
.field("source", source)
.finish(),
Self::Timeout {
request_id,
command,
timeout,
} => formatter
.debug_struct("Timeout")
.field("request_id", request_id)
.field("command", command)
.field("timeout", timeout)
.finish(),
Self::ExecutorShutdown {
request_id,
command,
} => formatter
.debug_struct("ExecutorShutdown")
.field("request_id", request_id)
.field("command", command)
.finish(),
Self::DuplicateRequest {
request_id,
command,
} => formatter
.debug_struct("DuplicateRequest")
.field("request_id", request_id)
.field("command", command)
.finish(),
Self::SupervisorLost {
request_id,
command,
} => formatter
.debug_struct("SupervisorLost")
.field("request_id", request_id)
.field("command", command)
.finish(),
#[cfg(feature = "control-mode")]
Self::ControlMode { kind, source } => formatter
.debug_struct("ControlMode")
.field("kind", kind)
.field("kind", &source.as_ref().map(io::Error::kind))
.finish(),
Self::RuntimeUnavailable { source } => formatter
.debug_struct("RuntimeUnavailable")
.field("kind", &source.kind())
.finish(),
Self::CommandFailed {
command,
exit_code,
stderr,
} => formatter
.debug_struct("CommandFailed")
.field("command", command)
.field("exit_code", exit_code)
.field("stderr", stderr)
.finish(),
Self::ObjectGone { kind, id } => formatter
.debug_struct("ObjectGone")
.field("kind", kind)
.field("id", id)
.finish(),
Self::DecodeListing {
list_command,
detail,
} => formatter
.debug_struct("DecodeListing")
.field("list_command", list_command)
.field("detail", detail)
.finish(),
}
}
}
#[cfg(test)]
mod compat_tests {
/// Pin the tmux wording that separates a missing target from a refusal.
///
/// `Error::refused` reads tmux's stderr because tmux exits 1 for both, so
/// this asserts against the tmux the lane is running rather than against
/// the source this was written from. Every compatibility lane runs it, so
/// a release that rewords these is a failure here rather than a silently
/// wrong `is_object_gone` in the field.
#[cfg(feature = "test-support")]
#[tokio::test]
async fn real_tmux_compat_error_missing_target_wording_is_recognized() {
use crate::ErrorKind;
use crate::test::TestServer;
let guard = TestServer::builder().start().await.expect("tmux starts");
let server = guard.server();
let session = server.new_session("compat-missing").await.expect("session");
// One live session, so tmux can resolve a current target and reports
// the specific object it could not find.
for (label, error) in [
(
"window",
server
.window_by_id(&"@4242".parse().expect("a window id"))
.await
.map(|found| assert!(found.is_none(), "the window does not exist"))
.err(),
),
(
"pane",
server
.pane_by_id(&"%4242".parse().expect("a pane id"))
.await
.map(|found| assert!(found.is_none(), "the pane does not exist"))
.err(),
),
] {
assert!(error.is_none(), "a lookup reports absence, not {label}");
}
// A mutation against a target tmux does not have is where the wording
// matters: it is the only signal separating this from a bad argument.
let mut window = session.try_windows().await.expect("windows").remove(0);
let doomed = session
.new_window(crate::NewWindowOptions::new("doomed").command("sleep 300"))
.await
.expect("window");
let mut stale = doomed.clone();
doomed.kill().await.expect("the window is killed");
let error = stale.rename("gone").await.expect_err("the window is gone");
assert_eq!(
error.kind(),
ErrorKind::ObjectGone,
"tmux 'can't find window' is recognized: {error}",
);
// And a refusal that is not a missing target stays a refusal, so the
// classification is not simply calling everything gone.
let refused = server
.delete_buffer("never-existed")
.await
.expect_err("tmux has no such buffer");
assert_eq!(refused.kind(), ErrorKind::Refused, "{refused}");
// With no session left, tmux cannot resolve a current target and says
// so instead, for the same request. Both wordings mean gone.
window
.rename("last")
.await
.expect("the window still exists");
session.kill().await.expect("the session is killed");
let error = stale
.rename("still gone")
.await
.expect_err("the window is gone");
assert_eq!(
error.kind(),
ErrorKind::ObjectGone,
"tmux 'no current target' is recognized: {error}",
);
guard.shutdown().await.expect("tmux fixture shuts down");
}
}