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