-
Notifications
You must be signed in to change notification settings - Fork 320
Expand file tree
/
Copy pathchurn.rs
More file actions
227 lines (196 loc) · 6.88 KB
/
Copy pathchurn.rs
File metadata and controls
227 lines (196 loc) · 6.88 KB
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
use super::utils::info_field::InfoField;
use crate::{cli::NumberSeparator, info::utils::format_number};
use anyhow::{Context, Result};
use gix::bstr::BString;
use globset::{GlobSetBuilder, Glob as GlobPattern};
use serde::Serialize;
use std::{collections::HashMap, fmt::Write};
#[derive(Serialize, Clone, Debug, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct FileChurn {
pub file_path: String,
pub nbr_of_commits: usize,
#[serde(skip_serializing)]
number_separator: NumberSeparator,
}
impl FileChurn {
pub fn new(
file_path: String,
nbr_of_commits: usize,
number_separator: NumberSeparator,
) -> Self {
Self {
file_path,
nbr_of_commits,
number_separator,
}
}
}
impl std::fmt::Display for FileChurn {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(
f,
"{} {}",
shorten_file_path(&self.file_path, 2),
format_number(&self.nbr_of_commits, self.number_separator)
)
}
}
#[derive(Serialize)]
pub struct ChurnInfo {
pub file_churns: Vec<FileChurn>,
pub churn_pool_size: usize,
}
impl ChurnInfo {
pub fn new(
number_of_commits_by_file_path: &HashMap<BString, usize>,
churn_pool_size: usize,
number_of_file_churns_to_display: usize,
globs_to_exclude: &[String],
number_separator: NumberSeparator,
) -> Result<Self> {
let file_churns = compute_file_churns(
number_of_commits_by_file_path,
number_of_file_churns_to_display,
globs_to_exclude,
number_separator,
)?;
Ok(Self {
file_churns,
churn_pool_size,
})
}
}
fn compute_file_churns(
number_of_commits_by_file_path: &HashMap<BString, usize>,
number_of_file_churns_to_display: usize,
globs_to_exclude: &[String],
number_separator: NumberSeparator,
) -> Result<Vec<FileChurn>> {
// Build a glob matcher for all the patterns to exclude
let mut builder = GlobSetBuilder::new();
for pattern in globs_to_exclude {
builder.add(GlobPattern::new(pattern)?);
}
let matcher = builder.build().context("Failed to build glob matcher for file exclusions")?;
let mut number_of_commits_by_file_path_sorted = Vec::from_iter(number_of_commits_by_file_path);
number_of_commits_by_file_path_sorted.sort_by(|(_, a), (_, b)| b.cmp(a));
let file_churns = number_of_commits_by_file_path_sorted
.into_iter()
.filter_map(|(file_path, count)| {
let path = std::str::from_utf8(&file_path).ok()?;
if matcher.is_match(path) {
return None;
}
let file_name = path.split('/').last().unwrap_or(path);
Some(FileChurn::new(
file_name.to_string(),
*count,
number_separator,
))
})
.take(number_of_file_churns_to_display)
.collect();
Ok(file_churns)
}
impl std::fmt::Display for ChurnInfo {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
let mut churn_info = String::new();
let pad = self.title().len() + 2;
for (i, file_churn) in self.file_churns.iter().enumerate() {
if i == 0 {
write!(churn_info, "{file_churn}")?;
} else {
write!(churn_info, "\n{:<width$}{}", "", file_churn, width = pad)?;
}
}
write!(f, "{churn_info}")
}
}
#[typetag::serialize]
impl InfoField for ChurnInfo {
fn value(&self) -> String {
self.to_string()
}
fn title(&self) -> String {
format!("Churn ({})", self.churn_pool_size)
}
}
fn shorten_file_path(file_path: &str, depth: usize) -> String {
let components: Vec<&str> = file_path.split('/').collect();
if depth == 0 || components.len() <= depth {
return file_path.to_string();
}
let truncated_components: Vec<&str> = components
.iter()
.skip(components.len() - depth)
.copied()
.collect();
format!("\u{2026}/{}", truncated_components.join("/"))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_display_file_churn() {
let file_churn = FileChurn::new("path/to/file.txt".into(), 50, NumberSeparator::Plain);
assert_eq!(file_churn.to_string(), "\u{2026}/to/file.txt 50");
}
#[test]
fn test_churn_info_value_with_two_file_churns() {
let file_churn_1 = FileChurn::new("path/to/file.txt".into(), 50, NumberSeparator::Plain);
let file_churn_2 = FileChurn::new("file_2.txt".into(), 30, NumberSeparator::Plain);
let churn_info = ChurnInfo {
file_churns: vec![file_churn_1, file_churn_2],
churn_pool_size: 5,
};
assert!(churn_info
.value()
.contains(&"\u{2026}/to/file.txt 50".to_string()));
assert!(churn_info.value().contains(&"file_2.txt 30".to_string()));
}
#[test]
fn test_truncate_file_path() {
assert_eq!(shorten_file_path("path/to/file.txt", 3), "path/to/file.txt");
assert_eq!(shorten_file_path("another/file.txt", 2), "another/file.txt");
assert_eq!(shorten_file_path("file.txt", 1), "file.txt");
assert_eq!(
shorten_file_path("path/to/file.txt", 2),
"\u{2026}/to/file.txt"
);
assert_eq!(
shorten_file_path("another/file.txt", 1),
"\u{2026}/file.txt"
);
assert_eq!(shorten_file_path("file.txt", 0), "file.txt");
}
#[test]
fn test_compute_file_churns() -> Result<()> {
let mut number_of_commits_by_file_path = HashMap::new();
number_of_commits_by_file_path.insert("path/to/file1.txt".into(), 2);
number_of_commits_by_file_path.insert("path/to/file2.txt".into(), 5);
number_of_commits_by_file_path.insert("path/to/file3.txt".into(), 3);
number_of_commits_by_file_path.insert("path/to/file4.txt".into(), 7);
number_of_commits_by_file_path.insert("foo/x/y/file.txt".into(), 70);
number_of_commits_by_file_path.insert("foo/x/file.txt".into(), 10);
let number_of_file_churns_to_display = 3;
let number_separator = NumberSeparator::Comma;
let globs_to_exclude = vec![
"foo/**/file.txt".to_string(),
"path/to/file2.txt".to_string(),
];
let actual = compute_file_churns(
&number_of_commits_by_file_path,
number_of_file_churns_to_display,
&globs_to_exclude,
number_separator,
)?;
let expected = vec![
FileChurn::new(String::from("file4.txt"), 7, number_separator),
FileChurn::new(String::from("file3.txt"), 3, number_separator),
FileChurn::new(String::from("file1.txt"), 2, number_separator),
];
assert_eq!(actual, expected);
Ok(())
}
}