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
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
use std::{
cell::RefCell,
convert::Infallible,
sync::atomic::{AtomicUsize, Ordering},
time::Instant,
};
use anyhow::{anyhow, bail};
use gix::{
bstr::{BStr, BString, ByteSlice},
diff::{blob::platform::prepare_diff::Operation, rewrites::CopySource},
features::progress,
objs::find::Error,
parallel::{InOrderIter, SequenceId},
prelude::ObjectIdExt,
Count, Progress,
};
use rusqlite::{params, Statement, Transaction};
use crate::query::Options;
pub fn update(
repo: &gix::Repository,
con: &mut rusqlite::Connection,
progress: &mut impl gix::NestedProgress,
mut err: impl std::io::Write,
Options {
object_cache_size_mb,
find_copies_harder,
threads,
}: Options,
) -> anyhow::Result<Vec<gix::ObjectId>> {
let commit_id = repo.head_id()?.detach();
let threads = gix::features::parallel::num_threads(threads);
let mut stat_progress = {
let mut p = progress.add_child("extract stats");
p.init(None, progress::count("commits"));
p
};
let stat_counter = stat_progress.counter();
let mut db_progress = {
let mut p = progress.add_child("db cache");
p.init(None, progress::count("events"));
p
};
let commit_counter = db_progress.counter();
let change_progress = {
let mut p = progress.add_child("find changes");
p.init(None, progress::count("modified files"));
p
};
let change_counter = change_progress.counter();
let lines_progress = {
let mut p = progress.add_child("find changes");
p.init(None, progress::count("diff lines"));
p
};
let lines_counter = lines_progress.counter();
let mut traverse_progress = progress.add_child("traverse commit graph");
traverse_progress.init(None, progress::count("commits"));
let out = std::thread::scope(|scope| -> anyhow::Result<_> {
struct CommitDiffStats {
/// The id of the commit which was diffed with its predecessor
id: gix::hash::ObjectId,
changes: Vec<FileChange>,
}
let start = Instant::now();
let (tx_stats, rx_stats) = std::sync::mpsc::channel::<Result<(SequenceId, Vec<CommitDiffStats>), Infallible>>();
let mut all_commits =
Vec::with_capacity(con.query_row("SELECT COUNT(hash) from commits", [], |r| r.get::<_, usize>(0))?);
for item in con
.prepare("SELECT hash from commits ORDER BY ROWID")?
.query_map([], |r| {
Ok(gix::ObjectId::try_from(r.get_ref(0)?.as_bytes()?)
.unwrap_or_else(|_| gix::ObjectId::null(gix::hash::Kind::Sha1)))
})?
{
all_commits.push(item?);
}
let mut known_commits = all_commits.clone();
known_commits.sort();
let db_thread = scope.spawn({
move || -> anyhow::Result<()> {
let trans = con.transaction()?;
{
let Updates {
mut new_commit,
mut insert_commit_file,
mut insert_commit_file_with_source,
mut insert_file_path,
} = Updates::new(&trans)?;
for stats in InOrderIter::from(rx_stats.into_iter()) {
for CommitDiffStats { id, changes } in stats.expect("infallible") {
new_commit.execute(params![id.as_bytes()])?;
for change in changes {
insert_file_path.execute(params![change.relpath.to_str_lossy()])?;
let (has_diff, lines) = change.lines.map(|l| (true, l)).unwrap_or_default();
if let Some(source_relpath) = change.source_relpath {
insert_file_path.execute(params![source_relpath.to_str_lossy()])?;
insert_commit_file_with_source.execute(params![
id.as_bytes(),
change.relpath.to_str_lossy(),
has_diff,
lines.added,
lines.removed,
lines.before,
lines.after,
change.mode as usize,
source_relpath.to_str_lossy(),
])?;
} else {
insert_commit_file.execute(params![
id.as_bytes(),
change.relpath.to_str_lossy(),
has_diff,
lines.added,
lines.removed,
lines.before,
lines.after,
change.mode as usize,
])?;
}
}
commit_counter.fetch_add(1, Ordering::Relaxed);
}
}
}
trans.commit()?;
Ok(())
}
});
let rewrites = {
// These are either configured, or we set them to the default. There is no turning them off.
let (r, was_configured) = gix::diff::new_rewrites(&repo.config_snapshot(), true)?;
if was_configured && r.is_none() {
gix::trace::warn!("Rename tracking is disabled by configuration, but we enable it using the default");
}
let mut r = r.unwrap_or_default();
r.copies = Some(gix::diff::rewrites::Copies {
source: if find_copies_harder {
CopySource::FromSetOfModifiedFilesAndAllSources
} else {
CopySource::FromSetOfModifiedFiles
},
percentage: None,
});
r
};
#[derive(Clone)]
struct Task {
commit: gix::hash::ObjectId,
parent_commit: Option<gix::hash::ObjectId>,
compute_stats: bool,
}
type Packet = (SequenceId, Vec<Task>);
let (tx_tree_ids, stat_threads) = {
let (tx, rx) = crossbeam_channel::unbounded::<Packet>();
let stat_workers = (0..threads)
.map(|_| {
scope.spawn({
let stat_counter = stat_counter.clone();
let change_counter = change_counter.clone();
let lines_counter = lines_counter.clone();
let tx_stats = tx_stats.clone();
let mut repo = repo.clone();
repo.object_cache_size_if_unset((object_cache_size_mb * 1024 * 1024) / threads);
let rx = rx.clone();
move || -> anyhow::Result<()> {
let mut rewrite_cache =
repo.diff_resource_cache(gix::diff::blob::pipeline::Mode::ToGit, Default::default())?;
let mut diff_cache = rewrite_cache.clone();
for (chunk_id, chunk) in rx {
let mut out_chunk = Vec::with_capacity(chunk.len());
for Task {
parent_commit,
commit,
compute_stats,
} in chunk
{
stat_counter.fetch_add(1, Ordering::SeqCst);
if gix::interrupt::is_triggered() {
return Ok(());
}
let mut out = Vec::new();
if compute_stats {
let from = match parent_commit {
Some(id) => {
match repo.find_object(id).ok().and_then(|c| c.peel_to_tree().ok()) {
Some(tree) => tree,
None => continue,
}
}
None => repo.empty_tree(),
};
let to = match repo.find_object(commit).ok().and_then(|c| c.peel_to_tree().ok())
{
Some(c) => c,
None => continue,
};
rewrite_cache.clear_resource_cache_keep_allocation();
diff_cache.clear_resource_cache_keep_allocation();
from.changes()?
.options(|opts| {
opts.track_path().track_rewrites(Some(rewrites));
})
.for_each_to_obtain_tree_with_cache(&to, &mut rewrite_cache, |change| {
use gix::object::tree::diff::Change::*;
change_counter.fetch_add(1, Ordering::SeqCst);
match change {
Addition {
entry_mode,
id,
location,
..
} => {
if entry_mode.is_blob_or_symlink() {
add_lines(&mut out, location, &lines_counter, id);
}
}
Modification {
entry_mode,
previous_entry_mode,
id,
previous_id,
location,
} => match (previous_entry_mode.is_blob(), entry_mode.is_blob()) {
(false, false) => {}
(false, true) => {
add_lines(&mut out, location, &lines_counter, id);
}
(true, false) => {
add_lines(&mut out, location, &lines_counter, previous_id);
}
(true, true) => {
if let Ok(cache) =
change.diff(&mut diff_cache).map(|p| p.resource_cache)
{
cache
.options
.skip_internal_diff_if_external_is_configured =
false;
if let Ok(prep) = cache.prepare_diff() {
let mut nl = 0;
let tokens = prep.interned_input();
match prep.operation {
Operation::InternalDiff { algorithm } => {
let diff = gix::diff::blob::Diff::compute(
algorithm, &tokens,
);
let added = diff.count_additions() as usize;
let removed =
diff.count_removals() as usize;
nl += added + removed;
let lines = LineStats {
added,
removed,
before: tokens.before.len(),
after: tokens.after.len(),
};
lines_counter
.fetch_add(nl, Ordering::SeqCst);
out.push(FileChange {
relpath: location.to_owned(),
mode: FileMode::Modified,
source_relpath: None,
lines: Some(lines),
});
}
Operation::ExternalCommand { .. } => {
unreachable!("disabled above")
}
Operation::SourceOrDestinationIsBinary => {}
}
}
}
}
},
Deletion {
entry_mode,
id,
location,
..
} => {
if entry_mode.is_blob_or_symlink() {
remove_lines(&mut out, location, &lines_counter, id);
}
}
Rewrite {
source_location,
diff,
copy,
location,
..
} => {
out.push(FileChange {
relpath: location.to_owned(),
source_relpath: Some(source_location.to_owned()),
mode: if copy { FileMode::Copy } else { FileMode::Rename },
lines: diff.map(|d| LineStats {
added: d.insertions as usize,
removed: d.removals as usize,
before: d.before,
after: d.after,
}),
});
}
}
Ok::<_, Infallible>(std::ops::ControlFlow::Continue(()))
})?;
out_chunk.push(CommitDiffStats {
id: commit,
changes: out,
});
} else {
out_chunk.push(CommitDiffStats {
id: commit,
changes: Vec::new(),
});
}
}
if tx_stats.send(Ok((chunk_id, out_chunk))).is_err() {
bail!("Thread failed to send result");
}
}
Ok(())
}
})
})
.collect::<Vec<_>>();
(tx, stat_workers)
};
drop(tx_stats);
#[derive(Clone)]
struct Db<'a, Find: Clone> {
inner: &'a Find,
progress: &'a dyn gix::progress::Count,
chunk: std::cell::RefCell<Vec<Task>>,
chunk_id: std::cell::RefCell<SequenceId>,
chunk_size: usize,
tx: crossbeam_channel::Sender<Packet>,
known_commits: &'a [gix::ObjectId],
}
impl<'a, Find> Db<'a, Find>
where
Find: gix::prelude::Find + Clone,
{
fn new(
inner: &'a Find,
progress: &'a dyn gix::progress::Count,
chunk_size: usize,
tx: crossbeam_channel::Sender<Packet>,
known_commits: &'a [gix::ObjectId],
) -> Self {
Self {
inner,
progress,
known_commits,
tx,
chunk_size,
chunk_id: 0.into(),
chunk: RefCell::new(Vec::with_capacity(chunk_size)),
}
}
fn send_last_chunk(self) {
self.tx.send((self.chunk_id.into_inner(), self.chunk.into_inner())).ok();
}
}
impl<Find> gix::prelude::Find for Db<'_, Find>
where
Find: gix::prelude::Find + Clone,
{
fn try_find<'b>(&self, id: &gix::oid, buf: &'b mut Vec<u8>) -> Result<Option<gix::objs::Data<'b>>, Error> {
let obj = self.inner.try_find(id, buf)?;
let Some(obj) = obj else { return Ok(None) };
if !obj.kind.is_commit() {
return Ok(None);
}
self.progress.inc();
if self.known_commits.binary_search(&id.to_owned()).is_err() {
let res = {
let mut parents = gix::objs::CommitRefIter::from_bytes(obj.data).parent_ids();
let res = parents.next().map(|first_parent| (Some(first_parent), id.to_owned()));
match parents.next() {
Some(_) => None,
None => res,
}
};
if let Some((first_parent, commit)) = res {
self.chunk.borrow_mut().push(Task {
parent_commit: first_parent,
commit,
compute_stats: true,
});
} else {
self.chunk.borrow_mut().push(Task {
parent_commit: None,
commit: id.to_owned(),
compute_stats: false,
});
}
if self.chunk.borrow().len() == self.chunk_size {
self.tx
.send((
*self.chunk_id.borrow(),
std::mem::replace(&mut self.chunk.borrow_mut(), Vec::with_capacity(self.chunk_size)),
))
.ok();
*self.chunk_id.borrow_mut() += 1;
}
}
Ok(Some(obj))
}
}
let db = Db::new(&repo.objects, &traverse_progress, 50, tx_tree_ids, &known_commits);
let commit_iter = gix::interrupt::Iter::new(commit_id.ancestors(&db), || anyhow!("Cancelled by user"));
let mut commits = Vec::new();
for c in commit_iter {
match c?.map(|c| c.id) {
Ok(c) => {
if known_commits.binary_search(&c).is_err() {
commits.push(c);
} else {
break;
}
}
Err(gix::traverse::commit::simple::Error::Find { .. }) => {
writeln!(err, "shallow repository - commit history is truncated").ok();
break;
}
Err(err) => return Err(err.into()),
}
}
db.send_last_chunk();
let saw_new_commits = !commits.is_empty();
if saw_new_commits {
traverse_progress.show_throughput(start);
}
drop(traverse_progress);
let stat_max = Some(commits.len());
stat_progress.set_max(stat_max);
db_progress.set_max(stat_max);
for handle in stat_threads {
handle.join().expect("no panic")?;
if gix::interrupt::is_triggered() {
bail!("Cancelled by user");
}
}
if saw_new_commits {
stat_progress.show_throughput(start);
change_progress.show_throughput(start);
lines_progress.show_throughput(start);
}
db_thread.join().expect("no panic")?;
if saw_new_commits {
db_progress.show_throughput(start);
} else {
db_progress.info("up to date".into());
}
commits.extend(all_commits);
Ok(commits)
})?;
Ok(out)
}
fn add_lines(out: &mut Vec<FileChange>, path: &BStr, lines_counter: &AtomicUsize, id: gix::Id<'_>) {
if let Ok(blob) = id.object() {
let nl = blob.data.lines_with_terminator().count();
let mut lines = LineStats::default();
lines.added += nl;
lines.after = nl;
lines_counter.fetch_add(nl, Ordering::SeqCst);
out.push(FileChange {
relpath: path.to_owned(),
mode: FileMode::Added,
source_relpath: None,
lines: Some(lines),
});
}
}
fn remove_lines(out: &mut Vec<FileChange>, path: &BStr, lines_counter: &AtomicUsize, id: gix::Id<'_>) {
if let Ok(blob) = id.object() {
let mut lines = LineStats::default();
let nl = blob.data.lines_with_terminator().count();
lines.removed += nl;
lines.before = nl;
lines_counter.fetch_add(nl, Ordering::SeqCst);
out.push(FileChange {
relpath: path.to_owned(),
mode: FileMode::Removed,
source_relpath: None,
lines: Some(lines),
});
}
}
#[derive(Debug, Copy, Clone)]
pub enum FileMode {
Added = 1,
Removed = 2,
Modified = 3,
Rename = 4,
Copy = 5,
}
impl FileMode {
pub fn as_str(&self) -> &'static str {
use FileMode::*;
match self {
Added => "+",
Removed => "-",
Modified => "Δ",
Rename => "➡",
Copy => "⏸",
}
}
pub fn from_usize(mode: usize) -> Option<Self> {
use FileMode::*;
match mode {
1 => Added,
2 => Removed,
3 => Modified,
4 => Rename,
5 => Copy,
_ => return None,
}
.into()
}
}
#[derive(Debug)]
struct FileChange {
relpath: BString,
mode: FileMode,
source_relpath: Option<BString>,
lines: Option<LineStats>,
}
/// Line statistics for a particular commit.
#[derive(Debug, Default, Copy, Clone)]
struct LineStats {
/// amount of added lines
added: usize,
/// amount of removed lines
removed: usize,
/// the amount of lines before the change.
before: usize,
/// the amount of lines after the change.
after: usize,
}
struct Updates<'a> {
new_commit: Statement<'a>,
insert_commit_file: Statement<'a>,
insert_commit_file_with_source: Statement<'a>,
insert_file_path: Statement<'a>,
}
impl<'a> Updates<'a> {
fn new(trans: &'a Transaction<'_>) -> rusqlite::Result<Self> {
let new_commit = trans.prepare(
r#"INSERT INTO
commits(hash)
VALUES(?)"#,
)?;
let insert_commit_file = trans.prepare(
r#"
INSERT INTO
commit_file(hash, file_id, has_diff, lines_added, lines_removed, lines_before, lines_after, mode)
VALUES(?, (SELECT files.file_id FROM files WHERE files.file_path = ?), ?, ?, ?, ?, ?, ?)
"#,
)?;
let insert_commit_file_with_source = trans.prepare(
r#"
INSERT INTO
commit_file(hash, file_id, has_diff, lines_added, lines_removed, lines_before, lines_after, mode, source_file_id)
VALUES(?, (SELECT files.file_id FROM files WHERE files.file_path = ?), ?, ?, ?, ?, ?, ?, (SELECT files.file_id FROM files WHERE files.file_path = ?))
"#,
)?;
let insert_file_path = trans.prepare(
r#"
INSERT OR IGNORE INTO
files(file_path)
VALUES(?)
"#,
)?;
Ok(Updates {
new_commit,
insert_commit_file,
insert_commit_file_with_source,
insert_file_path,
})
}
}