- Notifications
You must be signed in to change notification settings - Fork 286
/
Copy pathcli.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
usecrate::info::langs::language::{Language,LanguageType};
usecrate::info::utils::info_field::InfoType;
usecrate::ui::printer::SerializationFormat;
use anyhow::Result;
use clap::builder::PossibleValuesParser;
use clap::builder::TypedValueParseras _;
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;
constCOLOR_RESOLUTIONS:[&str;5] = ["16","32","64","128","256"];
pubconstNO_BOTS_DEFAULT_REGEX_PATTERN:&str = r"(?:-|\s)[Bb]ot$|\[[Bb]ot\]";
#[derive(Clone,Debug,Parser,PartialEq,Eq)]
#[command(version, about)]
pubstructCliOptions{
/// 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)]
pubinput:PathBuf,
#[command(flatten)]
pubinfo:InfoCliOptions,
#[command(flatten)]
pubtext_formatting:TextForamttingCliOptions,
#[command(flatten)]
pubascii:AsciiCliOptions,
#[command(flatten)]
pubimage:ImageCliOptions,
#[command(flatten)]
pubvisuals:VisualsCliOptions,
#[command(flatten)]
pubdeveloper:DeveloperCliOptions,
#[command(flatten)]
pubother:OtherCliOptions,
}
#[derive(Clone,Debug,Args,PartialEq,Eq)]
#[command(next_help_heading = "INFO")]
pubstructInfoCliOptions{
/// 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"
)]
pubdisabled_fields:Vec<InfoType>,
/// Hides the title
#[arg(long)]
pubno_title:bool,
/// Maximum NUM of authors to be shown
#[arg(long, default_value_t = 3usize, value_name = "NUM")]
pubnumber_of_authors:usize,
/// Maximum NUM of languages to be shown
#[arg(long, default_value_t = 6usize, value_name = "NUM")]
pubnumber_of_languages:usize,
/// Maximum NUM of file churns to be shown
#[arg(long, default_value_t = 3usize, value_name = "NUM")]
pubnumber_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")]
pubchurn_pool_size:Option<usize>,
/// Ignore all files & directories matching EXCLUDE
#[arg(long, short, num_args = 1..)]
pubexclude: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"
)]
pubno_bots:Option<MyRegex>,
/// Ignores merge commits
#[arg(long)]
pubno_merges:bool,
/// Show the email address of each author
#[arg(long, short = 'E')]
pubemail:bool,
/// Display repository URL as HTTP
#[arg(long)]
pubhttp_url:bool,
/// Hide token in repository URL
#[arg(long)]
pubhide_token:bool,
/// Count hidden files and directories
#[arg(long)]
pubinclude_hidden:bool,
/// Filters output by language type
#[arg(
long,
num_args = 1..,
default_values = &["programming","markup"],
short = 'T',
value_enum,
)]
pubr#type:Vec<LanguageType>,
}
#[derive(Clone,Debug,Args,PartialEq,Eq)]
#[command(next_help_heading = "ASCII")]
pubstructAsciiCliOptions{
/// 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)]
pubascii_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),
)]
pubascii_colors:Vec<u8>,
/// Which LANGUAGE's ascii art to print
#[arg(
long,
short,
value_name = "LANGUAGE",
value_enum,
hide_possible_values = true
)]
pubascii_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)]
pubtrue_color:When,
}
#[derive(Clone,Debug,Args,PartialEq,Eq)]
#[command(next_help_heading = "IMAGE")]
pubstructImageCliOptions{
/// Path to the IMAGE file
#[arg(long, short, value_hint = ValueHint::FilePath)]
pubimage:Option<PathBuf>,
/// Which image PROTOCOL to use
#[arg(long, value_enum, requires = "image", value_name = "PROTOCOL")]
pubimage_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())
)]
pubcolor_resolution:usize,
}
#[derive(Clone,Debug,Args,PartialEq,Eq)]
#[command(next_help_heading = "TEXT FORMATTING")]
pubstructTextForamttingCliOptions{
/// 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
)]
pubtext_colors:Vec<u8>,
/// Use ISO 8601 formatted timestamps
#[arg(long, short = 'z')]
pubiso_time:bool,
/// Which thousands SEPARATOR to use
#[arg(long, value_name = "SEPARATOR", default_value = "plain", value_enum)]
pubnumber_separator:NumberSeparator,
/// Turns off bold formatting
#[arg(long)]
pubno_bold:bool,
}
#[derive(Clone,Debug,Args,PartialEq,Eq,Default)]
#[command(next_help_heading = "VISUALS")]
pubstructVisualsCliOptions{
/// Hides the color palette
#[arg(long)]
pubno_color_palette:bool,
/// Hides the ascii art or image if provided
#[arg(long)]
pubno_art:bool,
/// Use Nerd Font icons
///
/// Replaces language chips with Nerd Font icons
#[arg(long)]
pubnerd_fonts:bool,
}
#[derive(Clone,Debug,Args,PartialEq,Eq,Default)]
#[command(next_help_heading = "DEVELOPER")]
pubstructDeveloperCliOptions{
/// Outputs Onefetch in a specific format
#[arg(long, short, value_name = "FORMAT", value_enum)]
puboutput:Option<SerializationFormat>,
/// If provided, outputs the completion file for given SHELL
#[arg(long = "generate", value_name = "SHELL", value_enum)]
pubcompletion:Option<Shell>,
}
#[derive(Clone,Debug,Args,PartialEq,Eq,Default)]
#[command(next_help_heading = "OTHER")]
pubstructOtherCliOptions{
/// Prints out supported languages
#[arg(long, short)]
publanguages:bool,
/// Prints out supported package managers
#[arg(long, short)]
pubpackage_managers:bool,
}
implDefaultforCliOptions{
fndefault() -> 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(),
}
}
}
implDefaultforInfoCliOptions{
fndefault() -> 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(),
}
}
}
implDefaultforTextForamttingCliOptions{
fndefault() -> Self{
TextForamttingCliOptions{
text_colors:Default::default(),
iso_time:Default::default(),
number_separator:NumberSeparator::Plain,
no_bold:Default::default(),
}
}
}
implDefaultforAsciiCliOptions{
fndefault() -> Self{
AsciiCliOptions{
ascii_input:Option::default(),
ascii_colors:Vec::default(),
ascii_language:Option::default(),
true_color:When::Auto,
}
}
}
implDefaultforImageCliOptions{
fndefault() -> Self{
ImageCliOptions{
image:Option::default(),
image_protocol:Default::default(),
color_resolution:16,
}
}
}
pubfnprint_supported_languages() -> Result<()>{
for l inLanguage::iter(){
println!("{l}");
}
Ok(())
}
pubfnprint_supported_package_managers() -> Result<()>{
for p inManifestType::iter(){
println!("{p}");
}
Ok(())
}
pubfnis_truecolor_terminal() -> bool{
env::var("COLORTERM")
.map(|colorterm| colorterm == "truecolor" || colorterm == "24bit")
.unwrap_or(false)
}
pubfnget_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(),
}
}
pubfnprint_completions<G:Generator>(gen:G,cmd:&mutCommand){
generate(gen, cmd, cmd.get_name().to_string(),&mut io::stdout());
}
#[derive(clap::ValueEnum,Clone,PartialEq,Eq,Debug)]
pubenumWhen{
Auto,
Never,
Always,
}
#[derive(clap::ValueEnum,Clone,PartialEq,Eq,Debug,Serialize,Copy)]
pubenumNumberSeparator{
Plain,
Comma,
Space,
Underscore,
}
implNumberSeparator{
fnseparator(&self) -> &'staticstr{
matchself{
Self::Plain => "",
Self::Comma => ",",
Self::Space => "\u{202f}",
Self::Underscore => "_",
}
}
pubfnget_format(&self) -> CustomFormat{
num_format::CustomFormat::builder()
.grouping(num_format::Grouping::Standard)
.separator(self.separator())
.build()
.unwrap()
}
}
#[cfg(test)]
mod test {
usesuper::*;
#[test]
fntest_default_config(){
let config:CliOptions = CliOptions::default();
assert_eq!(config,CliOptions::parse_from(["onefetch"]));
}
#[test]
fntest_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]
fntest_config_with_image_protocol_but_no_image(){
assert!(CliOptions::try_parse_from(["onefetch","--image-protocol","sixel"]).is_err())
}
#[test]
fntest_config_with_color_resolution_but_no_image(){
assert!(CliOptions::try_parse_from(["onefetch","--color-resolution","32"]).is_err())
}
#[test]
fntest_config_with_ascii_colors_but_out_of_bounds(){
assert!(CliOptions::try_parse_from(["onefetch","--ascii-colors","17"]).is_err())
}
#[test]
fntest_config_with_text_colors_but_out_of_bounds(){
assert!(CliOptions::try_parse_from(["onefetch","--text-colors","17"]).is_err())
}
}
#[derive(Clone,Debug)]
pubstructMyRegex(pubRegex);
implEqforMyRegex{}
implPartialEqforMyRegex{
fneq(&self,other:&MyRegex) -> bool{
self.0.as_str() == other.0.as_str()
}
}
implFromStrforMyRegex{
typeErr = anyhow::Error;
fnfrom_str(s:&str) -> Result<Self>{
Ok(MyRegex(Regex::new(s)?))
}
}