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
use crate::{
author::Author,
core::{naughty_word, split_into_clean_words},
};
use git2::{Commit, Repository};
#[cfg(feature = "json")]
use serde::Serialize;
use std::{collections::HashMap, env, error::Error, io, io::Write, path::Path};
#[cfg(feature = "table")]
use tabwriter::TabWriter;
#[derive(Debug)]
#[cfg_attr(feature = "json", derive(Serialize))]
pub struct Repo {
pub name: String,
pub total_commits: usize,
pub total_curses: usize,
pub curses: HashMap<String, usize>,
pub authors: HashMap<String, Author>,
}
impl Repo {
pub fn new(path: &Path) -> Result<Self, Box<dyn Error>> {
let repo = Repository::open(path)?;
let commits = Repo::commits(&repo)?;
let repo = match path.file_name() {
Some(path) => path.to_str().unwrap().to_owned(),
None => env::current_dir()?.to_str().unwrap().to_owned(),
};
let mut repo = Repo {
name: repo,
total_commits: 0,
total_curses: 0,
curses: HashMap::new(),
authors: HashMap::new(),
};
repo.build(commits);
repo.count_curses();
Ok(repo)
}
pub fn author(&mut self, author_name: &str) -> &mut Author {
if !self.authors.contains_key(author_name) {
self.authors
.entry(author_name.into())
.or_insert_with(|| Author::new(author_name));
}
self.authors.get_mut(author_name).expect("exists")
}
pub fn count_curses(&mut self) {
for author in self.authors.values() {
for (name, curse) in &author.curses {
self.curses
.entry(name.to_string())
.and_modify(|c| *c += *curse)
.or_insert_with(|| *curse);
}
}
}
fn total_naughty_authors(&self) -> usize {
self.authors.values().filter(|a| a.is_naughty()).count()
}
#[cfg(feature = "json")]
pub fn print_json(&self) -> Result<(), Box<dyn Error>> {
let serialized = serde_json::to_string(&self)?;
write!(io::stdout(), "{}", serialized)?;
io::stdout().flush()?;
Ok(())
}
#[cfg(feature = "table")]
pub fn print_list(&self) -> Result<(), Box<dyn Error>> {
let mut tw = TabWriter::new(vec![]);
let curses = Repo::sort(&self.curses);
self.table_headers(&mut tw, &curses)?;
self.table_separators(&mut tw, &curses)?;
self.table_authors(&mut tw, &curses)?;
if self.total_naughty_authors() > 1 {
self.table_separators(&mut tw, &curses)?;
self.table_total(&mut tw, &curses)?;
}
tw.flush()?;
write!(io::stdout(), "{}", String::from_utf8(tw.into_inner()?)?)?;
io::stdout().flush()?;
Ok(())
}
#[cfg(feature = "table")]
fn sort(curses: &HashMap<String, usize>) -> Vec<(String, usize)> {
let mut curses: Vec<(&String, &usize)> = curses.iter().collect();
curses.sort_by(|(a, _), (b, _)| a.cmp(b));
let curses: Vec<_> = curses
.iter()
.map(|(c, i)| ((*c).to_string(), **i))
.collect();
curses
}
#[cfg(feature = "table")]
fn table_headers(
&self,
tw: &mut TabWriter<Vec<u8>>,
curses: &[(String, usize)],
) -> Result<(), Box<dyn Error>> {
let mut header = String::new();
header.push_str("Author");
header.push_str("\t");
curses
.iter()
.for_each(|(curse, _)| header.push_str(&[curse, "\t"].concat()));
header.push_str(&["Total", "\t"].concat());
writeln!(tw, "{}", header)?;
Ok(())
}
#[cfg(feature = "table")]
fn table_separators(
&self,
tw: &mut TabWriter<Vec<u8>>,
curses: &[(String, usize)],
) -> Result<(), Box<dyn Error>> {
let mut sep = String::new();
sep.push_str(&[&"-".repeat("Author".len()), "\t"].concat());
curses
.iter()
.map(|(curse, _)| (curse, curse.len()))
.for_each(|(_, curse_len)| sep.push_str(&[&"-".repeat(curse_len), "\t"].concat()));
sep.push_str(&[&"-".repeat("Total".len()), "\t"].concat());
writeln!(tw, "{}", sep)?;
Ok(())
}
#[cfg(feature = "table")]
fn table_authors(
&self,
tw: &mut TabWriter<Vec<u8>>,
curses: &[(String, usize)],
) -> Result<(), Box<dyn Error>> {
let mut authors: Vec<_> = self.authors.values().collect();
authors.sort_unstable_by_key(|a| &a.name);
for author in authors {
if author.is_naughty() {
let mut out = String::new();
out.push_str(&[&author.name, "\t"].concat());
for (curse, _) in curses {
if let Some(count) = author.curses.get(curse) {
out.push_str(&[&count.to_string(), "\t"].concat());
} else {
out.push_str("0\t");
}
}
out.push_str(&author.curses.values().sum::<usize>().to_string());
writeln!(tw, "{}", out)?;
}
}
Ok(())
}
#[cfg(feature = "table")]
fn table_total(
&self,
tw: &mut TabWriter<Vec<u8>>,
curses: &[(String, usize)],
) -> Result<(), Box<dyn Error>> {
let mut out = String::new();
out.push_str(&["Overall", "\t"].concat());
curses
.iter()
.for_each(|(_, count)| out.push_str(&[&count.to_string(), "\t"].concat()));
out.push_str(&self.total_curses.to_string());
writeln!(tw, "{}", out)?;
Ok(())
}
pub fn commits(repo: &Repository) -> Result<Vec<Commit>, Box<dyn Error>> {
let mut revwalk = repo.revwalk()?;
let mut commits: Vec<Commit> = Vec::new();
revwalk.push_head()?;
for commit_id in revwalk {
let commit = repo.find_commit(commit_id?)?;
commits.push(commit);
}
Ok(commits)
}
pub fn build(&mut self, commits: Vec<Commit>) {
for commit in &commits {
if let (Some(author_name), Some(commit_message)) = (
commit.author().name(),
commit.message().map(|w| w.to_lowercase()),
) {
let mut curses_added = 0;
{
let author = self.author(author_name);
author.total_commits += 1;
for word in split_into_clean_words(&commit_message) {
if naughty_word(word) {
author.total_curses += 1;
curses_added += 1;
author.update_occurrence(word);
}
}
}
self.total_commits += 1;
self.total_curses += curses_added;
} else {
eprintln!(
"Skipping commit {:?} because either the commit author or message is missing",
commit
);
}
}
}
}