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
use crate::info::info_field::InfoType;
use crate::info::langs::language::{Language, LanguageType};
use crate::ui::printer::SerializationFormat;
use anyhow::Result;
use clap::builder::PossibleValuesParser;
use clap::builder::TypedValueParser as _;
use clap::{value_parser, Command, Parser, ValueHint};
use clap_complete::{generate, Generator, Shell};
use num_format::CustomFormat;
use onefetch_image::ImageProtocol;
use onefetch_manifest::ManifestType;
use regex::Regex;
use serde::Serialize;
use std::env;
use std::io;
use std::path::PathBuf;
use std::str::FromStr;
use strum::IntoEnumIterator;
const COLOR_RESOLUTIONS: [&str; 5] = ["16", "32", "64", "128", "256"];
#[derive(Clone, Debug, Parser, PartialEq, Eq)]
#[command(version, about, long_about = None, rename_all = "kebab-case")]
pub struct Config {
#[arg(default_value = ".", hide_default_value = true, value_hint = ValueHint::DirPath)]
pub input: PathBuf,
#[arg(long, value_name = "STRING", value_hint = ValueHint::CommandString)]
pub ascii_input: Option<String>,
#[arg(
long,
short,
value_name = "LANGUAGE",
value_enum,
hide_possible_values = true
)]
pub ascii_language: Option<Language>,
#[arg(
long,
num_args = 1..,
value_name = "X",
short = 'c',
value_parser = value_parser!(u8).range(..16),
)]
pub ascii_colors: Vec<u8>,
#[arg(
long,
short,
num_args = 1..,
hide_possible_values = true,
value_enum,
value_name = "FIELD"
)]
pub disabled_fields: Vec<InfoType>,
#[arg(long, short, value_hint = ValueHint::FilePath)]
pub image: Option<PathBuf>,
#[arg(long, value_enum, requires = "image")]
pub image_protocol: Option<ImageProtocol>,
#[arg(
long,
value_name = "VALUE",
requires = "image",
default_value_t = 16usize,
value_parser = PossibleValuesParser::new(COLOR_RESOLUTIONS)
.map(|s| s.parse::<usize>().unwrap())
)]
pub color_resolution: usize,
#[arg(long)]
pub no_bold: bool,
#[arg(long)]
pub no_merges: bool,
#[arg(long)]
pub no_color_palette: bool,
#[arg(long)]
pub no_title: bool,
#[arg(long, default_value_t = 3usize, value_name = "NUM")]
pub number_of_authors: usize,
#[arg(long, default_value_t = 6usize, value_name = "NUM")]
pub number_of_languages: usize,
#[arg(long, short, num_args = 1.., value_hint = ValueHint::AnyPath)]
pub exclude: Vec<PathBuf>,
#[arg(long, value_name = "REGEX")]
pub no_bots: Option<Option<MyRegex>>,
#[arg(long, short)]
pub languages: bool,
#[arg(long, short)]
pub package_managers: bool,
#[arg(long, short, value_name = "FORMAT", value_enum)]
pub output: Option<SerializationFormat>,
#[arg(long, default_value = "auto", value_name = "WHEN", value_enum)]
pub true_color: When,
#[arg(long, default_value = "always", value_name = "WHEN", value_enum)]
pub show_logo: When,
#[arg(
long,
short,
value_name = "X",
value_parser = value_parser!(u8).range(..16),
num_args = 1..=6
)]
pub text_colors: Vec<u8>,
#[arg(long, short = 'z')]
pub iso_time: bool,
#[arg(long, value_name = "SEPARATOR", default_value = "plain", value_enum)]
pub number_separator: NumberSeparator,
#[arg(long, short = 'E')]
pub email: bool,
#[arg(long)]
pub include_hidden: bool,
#[arg(
long,
num_args = 1..,
default_values = &["programming", "markup"],
short = 'T',
value_enum,
)]
pub r#type: Vec<LanguageType>,
#[arg(long = "generate", value_name = "SHELL", value_enum)]
pub completion: Option<Shell>,
}
impl Default for Config {
fn default() -> Config {
Config {
input: PathBuf::from("."),
ascii_input: Default::default(),
ascii_language: Default::default(),
ascii_colors: Default::default(),
disabled_fields: Default::default(),
image: Default::default(),
image_protocol: Default::default(),
color_resolution: 16,
no_bold: Default::default(),
no_merges: Default::default(),
no_color_palette: Default::default(),
no_title: Default::default(),
number_of_authors: 3,
number_of_languages: 6,
exclude: Default::default(),
no_bots: Default::default(),
languages: Default::default(),
package_managers: Default::default(),
output: Default::default(),
true_color: When::Auto,
show_logo: When::Always,
text_colors: Default::default(),
iso_time: Default::default(),
number_separator: NumberSeparator::Plain,
email: Default::default(),
include_hidden: Default::default(),
r#type: vec![LanguageType::Programming, LanguageType::Markup],
completion: Default::default(),
}
}
}
pub fn print_supported_languages() -> Result<()> {
for l in Language::iter() {
println!("{}", l);
}
Ok(())
}
pub fn print_supported_package_managers() -> Result<()> {
for p in ManifestType::iter() {
println!("{}", p);
}
Ok(())
}
pub fn is_truecolor_terminal() -> bool {
env::var("COLORTERM")
.map(|colorterm| colorterm == "truecolor" || colorterm == "24bit")
.unwrap_or(false)
}
pub fn get_git_version() -> String {
let version = std::process::Command::new("git").arg("--version").output();
match version {
Ok(v) => String::from_utf8_lossy(&v.stdout).replace('\n', ""),
Err(_) => String::new(),
}
}
pub fn print_completions<G: Generator>(gen: G, cmd: &mut Command) {
generate(gen, cmd, cmd.get_name().to_string(), &mut io::stdout());
}
#[derive(clap::ValueEnum, Clone, PartialEq, Eq, Debug)]
pub enum When {
Auto,
Never,
Always,
}
#[derive(clap::ValueEnum, Clone, PartialEq, Eq, Debug, Serialize, Copy)]
pub enum NumberSeparator {
Plain,
Comma,
Space,
Underscore,
}
impl NumberSeparator {
fn separator(&self) -> &'static str {
match self {
Self::Plain => "",
Self::Comma => ",",
Self::Space => "\u{202f}",
Self::Underscore => "_",
}
}
pub fn get_format(&self) -> CustomFormat {
num_format::CustomFormat::builder()
.grouping(num_format::Grouping::Standard)
.separator(self.separator())
.build()
.unwrap()
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_default_config() {
let config: Config = Default::default();
assert_eq!(config, Config::parse_from(&["onefetch"]))
}
#[test]
fn test_custom_config() {
let config: Config = Config {
number_of_authors: 4,
input: PathBuf::from("/tmp/folder"),
no_merges: true,
ascii_colors: vec![5, 0],
disabled_fields: vec![InfoType::Version, InfoType::URL],
show_logo: When::Never,
ascii_language: Some(Language::Lisp),
..Default::default()
};
assert_eq!(
config,
Config::parse_from(&[
"onefetch",
"/tmp/folder",
"--number-of-authors",
"4",
"--no-merges",
"--ascii-colors",
"5",
"0",
"--disabled-fields",
"version",
"url",
"--show-logo",
"never",
"--ascii-language",
"lisp"
])
)
}
#[test]
fn test_config_with_image_protocol_but_no_image() {
assert!(Config::try_parse_from(&["onefetch", "--image-protocol", "sixel"]).is_err())
}
#[test]
fn test_config_with_color_resolution_but_no_image() {
assert!(Config::try_parse_from(&["onefetch", "--color-resolution", "32"]).is_err())
}
#[test]
fn test_config_with_ascii_colors_but_out_of_bounds() {
assert!(Config::try_parse_from(&["onefetch", "--ascii-colors", "17"]).is_err())
}
#[test]
fn test_config_with_text_colors_but_out_of_bounds() {
assert!(Config::try_parse_from(&["onefetch", "--text-colors", "17"]).is_err())
}
}
#[derive(Clone, Debug)]
pub struct MyRegex(pub Regex);
impl Eq for MyRegex {}
impl PartialEq for MyRegex {
fn eq(&self, other: &MyRegex) -> bool {
self.0.as_str() == other.0.as_str()
}
}
impl FromStr for MyRegex {
type Err = anyhow::Error;
fn from_str(s: &str) -> Result<Self> {
Ok(MyRegex(Regex::new(s)?))
}
}