-
Notifications
You must be signed in to change notification settings - Fork 282
/
cli.rs
465 lines (428 loc) · 13.4 KB
/
cli.rs
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
use crate::info::langs::language::{Language, LanguageType};
use crate::info::utils::info_field::InfoType;
use crate::ui::printer::SerializationFormat;
use anyhow::Result;
use clap::builder::PossibleValuesParser;
use clap::builder::TypedValueParser as _;
use clap::{value_parser, Args, 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"];
pub const NO_BOTS_DEFAULT_REGEX_PATTERN: &str = r"(?:-|\s)[Bb]ot$|\[[Bb]ot\]";
#[derive(Clone, Debug, Parser, PartialEq, Eq)]
#[command(version, about)]
pub struct CliOptions {
/// Run as if onefetch was started in <input> instead of the current working directory
#[arg(default_value = ".", hide_default_value = true, value_hint = ValueHint::DirPath)]
pub input: PathBuf,
#[command(flatten)]
pub info: InfoCliOptions,
#[command(flatten)]
pub text_formatting: TextForamttingCliOptions,
#[command(flatten)]
pub ascii: AsciiCliOptions,
#[command(flatten)]
pub image: ImageCliOptions,
#[command(flatten)]
pub visuals: VisualsCliOptions,
#[command(flatten)]
pub developer: DeveloperCliOptions,
#[command(flatten)]
pub other: OtherCliOptions,
}
#[derive(Clone, Debug, Args, PartialEq, Eq)]
#[command(next_help_heading = "INFO")]
pub struct InfoCliOptions {
/// Allows you to disable FIELD(s) from appearing in the output
#[arg(
long,
short,
num_args = 1..,
hide_possible_values = true,
value_enum,
value_name = "FIELD"
)]
pub disabled_fields: Vec<InfoType>,
/// Hides the title
#[arg(long)]
pub no_title: bool,
/// Maximum NUM of authors to be shown
#[arg(long, default_value_t = 3usize, value_name = "NUM")]
pub number_of_authors: usize,
/// Maximum NUM of languages to be shown
#[arg(long, default_value_t = 6usize, value_name = "NUM")]
pub number_of_languages: usize,
/// Maximum NUM of file churns to be shown
#[arg(long, default_value_t = 3usize, value_name = "NUM")]
pub number_of_file_churns: usize,
/// Minimum NUM of commits from HEAD used to compute the churn summary
///
/// By default, the actual value is non-deterministic due to time-based computation
/// and will be displayed under the info title "Churn (NUM)"
#[arg(long, value_name = "NUM")]
pub churn_pool_size: Option<usize>,
/// Ignore all files & directories matching EXCLUDE
#[arg(long, short, num_args = 1..)]
pub exclude: Vec<String>,
/// Exclude [bot] commits. Use <REGEX> to override the default pattern
#[arg(
long,
num_args = 0..=1,
require_equals = true,
default_missing_value = NO_BOTS_DEFAULT_REGEX_PATTERN,
value_name = "REGEX"
)]
pub no_bots: Option<MyRegex>,
/// Ignores merge commits
#[arg(long)]
pub no_merges: bool,
/// Show the email address of each author
#[arg(long, short = 'E')]
pub email: bool,
/// Display repository URL as HTTP
#[arg(long)]
pub http_url: bool,
/// Hide token in repository URL
#[arg(long)]
pub hide_token: bool,
/// Count hidden files and directories
#[arg(long)]
pub include_hidden: bool,
/// Filters output by language type
#[arg(
long,
num_args = 1..,
default_values = &["programming", "markup"],
short = 'T',
value_enum,
)]
pub r#type: Vec<LanguageType>,
}
#[derive(Clone, Debug, Args, PartialEq, Eq)]
#[command(next_help_heading = "ASCII")]
pub struct AsciiCliOptions {
/// Takes a non-empty STRING as input to replace the ASCII logo
///
/// It is possible to pass a generated STRING by command substitution
///
/// For example:
///
/// '--ascii-input "$(fortune | cowsay -W 25)"'
#[arg(long, value_name = "STRING", value_hint = ValueHint::CommandString)]
pub ascii_input: Option<String>,
/// Colors (X X X...) to print the ascii art
#[arg(
long,
num_args = 1..,
value_name = "X",
short = 'c',
value_parser = value_parser!(u8).range(..16),
)]
pub ascii_colors: Vec<u8>,
/// Which LANGUAGE's ascii art to print
#[arg(
long,
short,
value_name = "LANGUAGE",
value_enum,
hide_possible_values = true
)]
pub ascii_language: Option<Language>,
/// Specify when to use true color
///
/// If set to auto: true color will be enabled if supported by the terminal
#[arg(long, default_value = "auto", value_name = "WHEN", value_enum)]
pub true_color: When,
}
#[derive(Clone, Debug, Args, PartialEq, Eq)]
#[command(next_help_heading = "IMAGE")]
pub struct ImageCliOptions {
/// Path to the IMAGE file
#[arg(long, short, value_hint = ValueHint::FilePath)]
pub image: Option<PathBuf>,
/// Which image PROTOCOL to use
#[arg(long, value_enum, requires = "image", value_name = "PROTOCOL")]
pub image_protocol: Option<ImageProtocol>,
/// VALUE of color resolution to use with SIXEL backend
#[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,
}
#[derive(Clone, Debug, Args, PartialEq, Eq)]
#[command(next_help_heading = "TEXT FORMATTING")]
pub struct TextForamttingCliOptions {
/// Changes the text colors (X X X...)
///
/// Goes in order of title, ~, underline, subtitle, colon, and info
///
/// For example:
///
/// '--text-colors 9 10 11 12 13 14'
#[arg(
long,
short,
value_name = "X",
value_parser = value_parser!(u8).range(..16),
num_args = 1..=6
)]
pub text_colors: Vec<u8>,
/// Use ISO 8601 formatted timestamps
#[arg(long, short = 'z')]
pub iso_time: bool,
/// Which thousands SEPARATOR to use
#[arg(long, value_name = "SEPARATOR", default_value = "plain", value_enum)]
pub number_separator: NumberSeparator,
/// Turns off bold formatting
#[arg(long)]
pub no_bold: bool,
}
#[derive(Clone, Debug, Args, PartialEq, Eq, Default)]
#[command(next_help_heading = "VISUALS")]
pub struct VisualsCliOptions {
/// Hides the color palette
#[arg(long)]
pub no_color_palette: bool,
/// Hides the ascii art or image if provided
#[arg(long)]
pub no_art: bool,
/// Use Nerd Font icons
///
/// Replaces language chips with Nerd Font icons
#[arg(long)]
pub nerd_fonts: bool,
}
#[derive(Clone, Debug, Args, PartialEq, Eq, Default)]
#[command(next_help_heading = "DEVELOPER")]
pub struct DeveloperCliOptions {
/// Outputs Onefetch in a specific format
#[arg(long, short, value_name = "FORMAT", value_enum)]
pub output: Option<SerializationFormat>,
/// If provided, outputs the completion file for given SHELL
#[arg(long = "generate", value_name = "SHELL", value_enum)]
pub completion: Option<Shell>,
}
#[derive(Clone, Debug, Args, PartialEq, Eq, Default)]
#[command(next_help_heading = "OTHER")]
pub struct OtherCliOptions {
/// Prints out supported languages
#[arg(long, short)]
pub languages: bool,
/// Prints out supported package managers
#[arg(long, short)]
pub package_managers: bool,
}
impl Default for CliOptions {
fn default() -> CliOptions {
CliOptions {
input: PathBuf::from("."),
info: InfoCliOptions::default(),
text_formatting: TextForamttingCliOptions::default(),
visuals: VisualsCliOptions::default(),
ascii: AsciiCliOptions::default(),
image: ImageCliOptions::default(),
developer: DeveloperCliOptions::default(),
other: OtherCliOptions::default(),
}
}
}
impl Default for InfoCliOptions {
fn default() -> Self {
InfoCliOptions {
number_of_authors: 3,
number_of_languages: 6,
number_of_file_churns: 3,
churn_pool_size: Option::default(),
exclude: Vec::default(),
no_bots: Option::default(),
no_merges: Default::default(),
email: Default::default(),
http_url: Default::default(),
hide_token: Default::default(),
include_hidden: Default::default(),
r#type: vec![LanguageType::Programming, LanguageType::Markup],
disabled_fields: Vec::default(),
no_title: Default::default(),
}
}
}
impl Default for TextForamttingCliOptions {
fn default() -> Self {
TextForamttingCliOptions {
text_colors: Default::default(),
iso_time: Default::default(),
number_separator: NumberSeparator::Plain,
no_bold: Default::default(),
}
}
}
impl Default for AsciiCliOptions {
fn default() -> Self {
AsciiCliOptions {
ascii_input: Option::default(),
ascii_colors: Vec::default(),
ascii_language: Option::default(),
true_color: When::Auto,
}
}
}
impl Default for ImageCliOptions {
fn default() -> Self {
ImageCliOptions {
image: Option::default(),
image_protocol: Default::default(),
color_resolution: 16,
}
}
}
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: CliOptions = CliOptions::default();
assert_eq!(config, CliOptions::parse_from(["onefetch"]));
}
#[test]
fn test_custom_config() {
let config: CliOptions = CliOptions {
input: PathBuf::from("/tmp/folder"),
info: InfoCliOptions {
number_of_authors: 4,
no_merges: true,
disabled_fields: vec![InfoType::Version, InfoType::URL],
..Default::default()
},
ascii: AsciiCliOptions {
ascii_colors: vec![5, 0],
ascii_language: Some(Language::Lisp),
..Default::default()
},
visuals: VisualsCliOptions {
no_art: true,
..Default::default()
},
..Default::default()
};
assert_eq!(
config,
CliOptions::parse_from([
"onefetch",
"/tmp/folder",
"--number-of-authors",
"4",
"--no-merges",
"--ascii-colors",
"5",
"0",
"--disabled-fields",
"version",
"url",
"--no-art",
"--ascii-language",
"lisp"
])
);
}
#[test]
fn test_config_with_image_protocol_but_no_image() {
assert!(CliOptions::try_parse_from(["onefetch", "--image-protocol", "sixel"]).is_err())
}
#[test]
fn test_config_with_color_resolution_but_no_image() {
assert!(CliOptions::try_parse_from(["onefetch", "--color-resolution", "32"]).is_err())
}
#[test]
fn test_config_with_ascii_colors_but_out_of_bounds() {
assert!(CliOptions::try_parse_from(["onefetch", "--ascii-colors", "17"]).is_err())
}
#[test]
fn test_config_with_text_colors_but_out_of_bounds() {
assert!(CliOptions::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)?))
}
}