clap_builder/util/color.rs
1use crate::builder::PossibleValue;
2use crate::derive::ValueEnum;
3
4/// Represents the color preferences for program output
5#[derive(Debug, Copy, Clone, Eq, PartialEq)]
6pub enum ColorChoice {
7 /// Enables colored output only when the output is going to a terminal or TTY.
8 ///
9 /// **NOTE:** This is the default behavior of `clap`.
10 ///
11 /// # Examples
12 ///
13 /// ```rust
14 /// # #[cfg(feature = "color")] {
15 /// # use clap_builder as clap;
16 /// # use clap::{Command, ColorChoice};
17 /// Command::new("myprog")
18 /// .color(ColorChoice::Auto)
19 /// .get_matches();
20 /// # }
21 /// ```
22 Auto,
23
24 /// Enables colored output regardless of whether or not the output is going to a terminal/TTY.
25 ///
26 /// # Examples
27 ///
28 /// ```rust
29 /// # #[cfg(feature = "color")] {
30 /// # use clap_builder as clap;
31 /// # use clap::{Command, ColorChoice};
32 /// Command::new("myprog")
33 /// .color(ColorChoice::Always)
34 /// .get_matches();
35 /// # }
36 /// ```
37 Always,
38
39 /// Disables colored output no matter if the output is going to a terminal/TTY, or not.
40 ///
41 /// # Examples
42 ///
43 /// ```rust
44 /// # #[cfg(feature = "color")] {
45 /// # use clap_builder as clap;
46 /// # use clap::{Command, ColorChoice};
47 /// Command::new("myprog")
48 /// .color(ColorChoice::Never)
49 /// .get_matches();
50 /// # }
51 /// ```
52 Never,
53}
54
55impl ColorChoice {
56 /// Report all `possible_values`
57 pub fn possible_values() -> impl Iterator<Item = PossibleValue> {
58 Self::value_variants()
59 .iter()
60 .filter_map(ValueEnum::to_possible_value)
61 }
62}
63
64impl Default for ColorChoice {
65 fn default() -> Self {
66 Self::Auto
67 }
68}
69
70impl std::fmt::Display for ColorChoice {
71 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
72 self.to_possible_value()
73 .expect("no values are skipped")
74 .get_name()
75 .fmt(f)
76 }
77}
78
79impl std::str::FromStr for ColorChoice {
80 type Err = String;
81
82 fn from_str(s: &str) -> Result<Self, Self::Err> {
83 for variant in Self::value_variants() {
84 if variant.to_possible_value().unwrap().matches(s, false) {
85 return Ok(*variant);
86 }
87 }
88 Err(format!("invalid variant: {s}"))
89 }
90}
91
92impl ValueEnum for ColorChoice {
93 fn value_variants<'a>() -> &'a [Self] {
94 &[Self::Auto, Self::Always, Self::Never]
95 }
96
97 fn to_possible_value(&self) -> Option<PossibleValue> {
98 Some(match self {
99 Self::Auto => PossibleValue::new("auto"),
100 Self::Always => PossibleValue::new("always"),
101 Self::Never => PossibleValue::new("never"),
102 })
103 }
104}