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
use std::{collections::BTreeMap, fmt, ops, path::PathBuf};
use crate::LanguageType;
#[derive(Clone, Debug, Default, PartialEq, serde::Deserialize, serde::Serialize)]
#[non_exhaustive]
pub struct CodeStats {
pub blanks: usize,
pub code: usize,
pub comments: usize,
pub blobs: BTreeMap<LanguageType, CodeStats>,
}
impl CodeStats {
pub fn new() -> Self {
Self::default()
}
pub fn lines(&self) -> usize {
self.blanks + self.code + self.comments
}
pub fn summarise(&self) -> Self {
let mut summary = self.clone();
for (_, stats) in std::mem::replace(&mut summary.blobs, BTreeMap::new()) {
let child_summary = stats.summarise();
summary.blanks += child_summary.blanks;
summary.comments += child_summary.comments;
summary.code += child_summary.code;
}
summary
}
}
impl ops::Add for CodeStats {
type Output = Self;
fn add(mut self, rhs: Self) -> Self::Output {
self += rhs;
self
}
}
impl ops::AddAssign for CodeStats {
fn add_assign(&mut self, rhs: Self) {
self.blanks += rhs.blanks;
self.code += rhs.code;
self.comments += rhs.comments;
for (language, stats) in rhs.blobs {
*self.blobs.entry(language).or_default() += stats;
}
}
}
#[derive(Deserialize, Serialize, Clone, Debug, Default, PartialEq)]
#[non_exhaustive]
pub struct Report {
pub stats: CodeStats,
pub name: PathBuf,
}
impl Report {
pub fn new(name: PathBuf) -> Self {
Report {
name,
..Self::default()
}
}
}
impl ops::AddAssign<CodeStats> for Report {
fn add_assign(&mut self, rhs: CodeStats) {
self.stats += rhs;
}
}
#[doc(hidden)]
pub fn find_char_boundary(s: &str, index: usize) -> usize {
for i in 0..4 {
if s.is_char_boundary(index + i) {
return index + i;
}
}
unreachable!();
}
macro_rules! display_stats {
($f:expr, $this:expr, $name:expr, $max:expr) => {
write!(
$f,
" {: <max$} {:>12} {:>12} {:>12} {:>12}",
$name,
$this.stats.lines(),
$this.stats.code,
$this.stats.comments,
$this.stats.blanks,
max = $max
)
};
}
impl fmt::Display for Report {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let name = self.name.to_string_lossy();
let name_length = name.len();
let max_len = f.width().unwrap_or(25);
if name_length <= max_len {
display_stats!(f, self, name, max_len)
} else {
let mut formatted = String::from("|");
let from = find_char_boundary(&name, name_length + 1 - max_len);
formatted.push_str(&name[from..]);
display_stats!(f, self, formatted, max_len)
}
}
}