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
pub fn color_choice() -> clap::ColorChoice {
let color = concolor::get(concolor::Stream::Either);
if color.ansi_color() {
clap::ColorChoice::Always
} else {
clap::ColorChoice::Never
}
}
#[derive(Copy, Clone, Default, Debug, PartialEq, Eq, clap::Args)]
#[command(about = None, long_about = None)]
pub struct Color {
#[arg(long, default_value_t = ColorChoice::Auto, value_name = "WHEN", value_enum, global = true)]
pub color: ColorChoice,
}
impl Color {
#[cfg(feature = "api")]
pub fn apply(&self) {
concolor::set(self.to_control());
}
pub fn to_control(&self) -> concolor::ColorChoice {
match self.color {
ColorChoice::Auto => concolor::ColorChoice::Auto,
ColorChoice::Always => concolor::ColorChoice::Always,
ColorChoice::Never => concolor::ColorChoice::Never,
}
}
}
#[derive(Copy, Clone, Debug, PartialEq, Eq, clap::ValueEnum)]
pub enum ColorChoice {
Auto,
Always,
Never,
}
impl ColorChoice {
pub fn possible_values() -> impl Iterator<Item = clap::builder::PossibleValue> {
use clap::ValueEnum;
Self::value_variants()
.iter()
.filter_map(clap::ValueEnum::to_possible_value)
}
}
impl Default for ColorChoice {
fn default() -> Self {
Self::Auto
}
}
impl std::fmt::Display for ColorChoice {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
use clap::ValueEnum;
self.to_possible_value()
.expect("no values are skipped")
.get_name()
.fmt(f)
}
}
impl std::str::FromStr for ColorChoice {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
AUTO => Ok(Self::Auto),
ALWAYS => Ok(Self::Always),
NEVER => Ok(Self::Never),
other => Err(format!("Unknown color choice '{other}'")),
}
}
}
const AUTO: &str = "auto";
const ALWAYS: &str = "always";
const NEVER: &str = "never";
#[cfg(test)]
mod test {
use super::*;
#[test]
fn verify_app() {
#[derive(Debug, clap::Parser)]
struct Cli {
#[clap(flatten)]
color: Color,
}
use clap::CommandFactory;
Cli::command().debug_assert()
}
}