libtmux 0.1.0-alpha.16

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
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
//! Tmux release parsing and capability checks.

use std::cmp::Ordering;
use std::fmt;
use std::str;

use crate::Error;

#[derive(Clone, Copy, Eq, Hash, Ord, PartialEq, PartialOrd)]
enum SuffixKind {
    /// Master before the release branch is cut: `next-X.Y`.
    Next,
    ReleaseCandidate(u16),
    Final,
    Patch(u8),
}

/// The suffix of a numbered tmux release.
///
/// Release candidates sort before a final release, while lowercase patch
/// letters sort after it.
///
/// # Examples
///
/// ```
/// use libtmux::{ReleaseSuffix, ReleaseVersion};
///
/// // tmux's two suffix shapes order differently: a patch letter comes *after*
/// // the plain release, and a release candidate comes before it.
/// let plain = ReleaseVersion::new(3, 5, ReleaseSuffix::FINAL);
/// let patched = ReleaseVersion::new(3, 5, ReleaseSuffix::patch('a').expect("a patch letter"));
/// let candidate = ReleaseVersion::new(
///     3,
///     5,
///     ReleaseSuffix::release_candidate(1).expect("one is nonzero"),
/// );
///
/// assert!(candidate < plain);
/// assert!(plain < patched);
///
/// // Only those two shapes exist, so anything else is rejected rather than
/// // guessed at.
/// assert_eq!(ReleaseSuffix::patch('B'), None);
/// assert_eq!(ReleaseSuffix::release_candidate(0), None);
/// ```
#[derive(Clone, Copy, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct ReleaseSuffix(SuffixKind);

impl ReleaseSuffix {
    /// An unnumbered `-rc` suffix, canonically equivalent to `-rc1`.
    pub const RELEASE_CANDIDATE: Self = Self(SuffixKind::ReleaseCandidate(1));

    /// A final release with no suffix.
    pub const FINAL: Self = Self(SuffixKind::Final);

    /// A development build of the release, ranked below its candidates.
    pub(crate) const NEXT: Self = Self(SuffixKind::Next);

    /// The second candidate, the earliest 3.8 build whose layouts are JSON.
    pub(crate) const RELEASE_CANDIDATE_2: Self = Self(SuffixKind::ReleaseCandidate(2));

    pub(crate) const PATCH_A: Self = Self(SuffixKind::Patch(b'a'));

    /// Construct a numbered release-candidate suffix.
    ///
    /// Candidate one displays canonically as `-rc`. Zero is not a valid
    /// release-candidate number.
    ///
    /// # Examples
    ///
    /// ```
    /// use libtmux::ReleaseSuffix;
    ///
    /// let suffix = ReleaseSuffix::release_candidate(2).expect("two is nonzero");
    /// assert_eq!(suffix.release_candidate_number(), Some(2));
    /// assert_eq!(ReleaseSuffix::release_candidate(0), None);
    /// ```
    #[must_use]
    pub const fn release_candidate(number: u16) -> Option<Self> {
        if number == 0 {
            None
        } else {
            Some(Self(SuffixKind::ReleaseCandidate(number)))
        }
    }

    /// Construct a lowercase patch-letter suffix.
    ///
    /// Returns `None` when `letter` is not an ASCII lowercase letter.
    ///
    /// # Examples
    ///
    /// ```
    /// use libtmux::ReleaseSuffix;
    ///
    /// let suffix = ReleaseSuffix::patch('b').expect("b is a patch letter");
    /// assert_eq!(suffix.patch_letter(), Some('b'));
    /// assert_eq!(ReleaseSuffix::patch('B'), None);
    /// ```
    #[must_use]
    pub fn patch(letter: char) -> Option<Self> {
        if !letter.is_ascii_lowercase() {
            return None;
        }

        u8::try_from(letter as u32)
            .ok()
            .map(|letter| Self(SuffixKind::Patch(letter)))
    }

    /// Return the lowercase patch letter, if this is a patch release.
    ///
    /// # Examples
    ///
    /// ```
    /// use libtmux::ReleaseSuffix;
    ///
    /// assert_eq!(ReleaseSuffix::FINAL.patch_letter(), None);
    /// assert_eq!(ReleaseSuffix::patch('a').and_then(|value| value.patch_letter()), Some('a'));
    /// ```
    #[must_use]
    pub fn patch_letter(self) -> Option<char> {
        match self.0 {
            SuffixKind::Patch(letter) => Some(char::from(letter)),
            SuffixKind::Next | SuffixKind::ReleaseCandidate(_) | SuffixKind::Final => None,
        }
    }

    /// Return the release-candidate number, if present.
    ///
    /// The unnumbered `-rc` spelling has the effective number one.
    ///
    /// # Examples
    ///
    /// ```
    /// use libtmux::ReleaseSuffix;
    ///
    /// assert_eq!(ReleaseSuffix::RELEASE_CANDIDATE.release_candidate_number(), Some(1));
    /// assert_eq!(ReleaseSuffix::FINAL.release_candidate_number(), None);
    /// ```
    #[must_use]
    pub const fn release_candidate_number(self) -> Option<u16> {
        match self.0 {
            SuffixKind::ReleaseCandidate(number) => Some(number),
            SuffixKind::Next | SuffixKind::Final | SuffixKind::Patch(_) => None,
        }
    }

    /// Return whether this suffix marks a final release.
    ///
    /// # Examples
    ///
    /// ```
    /// use libtmux::ReleaseSuffix;
    ///
    /// assert!(ReleaseSuffix::FINAL.is_final());
    /// assert!(!ReleaseSuffix::RELEASE_CANDIDATE.is_final());
    /// ```
    #[must_use]
    pub const fn is_final(self) -> bool {
        matches!(self.0, SuffixKind::Final)
    }

    /// Return whether this suffix marks a release candidate.
    ///
    /// # Examples
    ///
    /// ```
    /// use libtmux::ReleaseSuffix;
    ///
    /// assert!(ReleaseSuffix::RELEASE_CANDIDATE.is_release_candidate());
    /// assert!(!ReleaseSuffix::FINAL.is_release_candidate());
    /// ```
    #[must_use]
    pub const fn is_release_candidate(self) -> bool {
        matches!(self.0, SuffixKind::ReleaseCandidate(_))
    }
}

impl fmt::Debug for ReleaseSuffix {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self.0 {
            SuffixKind::ReleaseCandidate(number) => formatter
                .debug_tuple("ReleaseCandidate")
                .field(&number)
                .finish(),
            SuffixKind::Next => formatter.write_str("Next"),
            SuffixKind::Final => formatter.write_str("Final"),
            SuffixKind::Patch(letter) => formatter
                .debug_tuple("Patch")
                .field(&char::from(letter))
                .finish(),
        }
    }
}

impl fmt::Display for ReleaseSuffix {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self.0 {
            SuffixKind::Next => formatter.write_str("-next"),
            SuffixKind::ReleaseCandidate(1) => formatter.write_str("-rc"),
            SuffixKind::ReleaseCandidate(number) => write!(formatter, "-rc{number}"),
            SuffixKind::Final => Ok(()),
            SuffixKind::Patch(letter) => write!(formatter, "{}", char::from(letter)),
        }
    }
}

/// A numbered tmux release.
///
/// # Examples
///
/// ```
/// use libtmux::{ReleaseSuffix, ReleaseVersion};
///
/// // tmux numbers a patch with a letter, so `3.5a` is later than `3.5`.
/// let plain = ReleaseVersion::new(3, 5, ReleaseSuffix::FINAL);
/// let patched = ReleaseVersion::new(3, 5, ReleaseSuffix::patch('a').expect("a patch letter"));
/// assert!(patched > plain);
/// ```
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct ReleaseVersion {
    major: u16,
    minor: u16,
    suffix: ReleaseSuffix,
}

impl ReleaseVersion {
    /// Construct a numbered tmux release.
    ///
    /// # Examples
    ///
    /// ```
    /// use libtmux::{ReleaseSuffix, ReleaseVersion};
    ///
    /// let release = ReleaseVersion::new(3, 7, ReleaseSuffix::FINAL);
    /// assert_eq!(release.to_string(), "3.7");
    /// ```
    #[must_use]
    pub const fn new(major: u16, minor: u16, suffix: ReleaseSuffix) -> Self {
        Self {
            major,
            minor,
            suffix,
        }
    }

    /// Return the major release number.
    ///
    /// # Examples
    ///
    /// ```
    /// use libtmux::{ReleaseSuffix, ReleaseVersion};
    ///
    /// let release = ReleaseVersion::new(3, 7, ReleaseSuffix::FINAL);
    /// assert_eq!(release.major(), 3);
    /// ```
    #[must_use]
    pub const fn major(self) -> u16 {
        self.major
    }

    /// Return the minor release number.
    ///
    /// # Examples
    ///
    /// ```
    /// use libtmux::{ReleaseSuffix, ReleaseVersion};
    ///
    /// let release = ReleaseVersion::new(3, 7, ReleaseSuffix::FINAL);
    /// assert_eq!(release.minor(), 7);
    /// ```
    #[must_use]
    pub const fn minor(self) -> u16 {
        self.minor
    }

    /// Return the release suffix.
    ///
    /// # Examples
    ///
    /// ```
    /// use libtmux::{ReleaseSuffix, ReleaseVersion};
    ///
    /// let release = ReleaseVersion::new(3, 7, ReleaseSuffix::RELEASE_CANDIDATE);
    /// assert_eq!(release.suffix(), ReleaseSuffix::RELEASE_CANDIDATE);
    /// ```
    #[must_use]
    pub const fn suffix(self) -> ReleaseSuffix {
        self.suffix
    }
}

impl fmt::Display for ReleaseVersion {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(formatter, "{}.{}{}", self.major, self.minor, self.suffix)
    }
}

/// A parsed raw tmux version.
///
/// Numbered releases expose an ordered [`ReleaseVersion`]. Development
/// identifiers preserve their token and remain unordered relative to numbered
/// releases.
///
/// # Examples
///
/// ```
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build()?;
/// # runtime.block_on(async {
/// let guard = libtmux::test::TestServer::new().await?;
/// let version = guard.server().capabilities().await?.tmux_version().clone();
///
/// // A development build carries no numbered release, so a caller asks
/// // `meets` rather than comparing the text tmux printed.
/// assert!(version.release().is_some() || version.is_development());
/// assert!(!version.raw().is_empty());
///
/// guard.shutdown().await?;
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// # })?;
/// # Ok(())
/// # }
/// ```
#[derive(Clone, Debug)]
pub struct TmuxVersion {
    raw: Box<str>,
    release: Option<ReleaseVersion>,
}

/// The longest version token an unrecognized report may carry into an error.
const MAX_REPORTED_TOKEN: usize = 64;

impl TmuxVersion {
    /// The minimum supported tmux release, 3.3a.
    pub const MIN_SUPPORTED: ReleaseVersion = ReleaseVersion::new(3, 3, ReleaseSuffix::PATCH_A);

    /// Parse the exact output from `tmux -V`.
    ///
    /// The output must contain one nonempty program-name token, one version
    /// token, and one trailing newline. Invalid process output is never stored
    /// in the returned error.
    ///
    /// # Errors
    ///
    /// Returns [`Error::InvalidVersionOutput`] for malformed framing or version
    /// syntax, unsupported characters, extra lines, or invalid UTF-8.
    ///
    /// # Examples
    ///
    /// ```
    /// use libtmux::TmuxVersion;
    ///
    /// let version = TmuxVersion::parse_output(b"tmux 3.7b\n")?;
    /// assert_eq!(version.raw(), "3.7b");
    /// # Ok::<(), libtmux::Error>(())
    /// ```
    pub fn parse_output(output: &[u8]) -> Result<Self, Error> {
        let raw = parse_output_frame(output)
            .ok_or_else(|| Error::from_invalid_version_output(output.len()))?;

        let release = match raw.as_bytes().first() {
            Some(first) if first.is_ascii_digit() => Some(
                parse_release(raw)
                    .ok_or_else(|| Error::from_invalid_version_output(output.len()))?,
            ),
            Some(_) if is_development_identifier(raw) => None,
            _ => return Err(Error::from_invalid_version_output(output.len())),
        };

        Ok(Self {
            raw: raw.into(),
            release,
        })
    }

    /// Read the version a daemon or `tmux -V` reported, for the version check.
    ///
    /// Strict like [`TmuxVersion::parse_output`], except that a well-framed
    /// report whose token names no release is
    /// [`Error::UnrecognizedTmuxVersion`] rather than invalid output: the
    /// daemon answered, and the answer cannot be compared with the floor. The
    /// token is kept for the message only when it is at most
    /// [`MAX_REPORTED_TOKEN`] printable ASCII bytes. Anything else is
    /// [`Error::InvalidVersionOutput`] with `reported_len` as its length.
    pub(crate) fn parse_report(output: &[u8], reported_len: usize) -> Result<Self, Error> {
        match Self::parse_output(output) {
            Err(Error::InvalidVersionOutput { .. }) => {
                match parse_output_frame(output).filter(|token| {
                    token.len() <= MAX_REPORTED_TOKEN && token.bytes().all(|b| b.is_ascii_graphic())
                }) {
                    Some(token) => Err(Error::unrecognized_tmux_version(Self {
                        raw: token.into(),
                        release: None,
                    })),
                    None => Err(Error::from_invalid_version_output(reported_len)),
                }
            }
            other => other.map_err(|error| match error {
                Error::InvalidVersionOutput { .. } => {
                    Error::from_invalid_version_output(reported_len)
                }
                other => other,
            }),
        }
    }

    /// Return the exact version token without the program-name prefix or newline.
    ///
    /// # Examples
    ///
    /// ```
    /// use libtmux::TmuxVersion;
    ///
    /// let version = TmuxVersion::parse_output(b"tmux next-3.8\n")?;
    /// assert_eq!(version.raw(), "next-3.8");
    /// # Ok::<(), libtmux::Error>(())
    /// ```
    #[must_use]
    pub fn raw(&self) -> &str {
        &self.raw
    }

    /// Return the numbered release, or `None` for a development identifier.
    ///
    /// # Examples
    ///
    /// ```
    /// use libtmux::TmuxVersion;
    ///
    /// let release = TmuxVersion::parse_output(b"tmux 3.7\n")?;
    /// let development = TmuxVersion::parse_output(b"tmux master\n")?;
    /// assert_eq!(release.release().map(|value| value.major()), Some(3));
    /// assert_eq!(development.release(), None);
    /// # Ok::<(), libtmux::Error>(())
    /// ```
    #[must_use]
    pub const fn release(&self) -> Option<&ReleaseVersion> {
        self.release.as_ref()
    }

    /// Return whether this is a development identifier.
    ///
    /// # Examples
    ///
    /// ```
    /// use libtmux::TmuxVersion;
    ///
    /// let version = TmuxVersion::parse_output(b"tmux master\n")?;
    /// assert!(version.is_development());
    /// # Ok::<(), libtmux::Error>(())
    /// ```
    #[must_use]
    pub const fn is_development(&self) -> bool {
        self.release.is_none()
    }

    /// Return the release whose in-tree behavior this version carries.
    ///
    /// A numbered release returns itself. A `next-X.Y` identifier returns
    /// `X.Y` ranked below its release candidates: its tree is master before
    /// the release branch is cut, so it carries what shipped in earlier
    /// releases but not yet the changes that complete `X.Y`. `master` returns
    /// `None` because it names no release.
    ///
    /// Unlike [`TmuxVersion::meets`], this does not clamp development
    /// identifiers to the crate's minimum supported release. It answers "which
    /// tmux source is running", not "may this version be relied on", so it
    /// suits behavior windows that both open and close at known releases.
    pub(crate) fn behavior_release(&self) -> Option<ReleaseVersion> {
        self.release.or_else(|| parse_next_release(&self.raw))
    }

    /// Return whether this version supports a required numbered release.
    ///
    /// Development identifiers meet only requirements at or below the crate's
    /// minimum supported release; they are not promoted to an invented release.
    /// A `next-X.Y` identifier's own release number is not read here even
    /// when `required` is that same `X.Y` or earlier -- this is a floor
    /// check, not a capability check. Asking "does this tree already contain
    /// a capability that shipped at version V" is [`Self::has_behavior`]'s
    /// question, not this one; a call site gating a specific capability
    /// behind a release above [`Self::MIN_SUPPORTED`] almost always wants
    /// that instead, or it refuses a development build that already has the
    /// capability it is checking for.
    ///
    /// # Examples
    ///
    /// ```
    /// use libtmux::TmuxVersion;
    ///
    /// let version = TmuxVersion::parse_output(b"tmux 3.3a\n")?;
    /// assert!(version.meets(&TmuxVersion::MIN_SUPPORTED));
    /// # Ok::<(), libtmux::Error>(())
    /// ```
    ///
    /// The English verb suggests this answers "is a capability available",
    /// but on a development build it can refuse one that is already there:
    ///
    /// ```
    /// use libtmux::{ReleaseSuffix, ReleaseVersion, TmuxVersion};
    ///
    /// let next = TmuxVersion::parse_output(b"tmux next-3.9\n")?;
    /// let capture_line_flags = ReleaseVersion::new(3, 7, ReleaseSuffix::FINAL);
    ///
    /// // `next-3.9`'s tree already has 3.7's behavior, but this clamps every
    /// // development identifier to the crate's floor, so it says no anyway.
    /// // `TmuxVersion::has_behavior` is the question that says yes.
    /// assert!(!next.meets(&capture_line_flags));
    /// assert!(next.has_behavior(&capture_line_flags));
    /// # Ok::<(), libtmux::Error>(())
    /// ```
    #[must_use]
    pub fn meets(&self, required: &ReleaseVersion) -> bool {
        match self.release {
            Some(release) => release >= *required,
            None if *required > Self::MIN_SUPPORTED => false,
            None if self.raw.as_ref() == "master" => true,
            None => parse_next_release(&self.raw).is_some_and(|release| release >= *required),
        }
    }

    /// Report whether this version's tree carries a capability's behavior.
    ///
    /// The shared rule behind `Self::require`: a development identifier
    /// asks its `behavior_release`, never clamped to the crate's minimum
    /// supported release. Both this and `require` call it, so they cannot
    /// drift apart the way two independently written rules could.
    fn behavior_satisfies(&self, needs: ReleaseVersion) -> bool {
        self.behavior_release()
            .is_none_or(|release| release >= needs)
    }

    /// Report whether this version's tree carries a capability's behavior.
    ///
    /// This is `Self::require`'s refusal rule in boolean form, so a caller
    /// gating a specific capability -- or a test predicting which branch
    /// `require` takes -- uses the same rule `require` does, rather than an
    /// independently derived one that can drift from it. [`Self::meets`] is
    /// a different, deliberately non-identical rule: it clamps *every*
    /// development identifier -- `next-X.Y` included, not only a bare
    /// `master` -- to "no more than the crate's minimum supported release",
    /// so it refuses any requirement above that floor regardless of what the
    /// build's own next-release number is. This reads `next-X.Y` as the real
    /// release `X.Y` instead, so the two disagree for any development build
    /// checked against a requirement above the floor: [`crate::since`] holds
    /// several, and this crate's own tmux-matrix probe self-reports
    /// `next-3.9`. Checking a capability with `meets` instead of this
    /// refuses that capability on a development build that already has it.
    ///
    /// # Examples
    ///
    /// ```
    /// use libtmux::{ReleaseSuffix, ReleaseVersion, TmuxVersion};
    ///
    /// let next = TmuxVersion::parse_output(b"tmux next-3.9\n")?;
    /// let capture_line_flags = ReleaseVersion::new(3, 7, ReleaseSuffix::FINAL);
    ///
    /// // `next-3.9` already contains 3.7's behavior, so this reports it --
    /// // unlike `meets`, which clamps every development identifier to the
    /// // floor and would refuse it.
    /// assert!(next.has_behavior(&capture_line_flags));
    /// assert!(!next.meets(&capture_line_flags));
    /// # Ok::<(), libtmux::Error>(())
    /// ```
    #[must_use]
    pub fn has_behavior(&self, needs: &ReleaseVersion) -> bool {
        self.behavior_satisfies(*needs)
    }

    /// Refuse a capability this release is too old for.
    ///
    /// tmux usually accepts an unknown flag and ignores it, so without this
    /// "your tmux is too old" arrives as "the command did nothing". A
    /// development build carries no numbered release to compare and is taken
    /// at its word rather than refused.
    ///
    /// # Errors
    ///
    /// Returns [`Error::UnsupportedCapability`] when this release is below
    /// `needs`.
    pub(crate) fn require(
        &self,
        capability: &'static str,
        needs: ReleaseVersion,
    ) -> Result<(), Error> {
        if !self.behavior_satisfies(needs) {
            return Err(Error::UnsupportedCapability {
                capability,
                needs,
                found: self.clone(),
            });
        }

        Ok(())
    }

    /// Require a numbered release to meet the minimum supported version.
    ///
    /// A numbered `next-X.Y` report can establish the floor. An undated
    /// `master` report remains diagnostic and cannot qualify dispatch.
    ///
    /// # Errors
    ///
    /// Returns [`Error::UnsupportedTmuxVersion`] when the detected release is
    /// below tmux 3.3a, and [`Error::UnrecognizedTmuxVersion`] for a bare
    /// `master`, which names no release. The version check also refuses a
    /// daemon report that is well framed but names no release at all
    /// (`openbsd-*`, `3.3a-dev`) as [`Error::UnrecognizedTmuxVersion`], before
    /// a [`TmuxVersion`] exists to call this on.
    ///
    /// # Examples
    ///
    /// ```
    /// use libtmux::TmuxVersion;
    ///
    /// let version = TmuxVersion::parse_output(b"tmux 3.3a\n")?;
    /// version.ensure_supported()?;
    /// # Ok::<(), libtmux::Error>(())
    /// ```
    pub fn ensure_supported(&self) -> Result<(), Error> {
        match self.release.or_else(|| parse_next_release(&self.raw)) {
            Some(release) if release >= Self::MIN_SUPPORTED => Ok(()),
            Some(_) => Err(Error::unsupported_tmux_version(
                self.clone(),
                Self::MIN_SUPPORTED,
            )),
            None => Err(Error::unrecognized_tmux_version(self.clone())),
        }
    }

    /// The version of a daemon too old to run the version probe.
    ///
    /// `run-shell -C` arrived in tmux 3.2, so an older daemon refuses the
    /// probe's flag and never reports a version of its own.
    pub(crate) fn older_than_probe() -> Self {
        Self {
            raw: "older than 3.2".into(),
            release: None,
        }
    }
}

impl fmt::Display for TmuxVersion {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(&self.raw)
    }
}

impl PartialEq for TmuxVersion {
    fn eq(&self, other: &Self) -> bool {
        match (self.release, other.release) {
            (Some(left), Some(right)) => left == right,
            (None, None) => self.raw == other.raw,
            (Some(_), None) | (None, Some(_)) => false,
        }
    }
}

impl Eq for TmuxVersion {}

impl PartialOrd for TmuxVersion {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        match (self.release, other.release) {
            (Some(left), Some(right)) => Some(left.cmp(&right)),
            (None, None) if self.raw == other.raw => Some(Ordering::Equal),
            _ => None,
        }
    }
}

fn parse_release(raw: &str) -> Option<ReleaseVersion> {
    let (major, remainder) = raw.split_once('.')?;
    let minor_end = remainder
        .find(|character: char| !character.is_ascii_digit())
        .unwrap_or(remainder.len());
    let (minor, suffix) = remainder.split_at(minor_end);
    let major = parse_u16_component(major)?;
    let minor = parse_u16_component(minor)?;
    let suffix = parse_release_suffix(suffix)?;

    Some(ReleaseVersion::new(major, minor, suffix))
}

fn is_development_identifier(raw: &str) -> bool {
    raw == "master" || parse_next_release(raw).is_some()
}

fn parse_next_release(raw: &str) -> Option<ReleaseVersion> {
    let (major, minor) = raw.strip_prefix("next-")?.split_once('.')?;
    Some(ReleaseVersion::new(
        parse_u16_component(major)?,
        parse_u16_component(minor)?,
        ReleaseSuffix::NEXT,
    ))
}

fn parse_release_suffix(suffix: &str) -> Option<ReleaseSuffix> {
    if suffix.is_empty() {
        return Some(ReleaseSuffix::FINAL);
    }
    if suffix == "-rc" {
        return Some(ReleaseSuffix::RELEASE_CANDIDATE);
    }
    if let Some(number) = suffix.strip_prefix("-rc") {
        return ReleaseSuffix::release_candidate(parse_u16_component(number)?);
    }
    match suffix.as_bytes() {
        [letter] if letter.is_ascii_lowercase() => Some(ReleaseSuffix(SuffixKind::Patch(*letter))),
        _ => None,
    }
}

fn parse_u16_component(component: &str) -> Option<u16> {
    if component.is_empty()
        || (component.len() > 1 && component.starts_with('0'))
        || !component.bytes().all(|byte| byte.is_ascii_digit())
    {
        return None;
    }
    component.parse().ok()
}

fn parse_output_frame(output: &[u8]) -> Option<&str> {
    let line = output.strip_suffix(b"\n")?;
    let separator = line.iter().position(|byte| *byte == b' ')?;
    let program = line.get(..separator)?;
    let version = line.get(separator + 1..)?;
    if program.is_empty()
        || version.is_empty()
        || program
            .iter()
            .any(|byte| byte.is_ascii_whitespace() || byte.is_ascii_control())
        || version
            .iter()
            .any(|byte| byte.is_ascii_whitespace() || byte.is_ascii_control())
    {
        return None;
    }
    str::from_utf8(version).ok()
}

/// The tmux release each version-gated capability arrived in.
///
/// Every method that can answer [`crate::Error::UnsupportedCapability`] names
/// its floor here, so a caller can ask before it calls rather than learning
/// from the failure. Compare with [`TmuxVersion::meets`].
///
/// # Examples
///
/// ```
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build()?;
/// # runtime.block_on(async {
/// let guard = libtmux::test::TestServer::new().await?;
/// let version = guard.server().capabilities().await?.tmux_version().clone();
///
/// if version.meets(&libtmux::since::CAPTURE_LINE_FLAGS) {
///     // `capture-pane -F` exists here; older supported releases lack it.
///     assert!(version.has_behavior(&libtmux::since::CAPTURE_LINE_FLAGS));
/// }
///
/// guard.shutdown().await?;
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// # })?;
/// # Ok(())
/// # }
/// ```
pub mod since {
    use super::{ReleaseSuffix, ReleaseVersion};

    /// `pane-border-style` and `pane-active-border-style` becoming pane
    /// options as well as window ones, below it tmux stores them only per window, and a
    /// write sent with `-p` lands there instead -- reporting success for a change
    /// the caller did not ask for. See [`crate::OptionSchema::accepts`].
    pub const PANE_BORDER_STYLE_PER_PANE: ReleaseVersion =
        ReleaseVersion::new(3, 7, ReleaseSuffix::FINAL);

    /// `capture-pane -F`, and so [`crate::Pane::capture_lines`].
    pub const CAPTURE_LINE_FLAGS: ReleaseVersion = ReleaseVersion::new(3, 7, ReleaseSuffix::FINAL);

    /// `list-keys -F`, and so [`crate::Server::typed_key_bindings`].
    ///
    /// Below this release `list-keys` prints only its own `bind-key` lines,
    /// which quote a key and leave a table name bare, and carry no note.
    pub const LIST_KEYS_FORMAT: ReleaseVersion = ReleaseVersion::new(3, 7, ReleaseSuffix::FINAL);

    /// Taking a pane out of a control client's stream without crashing the
    /// server, and so [`crate::control::ControlSender::mute_pane`] using `off`.
    ///
    /// Before this release `refresh-client -A <pane>:off` leaves the output
    /// blocks already queued for that pane in place, while the pane stops
    /// holding the server's read buffer back. Writing those blocks later
    /// reads past the end of a buffer the server has drained, and the server
    /// segfaults. `mute_pane` pauses the pane below this release instead,
    /// which discards the queue on every supported release.
    pub const CONTROL_PANE_OFF: ReleaseVersion = ReleaseVersion::new(3, 7, ReleaseSuffix::FINAL);

    /// `capture-pane -T`, and so [`crate::CaptureOptions::trim_blank_cells`].
    ///
    /// Added in 3.4 to stop at the last used cell instead of the pane's full
    /// width. The option string is `ab:CeE:JNpPqS:t:` on 3.2a and gains `T`
    /// by 3.5a; tmux's own CHANGES puts it in the 3.3a-to-3.4 section.
    ///
    /// `-N` and `-P` are available on every supported release.
    pub const CAPTURE_TRIM_BLANK_CELLS: ReleaseVersion =
        ReleaseVersion::new(3, 4, ReleaseSuffix::FINAL);

    /// `list-clients` leaving out a client that is stopped rather than gone,
    /// and so [`crate::Error::ClientSuspended`] being reachable at all.
    ///
    /// From this release `sort_get_clients` screens the listing on
    /// `CLIENT_UNATTACHEDFLAGS`, which covers the dead, the exiting and the
    /// suspended together, so a suspended or locked client disappears from it.
    /// Earlier releases screen on the session alone, and suspending a client
    /// never clears that, so it stays listed and reads back normally.
    ///
    /// Measured on 3.2a, 3.4, 3.5a, 3.6b, 3.7 and 3.7c: the first four list a
    /// suspended client, the last two do not.
    pub const CLIENTS_HIDE_STOPPED: ReleaseVersion =
        ReleaseVersion::new(3, 7, ReleaseSuffix::FINAL);

    /// The mirrored layouts, and so [`crate::Layout::MainHorizontalMirrored`]
    /// and [`crate::Layout::MainVerticalMirrored`].
    ///
    /// Below this release `layout_set_lookup` does not carry those names, and
    /// tmux refuses one as it would a typo.
    pub const MIRRORED_LAYOUTS: ReleaseVersion = ReleaseVersion::new(3, 5, ReleaseSuffix::FINAL);

    /// `window_layout` and `select-layout` using a JSON subset instead of the
    /// classic checksum-prefixed string, and so [`crate::LayoutSpec::Saved`]
    /// accepting one.
    ///
    /// tmux's own `CHANGES FROM 3.7c TO 3.8` names the release: "Layout
    /// strings now use a JSON subset format ... The old format is still
    /// accepted; control mode clients receive old layouts unless they set the
    /// new-layouts flag." Below this release a JSON string is refused as an
    /// unrecognised layout, with no hint that the value is simply from a
    /// newer tmux.
    ///
    /// The gate is the earliest build measured: 3.8-rc2, 3.8-rc3 and 3.8
    /// dump JSON, and 3.7c does not. The `3.8-rc` tag no longer exists
    /// upstream, so a candidate below rc2 cannot be checked.
    pub const JSON_LAYOUTS: ReleaseVersion =
        ReleaseVersion::new(3, 8, ReleaseSuffix::RELEASE_CANDIDATE_2);
}

#[cfg(test)]
mod grammar_tests {
    use super::{MAX_REPORTED_TOKEN, ReleaseVersion, TmuxVersion};
    use crate::Error;

    fn parsed(raw: &str) -> Result<TmuxVersion, Error> {
        TmuxVersion::parse_output(format!("tmux {raw}\n").as_bytes())
    }

    /// The reading the version check gives a daemon's report.
    fn report(raw: &str) -> Result<TmuxVersion, Error> {
        let output = format!("tmux {raw}\n");
        TmuxVersion::parse_report(output.as_bytes(), output.len())
    }

    fn rank(raw: &str) -> ReleaseVersion {
        parsed(raw)
            .unwrap_or_else(|error| panic!("{raw}: {error:?}"))
            .behavior_release()
            .unwrap_or_else(|| panic!("{raw} names no release"))
    }

    /// Every form tmux has reported through `#{version}`, and the library-side
    /// spellings it never reported.
    #[test]
    fn the_canonical_grammar_accepts_refuses_and_orders() {
        for raw in [
            "3.3a", "3.4", "3.7d", "3.8", "3.10", "4.0", "3.4-rc", "3.8-rc", "3.8-rc2", "next-3.4",
            "next-3.9",
        ] {
            let version = parsed(raw).unwrap_or_else(|error| panic!("{raw}: {error:?}"));
            assert!(version.ensure_supported().is_ok(), "{raw} is supported");
        }
        for raw in ["3.3", "3.2a", "3.3-rc", "3.2-rc5", "next-3.3"] {
            let version = parsed(raw).unwrap_or_else(|error| panic!("{raw}: {error:?}"));
            assert!(
                matches!(
                    version.ensure_supported(),
                    Err(Error::UnsupportedTmuxVersion { .. })
                ),
                "{raw} is below the floor"
            );
        }
        // A report that names no release is unrecognized, never "too old".
        for raw in [
            "master",
            "openbsd-7.6",
            "3",
            "garbage",
            "3.3a-master",
            "3.3a-dev",
            "next-3.3a",
            "next-3.9-master",
        ] {
            let outcome = report(raw).and_then(|version| version.ensure_supported());
            assert!(
                matches!(outcome, Err(Error::UnrecognizedTmuxVersion { .. })),
                "{raw} is unrecognized: {outcome:?}"
            );
        }
        // Output that is not a version report is invalid, with the length the
        // caller says it read.
        let long = "x".repeat(MAX_REPORTED_TOKEN + 1);
        let at_limit = "x".repeat(MAX_REPORTED_TOKEN);
        for output in [
            b"tmux \n".to_vec(),
            b"tmux 3.3a garbage\n".to_vec(),
            b"tmux 3.3a".to_vec(),
            b"3.3a\n".to_vec(),
            format!("tmux {long}\n").into_bytes(),
            "tmux 3.3\u{e9}\n".as_bytes().to_vec(),
            b"tmux 3.3\x01\n".to_vec(),
        ] {
            let outcome = TmuxVersion::parse_report(&output, 7);
            assert!(
                matches!(outcome, Err(Error::InvalidVersionOutput { output_len: 7 })),
                "{}: {outcome:?}",
                output.escape_ascii()
            );
        }
        let outcome = TmuxVersion::parse_report(format!("tmux {at_limit}\n").as_bytes(), 0);
        assert!(
            matches!(outcome, Err(Error::UnrecognizedTmuxVersion { .. })),
            "a token at the limit is kept: {outcome:?}"
        );

        for chain in [
            &["next-3.7", "3.7-rc", "3.7-rc3", "3.7", "3.7a"][..],
            &["next-3.4", "3.4-rc", "3.4"],
            &["3.9", "3.10"],
        ] {
            for pair in chain.windows(2) {
                assert!(
                    rank(pair[0]) < rank(pair[1]),
                    "{} ranks below {}",
                    pair[0],
                    pair[1]
                );
            }
        }

        // Anything ranking at or above 3.7 final may acquire control.
        let control = ReleaseVersion::new(3, 7, crate::ReleaseSuffix::FINAL);
        for (raw, allowed) in [
            ("3.8-rc2", true),
            ("next-3.8", true),
            ("3.7", true),
            ("3.7d", true),
            ("next-3.7", false),
            ("3.7-rc2", false),
            ("3.6b", false),
        ] {
            let version = parsed(raw).unwrap_or_else(|error| panic!("{raw}: {error:?}"));
            assert_eq!(
                version.has_behavior(&control),
                allowed,
                "{raw} control acquisition"
            );
        }
    }
}