forked from o2sh/onefetch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinfo.rs
596 lines (526 loc) · 19.5 KB
/
info.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
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
use std::ffi::OsStr;
use std::fmt::Write;
use std::fs;
use std::process::Command;
use std::str::FromStr;
use colored::{Color, Colorize, ColoredString};
use git2::Repository;
use license::License;
use crate::language::Language;
use crate::{AsciiArt, CommitInfo, Configuration, Error, InfoFieldOn};
type Result<T> = std::result::Result<T, crate::Error>;
pub struct Info {
git_version: String,
git_username: String,
project_name: String,
current_commit: CommitInfo,
version: String,
creation_date: String,
dominant_language: Language,
languages: Vec<(Language, f64)>,
authors: Vec<(String, usize, usize)>,
last_change: String,
repo: String,
commits: String,
repo_size: String,
number_of_lines: usize,
license: String,
custom_logo: Language,
custom_colors: Vec<String>,
disable_fields: InfoFieldOn,
bold_enabled: bool,
}
impl std::fmt::Display for Info {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
let mut buf = String::new();
let color = match self.colors().get(0) {
Some(&c) => c,
None => Color::White,
};
if !self.disable_fields.git_info{
let git_info;
if self.git_username != "" {
git_info = format!("{} : {}", self.git_username, self.git_version);
write!(&mut buf, "{}{}", &self.get_formatted_info_label(&self.git_username, color), " : ")?;
} else {
git_info = self.git_version.clone();
}
write_buf(&mut buf, &self.get_formatted_info_label(&self.git_version, color), "")?;
let separator = "-".repeat(git_info.len());
write_buf(&mut buf, &self.get_formatted_info_label("", color), &separator)?;
}
if !self.disable_fields.project {
write_buf(&mut buf, &self.get_formatted_info_label("Project: ", color), &self.project_name)?;
}
if !self.disable_fields.head {
write_buf(&mut buf, &self.get_formatted_info_label("HEAD: ", color), &self.current_commit)?;
}
if !self.disable_fields.version {
write_buf(&mut buf, &self.get_formatted_info_label("Version: ", color), &self.version)?;
}
if !self.disable_fields.created {
write_buf(&mut buf, &self.get_formatted_info_label("Created: ", color), &self.creation_date)?;
}
if !self.disable_fields.languages && !self.languages.is_empty() {
if self.languages.len() > 1 {
let title = "Languages: ";
let pad = " ".repeat(title.len());
let mut s = String::from("");
for (cnt, language) in self.languages.iter().enumerate() {
let formatted_number = format!("{:.*}", 2, language.1);
if cnt != 0 && cnt % 3 == 0 {
s = s + &format!("\n{}{} ({} %) ", pad, language.0, formatted_number);
} else {
s = s + &format!("{} ({} %) ", language.0, formatted_number);
}
}
writeln!(buf, "{}{}", &self.get_formatted_info_label(title, color), s)?;
} else {
write_buf(&mut buf, &self.get_formatted_info_label("Language: ", color), &self.dominant_language)?;
};
}
if !self.disable_fields.authors && !self.authors.is_empty() {
let title = if self.authors.len() > 1 {
"Authors: "
} else {
"Author: "
};
writeln!(
buf,
"{}{}% {} {}",
&self.get_formatted_info_label(title, color),
self.authors[0].2,
self.authors[0].0,
self.authors[0].1
)?;
let title = " ".repeat(title.len());
for author in self.authors.iter().skip(1) {
writeln!(
buf,
"{}{}% {} {}",
&self.get_formatted_info_label(&title, color),
author.2,
author.0,
author.1
)?;
}
}
if !self.disable_fields.last_change {
write_buf(&mut buf, &self.get_formatted_info_label("Last change: ", color), &self.last_change)?;
}
if !self.disable_fields.repo {
write_buf(&mut buf, &self.get_formatted_info_label("Repo: ", color), &self.repo)?;
}
if !self.disable_fields.commits {
write_buf(&mut buf, &self.get_formatted_info_label("Commits: ", color), &self.commits)?;
}
if !self.disable_fields.lines_of_code {
write_buf(&mut buf, &self.get_formatted_info_label("Lines of code: ", color), &self.number_of_lines)?;
}
if !self.disable_fields.size {
write_buf(&mut buf, &self.get_formatted_info_label("Size: ", color), &self.repo_size)?;
}
if !self.disable_fields.license {
write_buf(&mut buf, &self.get_formatted_info_label("License: ", color), &self.license)?;
}
writeln!(
buf,
"\n{0}{1}{2}{3}{4}{5}{6}{7}\n{8}{9}{10}{11}{12}{13}{14}{15}",
" ".on_black(),
" ".on_red(),
" ".on_green(),
" ".on_yellow(),
" ".on_blue(),
" ".on_magenta(),
" ".on_cyan(),
" ".on_white(),
" ".on_bright_black(),
" ".on_bright_red(),
" ".on_bright_green(),
" ".on_bright_yellow(),
" ".on_bright_blue(),
" ".on_bright_magenta(),
" ".on_bright_cyan(),
" ".on_bright_white(),
)?;
let mut logo_lines = AsciiArt::new(self.get_ascii(), self.colors(), self.bold_enabled);
let mut info_lines = buf.lines();
let center_pad = " ";
loop {
match (logo_lines.next(), info_lines.next()) {
(Some(logo_line), Some(info_line)) => {
writeln!(f, "{}{}{:^}", logo_line, center_pad, info_line)?
}
(Some(logo_line), None) => writeln!(f, "{}", logo_line)?,
(None, Some(info_line)) => writeln!(
f,
"{:<width$}{}{:^}",
"",
center_pad,
info_line,
width = logo_lines.width()
)?,
(None, None) => {
writeln!(f, "\n")?;
break;
}
}
}
Ok(())
}
}
impl Info {
pub fn new(
dir: &str,
logo: Language,
colors: Vec<String>,
disabled: InfoFieldOn,
bold_flag: bool,
) -> Result<Info> {
let authors = Info::get_authors(&dir, 3);
let (git_v, git_user) = Info::get_git_info(&dir);
let current_commit_info = Info::get_current_commit_info(&dir)?;
let config = Info::get_configuration(&dir)?;
let version = Info::get_version(&dir)?;
let commits = Info::get_commits(&dir)?;
let repo_size = Info::get_packed_size(&dir)?;
let last_change = Info::get_last_change(&dir)?;
let creation_date = Info::get_creation_time(dir)?;
let project_license = Info::get_project_license(&dir)?;
let (languages_stats, number_of_lines) = Language::get_language_stats(&dir)?;
let dominant_language = Language::get_dominant_language(languages_stats.clone());
Ok(Info {
git_version: git_v,
git_username: git_user,
project_name: config.repository_name,
current_commit: current_commit_info,
version,
creation_date: creation_date,
dominant_language,
languages: languages_stats,
authors,
last_change,
repo: config.repository_url,
commits,
repo_size,
number_of_lines,
license: project_license,
custom_logo: logo,
custom_colors: colors,
disable_fields: disabled,
bold_enabled: bold_flag,
})
}
// Return first n most active commiters as authors within this project.
fn get_authors(dir: &str, n: usize) -> Vec<(String, usize, usize)> {
let output = Command::new("git")
.arg("-C")
.arg(dir)
.arg("log")
.arg("--format='%aN'")
.output()
.expect("Failed to execute git.");
// create map for storing author name as a key and their commit count as value
let mut authors = std::collections::HashMap::new();
let mut total_commits = 0;
let output = String::from_utf8_lossy(&output.stdout);
for line in output.lines() {
let commit_count = authors.entry(line.to_string()).or_insert(0);
*commit_count += 1;
total_commits += 1;
}
// sort authors by commit count where the one with most commit count is first
let mut authors: Vec<(String, usize)> = authors.into_iter().collect();
authors.sort_by_key(|(_, c)| *c);
authors.reverse();
// truncate the vector so we only get the count of authors we specified as 'n'
authors.truncate(n);
// get only authors without their commit count
// and string "'" prefix and suffix
let authors: Vec<(String, usize, usize)> = authors
.into_iter()
.map(|(author, count)| {
(
author.trim_matches('\'').to_string(),
count,
count * 100 / total_commits,
)
})
.collect();
authors
}
fn get_git_info(dir: &str) -> (String, String){
let version = Command::new("git")
.arg("--version")
.output()
.expect("Failed to execute git.");
let version = String::from_utf8_lossy(&version.stdout).replace('\n',"");
let username = Command::new("git")
.arg("-C")
.arg(dir)
.arg("config")
.arg("--get")
.arg("user.name")
.output()
.expect("Failed to execute git.");
let username = String::from_utf8_lossy(&username.stdout).replace('\n',"");
(version, username)
}
fn get_current_commit_info(dir: &str) -> Result<CommitInfo> {
let repo = Repository::open(dir).map_err(|_| Error::NotGitRepo)?;
let head = repo.head().map_err(|_| Error::ReferenceInfoError)?;
let head_oid = head.target().ok_or(Error::ReferenceInfoError)?;
let refs = repo.references().map_err(|_| Error::ReferenceInfoError)?;
let refs_info = refs
.into_iter()
.filter_map(|reference| match reference {
Ok(reference) => match (reference.target(), reference.shorthand()) {
(Some(oid), Some(shorthand)) if oid == head_oid => {
Some(if reference.is_tag() {
String::from("tags/") + shorthand
} else {
String::from(shorthand)
})
}
_ => None,
},
Err(_) => None,
})
.collect::<Vec<String>>();
Ok(CommitInfo::new(head_oid, refs_info))
}
fn get_configuration(dir: &str) -> Result<Configuration> {
let repo = Repository::open(dir).map_err(|_| Error::NotGitRepo)?;
let config = repo.config().map_err(|_| Error::NoGitData)?;
let mut remote_url = String::new();
let mut repository_name = String::new();
let mut remote_upstream: Option<String> = None;
for entry in &config.entries(None).unwrap() {
let entry = entry.unwrap();
match entry.name().unwrap() {
"remote.origin.url" => remote_url = entry.value().unwrap().to_string(),
"remote.upstream.url" => remote_upstream = Some(entry.value().unwrap().to_string()),
_ => (),
}
}
if let Some(url) = remote_upstream {
remote_url = url.clone();
}
let url = remote_url.clone();
let name_parts: Vec<&str> = url.split('/').collect();
if !name_parts.is_empty() {
repository_name = name_parts[name_parts.len() - 1].to_string();
}
if repository_name.contains(".git") {
let repo_name = repository_name.clone();
let parts: Vec<&str> = repo_name.split(".git").collect();
repository_name = parts[0].to_string();
}
Ok(Configuration {
repository_name: repository_name.clone(),
repository_url: name_parts.join("/"),
})
}
fn get_version(dir: &str) -> Result<String> {
let output = Command::new("git")
.arg("-C")
.arg(dir)
.arg("describe")
.arg("--abbrev=0")
.arg("--tags")
.output()
.expect("Failed to execute git.");
let output = String::from_utf8_lossy(&output.stdout);
if output == "" {
Ok("??".into())
} else {
Ok(output.to_string().replace('\n', ""))
}
}
fn get_commits(dir: &str) -> Result<String> {
let output = Command::new("git")
.arg("-C")
.arg(dir)
.arg("rev-list")
.arg("--count")
.arg("HEAD")
.output()
.expect("Failed to execute git.");
let output = String::from_utf8_lossy(&output.stdout);
if output == "" {
Ok("0".into())
} else {
Ok(output.to_string().replace('\n', ""))
}
}
fn get_packed_size(dir: &str) -> Result<String> {
let output = Command::new("git")
.arg("-C")
.arg(dir)
.arg("count-objects")
.arg("-vH")
.output()
.expect("Failed to execute git.");
let output = String::from_utf8_lossy(&output.stdout);
let lines = output.to_string();
let size_line = lines
.split("\n")
.find(|line| line.starts_with("size-pack:"));
let repo_size = match size_line {
None => "??",
Some(size_str) => &(size_str[11..]),
};
let output = Command::new("git")
.arg("-C")
.arg(dir)
.arg("ls-files")
.output()
.expect("Failed to execute git.");
// To check if command executed successfully or not
let error = &output.stderr;
if error.is_empty() {
let output = String::from_utf8_lossy(&output.stdout);
let lines = output.to_string();
let files_list = lines.split("\n");
let mut files_count: u128 = 0;
for _file in files_list {
files_count += 1;
}
files_count -= 1; // As splitting giving one line extra(blank).
let res = repo_size.to_owned() + &(" (") + &(files_count.to_string()) + &(" files)");
Ok(res.into())
} else {
let res = repo_size;
Ok(res.into())
}
}
fn get_last_change(dir: &str) -> Result<String> {
let output = Command::new("git")
.arg("-C")
.arg(dir)
.arg("log")
.arg("-1")
.arg("--format=%cr")
.output()
.expect("Failed to execute git.");
let output = String::from_utf8_lossy(&output.stdout);
if output == "" {
Ok("??".into())
} else {
Ok(output.to_string().replace('\n', ""))
}
}
fn get_creation_time(dir: &str) -> Result<String> {
let output = Command::new("git")
.arg("-C")
.arg(dir)
.arg("log")
.arg("--reverse")
.arg("--pretty=oneline")
.arg("--format=\"%ar\"")
.output()
.expect("Failed to execute git.");
let output = String::from_utf8_lossy(&output.stdout);
let output = match output.lines().next() {
Some(creation_time) => creation_time.replace('"', ""),
None => "??".into(),
};
Ok(output)
}
fn get_project_license(dir: &str) -> Result<String> {
let output = fs::read_dir(dir)
.map_err(|_| Error::ReadDirectory)?
.filter_map(std::result::Result::ok)
.map(|entry| entry.path())
.filter(
|entry| {
entry.is_file()
&& !(entry
.file_name()
.map(OsStr::to_string_lossy)
.iter()
.filter(|x| x.starts_with("LICENSE") || x.starts_with("COPYING"))
.collect::<Vec<_>>()
.is_empty())
}, // TODO: multiple prefixes, like COPYING?
)
.map(|entry| {
license::Kind::from_str(&fs::read_to_string(entry).unwrap_or_else(|_| "".into()))
})
.filter_map(std::result::Result::ok)
.map(|license| license.name().to_string())
.collect::<Vec<_>>()
.join(", ");
if output == "" {
Ok("??".into())
} else {
Ok(output)
}
}
fn get_ascii(&self) -> &str {
let language = if let Language::Unknown = self.custom_logo {
&self.dominant_language
} else {
&self.custom_logo
};
language.get_ascii_art()
}
fn colors(&self) -> Vec<Color> {
let language = if let Language::Unknown = self.custom_logo {
&self.dominant_language
} else {
&self.custom_logo
};
let colors = language.get_colors();
let colors: Vec<Color> = colors
.iter()
.enumerate()
.map(|(index, default_color)| {
if let Some(color_num) = self.custom_colors.get(index) {
if let Some(color) = Info::num_to_color(color_num) {
return color;
}
}
*default_color
})
.collect();
colors
}
fn num_to_color(num: &str) -> Option<Color> {
let color = match num {
"0" => Color::Black,
"1" => Color::Red,
"2" => Color::Green,
"3" => Color::Yellow,
"4" => Color::Blue,
"5" => Color::Magenta,
"6" => Color::Cyan,
"7" => Color::White,
"8" => Color::BrightBlack,
"9" => Color::BrightRed,
"10" => Color::BrightGreen,
"11" => Color::BrightYellow,
"12" => Color::BrightBlue,
"13" => Color::BrightMagenta,
"14" => Color::BrightCyan,
"15" => Color::BrightWhite,
_ => return None,
};
Some(color)
}
/// Returns a formatted info label with the desired color and boldness
fn get_formatted_info_label(&self, label: &str, color: Color) -> ColoredString {
let mut formatted_label = label.color(color);
if self.bold_enabled {
formatted_label = formatted_label.bold();
}
formatted_label
}
}
fn write_buf<T: std::fmt::Display>(
buffer: &mut String,
title: &ColoredString,
content: T,
) -> std::fmt::Result {
writeln!(buffer, "{}{}", title, content)
}