-
Notifications
You must be signed in to change notification settings - Fork 286
/
Copy pathcli.rs
439 lines (411 loc) · 14.3 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
use crate::info::deps::package_manager::PackageManager;
use crate::info::info_field::{InfoField, InfoFieldOff};
use crate::info::language::Language;
use crate::ui::image_backends;
use crate::ui::image_backends::ImageBackend;
use crate::ui::printer::SerializationFormat;
use anyhow::{Context, Result};
use clap::{crate_description, crate_name, crate_version, App, AppSettings, Arg};
use image::DynamicImage;
use regex::Regex;
use std::process::Command;
use std::{convert::From, env, str::FromStr};
use strum::IntoEnumIterator;
const MAX_TERM_WIDTH: usize = 95;
pub struct Config {
pub repo_path: String,
pub ascii_input: Option<String>,
pub ascii_language: Option<Language>,
pub ascii_colors: Vec<String>,
pub disabled_fields: InfoFieldOff,
pub no_bold: bool,
pub image: Option<DynamicImage>,
pub image_backend: Option<Box<dyn ImageBackend>>,
pub image_color_resolution: usize,
pub no_merges: bool,
pub no_color_palette: bool,
pub number_of_authors: usize,
pub ignored_directories: Vec<String>,
pub bot_regex_pattern: Option<Regex>,
pub print_languages: bool,
pub print_package_managers: bool,
pub output: Option<SerializationFormat>,
pub true_color: bool,
pub art_off: bool,
pub text_colors: Vec<String>,
pub iso_time: bool,
pub show_email: bool,
pub include_hidden: bool,
}
impl Config {
pub fn new() -> Result<Self> {
#[cfg(not(windows))]
let possible_backends = ["kitty", "iterm", "sixel"];
#[cfg(windows)]
let possible_backends = [];
let color_values =
&["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15"];
let matches = App::new(crate_name!())
.version(crate_version!())
.about(crate_description!())
.setting(AppSettings::ColoredHelp)
.setting(AppSettings::DeriveDisplayOrder)
.setting(AppSettings::UnifiedHelpMessage)
.setting(AppSettings::HidePossibleValuesInHelp)
.arg(
Arg::with_name("input")
.default_value(".")
.hide_default_value(true)
.help("Run as if onefetch was started in <input> instead of the current working directory.")
)
.arg(
Arg::with_name("output")
.short("o")
.long("output")
.help("Outputs Onefetch in a specific format (json, yaml).")
.takes_value(true)
.possible_values(&SerializationFormat::iter()
.map(|format| format.into())
.collect::<Vec<&str>>())
)
.arg(
Arg::with_name("languages")
.short("l")
.long("languages")
.help("Prints out supported languages."),
)
.arg(
Arg::with_name("package-managers")
.short("p")
.long("package-managers")
.help("Prints out supported package managers."),
)
.arg(
Arg::with_name("show-logo")
.long("show-logo")
.value_name("WHEN")
.takes_value(true)
.possible_values(&["auto", "never", "always"])
.default_value("always")
.hide_default_value(true)
.help("Specify when to show the logo (auto, never, *always*).")
.long_help(
"Specify when to show the logo (auto, never, *always*). \n\
If set to auto: the logo will be hidden if the terminal's width < 95.")
)
.arg(
Arg::with_name("image")
.short("i")
.long("image")
.value_name("IMAGE")
.takes_value(true)
.help("Path to the IMAGE file."),
)
.arg(
Arg::with_name("image-backend")
.long("image-backend")
.value_name("BACKEND")
.takes_value(true)
.requires("image")
.possible_values(&possible_backends)
.help("Which image BACKEND to use."),
)
.arg(
Arg::with_name("color-resolution")
.long("color-resolution")
.value_name("VALUE")
.requires("image")
.takes_value(true)
.possible_values(&["16", "32", "64", "128", "256"])
.help("VALUE of color resolution to use with SIXEL backend."),
)
.arg(
Arg::with_name("ascii-language")
.short("a")
.value_name("LANGUAGE")
.long("ascii-language")
.takes_value(true)
.case_insensitive(true)
.help("Which LANGUAGE's ascii art to print.")
.possible_values(
&Language::iter()
.map(|language| language.into())
.collect::<Vec<&str>>())
)
.arg(
Arg::with_name("ascii-input")
.long("ascii-input")
.value_name("STRING")
.takes_value(true)
.help("Takes a non-empty STRING as input to replace the ASCII logo.")
.long_help(
"Takes a non-empty STRING as input to replace the ASCII logo. \
It is possible to pass a generated STRING by command substitution. \n\
For example:\n \
'--ascii-input \"$(fortune | cowsay -W 25)\"'")
.validator(|t| {
if t.is_empty() {
Err(String::from("must not be empty"))
} else {
Ok(())
}
}),
)
.arg(
Arg::with_name("true-color")
.long("true-color")
.value_name("WHEN")
.takes_value(true)
.possible_values(&["auto", "never", "always"])
.default_value("auto")
.hide_default_value(true)
.help("Specify when to use true color (*auto*, never, always).")
.long_help(
"Specify when to use true color (*auto*, never, always). \n\
If set to auto: true color will be enabled if supported by the terminal.")
)
.arg(
Arg::with_name("ascii-colors")
.short("c")
.long("ascii-colors")
.value_name("X")
.multiple(true)
.takes_value(true)
.possible_values(color_values)
.help("Colors (X X X...) to print the ascii art."),
)
.arg(
Arg::with_name("text-colors")
.short("t")
.long("text-colors")
.value_name("X")
.multiple(true)
.takes_value(true)
.max_values(6)
.possible_values(color_values)
.help("Changes the text colors (X X X...).")
.long_help(
"Changes the text colors (X X X...). \
Goes in order of title, ~, underline, subtitle, colon, and info. \n\
For example:\n \
'--text-colors 9 10 11 12 13 14'")
)
.arg(
Arg::with_name("no-bold")
.long("no-bold")
.help("Turns off bold formatting."),
)
.arg(
Arg::with_name("no-palette")
.long("no-palette")
.help("Hides the color palette."),
)
.arg(
Arg::with_name("no-merges")
.long("no-merges")
.help("Ignores merge commits."),
)
.arg(
Arg::with_name("no-bots")
.long("no-bots")
.min_values(0)
.max_values(1)
.value_name("REGEX")
.help("Exclude [bot] commits. Use <REGEX> to override the default pattern.")
.validator(|p| {
match Regex::from_str(&p) {
Ok(_) => Ok(()),
Err(_) => Err(String::from("must be a valid regex pattern"))
}
}),
)
.arg(
Arg::with_name("isotime")
.short("z")
.long("isotime")
.help("Use ISO 8601 formatted timestamps.")
)
.arg(
Arg::with_name("disable-fields")
.long("disable-fields")
.short("d")
.value_name("FIELD")
.multiple(true)
.takes_value(true)
.case_insensitive(true)
.help("Allows you to disable FIELD(s) from appearing in the output.")
.possible_values(
&InfoField::iter()
.map(|field| field.into())
.collect::<Vec<&str>>())
)
.arg(
Arg::with_name("authors-number")
.short("A")
.long("authors-number")
.value_name("NUM")
.takes_value(true)
.default_value("3")
.help("NUM of authors to be shown.")
.validator(|t| {
match t.parse::<u32>() {
Ok(_) => Ok(()),
Err(_) => Err(String::from("must be a number"))
}
})
)
.arg(
Arg::with_name("email")
.short("E")
.long("email")
.help("show the email address of each author.")
)
.arg(
Arg::with_name("hidden")
.long("hidden")
.help("Count hidden files and directories.")
)
.arg(
Arg::with_name("exclude")
.short("e")
.long("exclude")
.value_name("EXCLUDE")
.multiple(true)
.takes_value(true)
.help("Ignore all files & directories matching EXCLUDE."),
)
.get_matches();
let true_color = match matches.value_of("true-color") {
Some("always") => true,
Some("never") => false,
Some("auto") => is_truecolor_terminal(),
_ => unreachable!(),
};
let no_bold = matches.is_present("no-bold");
let no_merges = matches.is_present("no-merges");
let no_color_palette = matches.is_present("no-palette");
let print_languages = matches.is_present("languages");
let print_package_managers = matches.is_present("package-managers");
let iso_time = matches.is_present("isotime");
let show_email = matches.is_present("email");
let include_hidden = matches.is_present("hidden");
let output = matches.value_of("output").map(SerializationFormat::from_str).transpose()?;
let fields_to_hide: Vec<String> = if let Some(values) = matches.values_of("disable-fields")
{
values.map(String::from).collect()
} else {
Vec::new()
};
let disabled_fields = InfoFieldOff::new(fields_to_hide)?;
let art_off = match matches.value_of("show-logo") {
Some("always") => false,
Some("never") => true,
Some("auto") => {
if let Some((width, _)) = term_size::dimensions_stdout() {
width < MAX_TERM_WIDTH
} else {
false
}
}
_ => unreachable!(),
};
let image = if let Some(image_path) = matches.value_of("image") {
Some(image::open(image_path).with_context(|| "Could not load the specified image")?)
} else {
None
};
let image_backend = if image.is_some() {
if let Some(backend_name) = matches.value_of("image-backend") {
image_backends::get_image_backend(backend_name)
} else {
image_backends::get_best_backend()
}
} else {
None
};
let image_color_resolution = if let Some(value) = matches.value_of("color-resolution") {
usize::from_str(value)?
} else {
16
};
let repo_path = matches
.value_of("input")
.map(String::from)
.with_context(|| "Failed to parse input directory")?;
let ascii_input = matches.value_of("ascii-input").map(String::from);
let ascii_language = matches
.value_of("ascii-language")
.map(|ascii_language| Language::from_str(&ascii_language.to_lowercase()).unwrap());
let ascii_colors = if let Some(values) = matches.values_of("ascii-colors") {
values.map(String::from).collect()
} else {
Vec::new()
};
let text_colors = if let Some(values) = matches.values_of("text-colors") {
values.map(String::from).collect()
} else {
Vec::new()
};
let number_of_authors: usize = matches.value_of("authors-number").unwrap().parse()?;
let ignored_directories =
if let Some(user_ignored_directories) = matches.values_of("exclude") {
user_ignored_directories.map(String::from).collect()
} else {
Vec::new()
};
let bot_regex_pattern = matches.is_present("no-bots").then(|| {
matches
.value_of("no-bots")
.map_or(Regex::from_str(r"\[bot\]").unwrap(), |s| Regex::from_str(s).unwrap())
});
Ok(Config {
repo_path,
ascii_input,
ascii_language,
ascii_colors,
disabled_fields,
no_bold,
image,
image_backend,
image_color_resolution,
no_merges,
no_color_palette,
number_of_authors,
ignored_directories,
bot_regex_pattern,
print_languages,
print_package_managers,
output,
true_color,
art_off,
text_colors,
iso_time,
show_email,
include_hidden,
})
}
}
pub fn print_supported_languages() -> Result<()> {
for l in Language::iter() {
println!("{}", l);
}
Ok(())
}
pub fn print_supported_package_managers() -> Result<()> {
for p in PackageManager::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 = Command::new("git").arg("--version").output();
match version {
Ok(v) => String::from_utf8_lossy(&v.stdout).replace('\n', ""),
Err(_) => String::new(),
}
}