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
#![warn(clippy::all)]
use crate::git_logger::{CommitChange, FileChange, GitLog, GitLogEntry, User};
use chrono::offset::TimeZone;
use chrono::Utc;
use failure::Error;
use git2::Oid;
use indicatif::{ProgressBar, ProgressStyle};
use serde::Serialize;
use std::collections::HashMap;
use std::path::Path;
use std::path::PathBuf;
#[derive(Debug, Serialize, Builder)]
#[builder(setter(into), pattern = "owned")]
pub struct FileHistoryEntry {
pub id: String,
pub committer: User,
pub commit_time: u64,
pub author: User,
pub author_time: u64,
pub co_authors: Vec<User>,
pub change: CommitChange,
pub lines_added: u64,
pub lines_deleted: u64,
}
impl FileHistoryEntry {
fn from(entry: &GitLogEntry, file_change: &FileChange) -> FileHistoryEntry {
let entry = entry.clone();
let file_change = file_change.clone();
FileHistoryEntry {
id: entry.id().to_owned(),
committer: entry.committer().clone(),
commit_time: *entry.commit_time(),
author: entry.author().clone(),
author_time: *entry.author_time(),
co_authors: entry.co_authors().clone(),
change: file_change.change().clone(),
lines_added: *file_change.lines_added(),
lines_deleted: *file_change.lines_deleted(),
}
}
}
#[cfg(test)]
impl FileHistoryEntryBuilder {
pub fn test_default() -> Self {
FileHistoryEntryBuilder::default()
.co_authors(Vec::new())
.change(CommitChange::Add)
.lines_added(0u64)
.lines_deleted(0u64)
}
pub fn emails(self, email: &str) -> Self {
self.committer(User::new(None, Some(email)))
.author(User::new(None, Some(email)))
}
pub fn times(self, time: u64) -> Self {
self.commit_time(time).author_time(time)
}
}
#[derive(Debug, Serialize)]
pub struct GitFileHistory {
workdir: PathBuf,
history_by_file: HashMap<PathBuf, Vec<FileHistoryEntry>>,
last_commit: u64,
}
impl GitFileHistory {
pub fn new(log: &mut GitLog) -> Result<GitFileHistory, Error> {
let mut last_commit: u64 = 0;
let mut history_by_file = HashMap::<PathBuf, Vec<FileHistoryEntry>>::new();
let progress_bar = ProgressBar::new_spinner()
.with_style(ProgressStyle::default_spinner().template("[{elapsed}] {msg}"));
let log_iterator = log.iterator()?;
let git_file_future_registry = log_iterator.git_file_future_registry();
let log_entries: Vec<Result<GitLogEntry, Error>> = log_iterator.collect();
let git_file_future_registry = git_file_future_registry.borrow();
for entry in log_entries {
progress_bar.tick();
match entry {
Ok(entry) => {
let commit_time = *entry.commit_time();
let fmt_time = Utc.timestamp(commit_time as i64, 0).to_string();
progress_bar.set_message(&fmt_time);
if commit_time > last_commit {
last_commit = commit_time;
}
for file_change in entry.clone().file_changes() {
let final_filename = git_file_future_registry
.final_name(&Oid::from_str(entry.id()).unwrap(), file_change.file());
if let Some(filename) = final_filename {
let hash_entry =
history_by_file.entry(filename).or_insert_with(Vec::new);
let new_entry = FileHistoryEntry::from(&entry, &file_change);
hash_entry.push(new_entry);
} else {
debug!(
"Not storing history for deleted file {:?}",
file_change.file()
);
}
}
}
Err(e) => {
warn!("Ignoring invalid git log entry: {:?}", e);
}
}
}
Ok(GitFileHistory {
workdir: log.workdir().to_owned(),
history_by_file,
last_commit,
})
}
pub fn is_repo_for(&self, file: &Path) -> Result<bool, Error> {
let canonical_file = file.canonicalize()?;
Ok(canonical_file.starts_with(&self.workdir))
}
pub fn history_for(&self, file: &Path) -> Result<Option<&Vec<FileHistoryEntry>>, Error> {
let canonical_file = file.canonicalize()?;
let relative_file = canonical_file.strip_prefix(&self.workdir)?;
Ok(self.history_by_file.get(relative_file))
}
pub fn last_commit(&self) -> u64 {
self.last_commit
}
}
#[cfg(test)]
mod test {
use super::*;
use crate::git_logger::GitLogConfig;
use pretty_assertions::assert_eq;
use tempfile::tempdir;
use test_shared::*;
#[test]
fn can_get_log_by_filename() -> Result<(), Error> {
let gitdir = tempdir()?;
let git_root = unzip_git_sample("git_sample", gitdir.path())?;
let mut git_log = GitLog::new(&git_root, GitLogConfig::default())?;
let history = GitFileHistory::new(&mut git_log)?;
assert_eq!(history.workdir.canonicalize()?, git_root.canonicalize()?);
assert_eq_json_file(
&history.history_by_file,
"./tests/expected/git/git_sample_by_filename.json",
);
Ok(())
}
#[test]
fn can_tell_if_file_is_in_git_repo() -> Result<(), Error> {
let gitdir = tempdir()?;
let git_root = unzip_git_sample("git_sample", gitdir.path())?;
let mut git_log = GitLog::new(&git_root, GitLogConfig::default())?;
let history = GitFileHistory::new(&mut git_log)?;
assert_eq!(
history.is_repo_for(&git_root.join("simple/parent.clj"))?,
true
);
Ok(())
}
#[test]
fn can_get_history_for_file() -> Result<(), Error> {
let gitdir = tempdir()?;
let git_root = unzip_git_sample("git_sample", gitdir.path())?;
let mut git_log = GitLog::new(&git_root, GitLogConfig::default())?;
let history = GitFileHistory::new(&mut git_log)?;
let file_history = history.history_for(&git_root.join("simple/parent.clj"))?;
assert_eq!(file_history.is_some(), true);
let ids: Vec<_> = file_history.unwrap().iter().map(|h| &h.id).collect();
assert_eq!(
ids,
vec![
"0dbd54d4c524ecc776f381e660cce9b2dd92162c",
"a0ae9997cfdf49fd0cbf54dacc72c778af337519",
"ca239efb9b26db57ac9e2ec3e2df1c42578a46f8"
]
);
assert_eq!(history.last_commit(), 1_558_533_240);
Ok(())
}
#[test]
fn no_history_for_files_not_known() -> Result<(), Error> {
let gitdir = tempdir()?;
let git_root = unzip_git_sample("git_sample", gitdir.path())?;
let mut git_log = GitLog::new(&git_root, GitLogConfig::default())?;
let history = GitFileHistory::new(&mut git_log)?;
let new_file = git_root.join("simple/nonesuch.clj");
std::fs::File::create(&new_file)?;
let file_history = history.history_for(&new_file)?;
assert_eq!(file_history.is_none(), true);
Ok(())
}
#[test]
fn can_get_history_for_complex_renamed_files() -> Result<(), Error> {
let gitdir = tempdir()?;
let git_root = unzip_git_sample("rename_complex", gitdir.path())?;
let mut git_log = GitLog::new(&git_root, GitLogConfig::default())?;
let history = GitFileHistory::new(&mut git_log)?;
let file_history = history.history_for(&git_root.join("a.txt"))?;
let ids: Vec<_> = file_history.unwrap().iter().map(|h| &h.id).collect();
assert_eq!(
ids,
vec![
"c3b47c335ebd9dbb9b0c9922bc258555a2cf71c9",
"500a621e9e83612f51dbce15202cd7bef3c88f00",
"34b904b010abf316167bba7a7ce2b4a5996cc0d1",
"3bd2d9088ee5b051ada1bd30f07e7bcd390f6327",
"8be47dfc0a25ec27941413619f632a1fa66e5ba5",
"388e644e9240aa333fe669069bb00d418ffca500",
"bd6d7dfa063ec95ebc3bad7bffd4262e3702b77c",
]
);
Ok(())
}
#[test]
fn deleted_files_dont_have_history() -> Result<(), Error> {
let gitdir = tempdir()?;
let git_root = unzip_git_sample("rename_complex", gitdir.path())?;
let mut git_log = GitLog::new(&git_root, GitLogConfig::default())?;
let history = GitFileHistory::new(&mut git_log)?;
let file_history = history.history_for(&git_root.join("z.txt"))?;
assert_eq!(file_history.is_some(), true);
let ids: Vec<_> = file_history.unwrap().iter().map(|h| &h.id).collect();
assert_eq!(
ids,
vec!["3629e5a8d8d7547bac749530eb540d0f61535cd1",]
);
Ok(())
}
}