diffcore-rename: simplify and accelerate register_rename_src()
[git] / diffcore-rename.c
1 /*
2  *
3  * Copyright (C) 2005 Junio C Hamano
4  */
5 #include "cache.h"
6 #include "diff.h"
7 #include "diffcore.h"
8 #include "object-store.h"
9 #include "hashmap.h"
10 #include "progress.h"
11 #include "promisor-remote.h"
12
13 /* Table of rename/copy destinations */
14
15 static struct diff_rename_dst {
16         struct diff_filespec *two;
17         struct diff_filepair *pair;
18 } *rename_dst;
19 static int rename_dst_nr, rename_dst_alloc;
20
21 static int find_rename_dst(struct diff_filespec *two)
22 {
23         int first, last;
24
25         first = 0;
26         last = rename_dst_nr;
27         while (last > first) {
28                 int next = first + ((last - first) >> 1);
29                 struct diff_rename_dst *dst = &(rename_dst[next]);
30                 int cmp = strcmp(two->path, dst->two->path);
31                 if (!cmp)
32                         return next;
33                 if (cmp < 0) {
34                         last = next;
35                         continue;
36                 }
37                 first = next+1;
38         }
39         return -first - 1;
40 }
41
42 static struct diff_rename_dst *locate_rename_dst(struct diff_filespec *two)
43 {
44         int ofs = find_rename_dst(two);
45         return ofs < 0 ? NULL : &rename_dst[ofs];
46 }
47
48 /*
49  * Returns 0 on success, -1 if we found a duplicate.
50  */
51 static int add_rename_dst(struct diff_filespec *two)
52 {
53         int first = find_rename_dst(two);
54
55         if (first >= 0)
56                 return -1;
57         first = -first - 1;
58
59         /* insert to make it at "first" */
60         ALLOC_GROW(rename_dst, rename_dst_nr + 1, rename_dst_alloc);
61         rename_dst_nr++;
62         if (first < rename_dst_nr)
63                 MOVE_ARRAY(rename_dst + first + 1, rename_dst + first,
64                            rename_dst_nr - first - 1);
65         rename_dst[first].two = alloc_filespec(two->path);
66         fill_filespec(rename_dst[first].two, &two->oid, two->oid_valid,
67                       two->mode);
68         rename_dst[first].pair = NULL;
69         return 0;
70 }
71
72 /* Table of rename/copy src files */
73 static struct diff_rename_src {
74         struct diff_filepair *p;
75         unsigned short score; /* to remember the break score */
76 } *rename_src;
77 static int rename_src_nr, rename_src_alloc;
78
79 static void register_rename_src(struct diff_filepair *p)
80 {
81         /*
82          * If we have multiple entries at the same path in the source tree
83          * (an invalid tree, to be sure), avoid using more more than one
84          * such entry in rename detection.  Once upon a time, doing so
85          * caused segfaults; see commit 25d5ea410f ("[PATCH] Redo
86          * rename/copy detection logic.", 2005-05-24).
87          */
88         if (rename_src_nr > 0 &&
89             !strcmp(rename_src[rename_src_nr-1].p->one->path, p->one->path))
90                 return;
91
92         ALLOC_GROW(rename_src, rename_src_nr + 1, rename_src_alloc);
93         rename_src[rename_src_nr].p = p;
94         rename_src[rename_src_nr].score = p->score;
95         rename_src_nr++;
96 }
97
98 static int basename_same(struct diff_filespec *src, struct diff_filespec *dst)
99 {
100         int src_len = strlen(src->path), dst_len = strlen(dst->path);
101         while (src_len && dst_len) {
102                 char c1 = src->path[--src_len];
103                 char c2 = dst->path[--dst_len];
104                 if (c1 != c2)
105                         return 0;
106                 if (c1 == '/')
107                         return 1;
108         }
109         return (!src_len || src->path[src_len - 1] == '/') &&
110                 (!dst_len || dst->path[dst_len - 1] == '/');
111 }
112
113 struct diff_score {
114         int src; /* index in rename_src */
115         int dst; /* index in rename_dst */
116         unsigned short score;
117         short name_score;
118 };
119
120 struct prefetch_options {
121         struct repository *repo;
122         int skip_unmodified;
123 };
124 static void prefetch(void *prefetch_options)
125 {
126         struct prefetch_options *options = prefetch_options;
127         int i;
128         struct oid_array to_fetch = OID_ARRAY_INIT;
129
130         for (i = 0; i < rename_dst_nr; i++) {
131                 if (rename_dst[i].pair)
132                         /*
133                          * The loop in diffcore_rename() will not need these
134                          * blobs, so skip prefetching.
135                          */
136                         continue; /* already found exact match */
137                 diff_add_if_missing(options->repo, &to_fetch,
138                                     rename_dst[i].two);
139         }
140         for (i = 0; i < rename_src_nr; i++) {
141                 if (options->skip_unmodified &&
142                     diff_unmodified_pair(rename_src[i].p))
143                         /*
144                          * The loop in diffcore_rename() will not need these
145                          * blobs, so skip prefetching.
146                          */
147                         continue;
148                 diff_add_if_missing(options->repo, &to_fetch,
149                                     rename_src[i].p->one);
150         }
151         promisor_remote_get_direct(options->repo, to_fetch.oid, to_fetch.nr);
152         oid_array_clear(&to_fetch);
153 }
154
155 static int estimate_similarity(struct repository *r,
156                                struct diff_filespec *src,
157                                struct diff_filespec *dst,
158                                int minimum_score,
159                                int skip_unmodified)
160 {
161         /* src points at a file that existed in the original tree (or
162          * optionally a file in the destination tree) and dst points
163          * at a newly created file.  They may be quite similar, in which
164          * case we want to say src is renamed to dst or src is copied into
165          * dst, and then some edit has been applied to dst.
166          *
167          * Compare them and return how similar they are, representing
168          * the score as an integer between 0 and MAX_SCORE.
169          *
170          * When there is an exact match, it is considered a better
171          * match than anything else; the destination does not even
172          * call into this function in that case.
173          */
174         unsigned long max_size, delta_size, base_size, src_copied, literal_added;
175         int score;
176         struct diff_populate_filespec_options dpf_options = {
177                 .check_size_only = 1
178         };
179         struct prefetch_options prefetch_options = {r, skip_unmodified};
180
181         if (r == the_repository && has_promisor_remote()) {
182                 dpf_options.missing_object_cb = prefetch;
183                 dpf_options.missing_object_data = &prefetch_options;
184         }
185
186         /* We deal only with regular files.  Symlink renames are handled
187          * only when they are exact matches --- in other words, no edits
188          * after renaming.
189          */
190         if (!S_ISREG(src->mode) || !S_ISREG(dst->mode))
191                 return 0;
192
193         /*
194          * Need to check that source and destination sizes are
195          * filled in before comparing them.
196          *
197          * If we already have "cnt_data" filled in, we know it's
198          * all good (avoid checking the size for zero, as that
199          * is a possible size - we really should have a flag to
200          * say whether the size is valid or not!)
201          */
202         if (!src->cnt_data &&
203             diff_populate_filespec(r, src, &dpf_options))
204                 return 0;
205         if (!dst->cnt_data &&
206             diff_populate_filespec(r, dst, &dpf_options))
207                 return 0;
208
209         max_size = ((src->size > dst->size) ? src->size : dst->size);
210         base_size = ((src->size < dst->size) ? src->size : dst->size);
211         delta_size = max_size - base_size;
212
213         /* We would not consider edits that change the file size so
214          * drastically.  delta_size must be smaller than
215          * (MAX_SCORE-minimum_score)/MAX_SCORE * min(src->size, dst->size).
216          *
217          * Note that base_size == 0 case is handled here already
218          * and the final score computation below would not have a
219          * divide-by-zero issue.
220          */
221         if (max_size * (MAX_SCORE-minimum_score) < delta_size * MAX_SCORE)
222                 return 0;
223
224         dpf_options.check_size_only = 0;
225
226         if (!src->cnt_data && diff_populate_filespec(r, src, &dpf_options))
227                 return 0;
228         if (!dst->cnt_data && diff_populate_filespec(r, dst, &dpf_options))
229                 return 0;
230
231         if (diffcore_count_changes(r, src, dst,
232                                    &src->cnt_data, &dst->cnt_data,
233                                    &src_copied, &literal_added))
234                 return 0;
235
236         /* How similar are they?
237          * what percentage of material in dst are from source?
238          */
239         if (!dst->size)
240                 score = 0; /* should not happen */
241         else
242                 score = (int)(src_copied * MAX_SCORE / max_size);
243         return score;
244 }
245
246 static void record_rename_pair(int dst_index, int src_index, int score)
247 {
248         struct diff_filespec *src, *dst;
249         struct diff_filepair *dp;
250
251         if (rename_dst[dst_index].pair)
252                 die("internal error: dst already matched.");
253
254         src = rename_src[src_index].p->one;
255         src->rename_used++;
256         src->count++;
257
258         dst = rename_dst[dst_index].two;
259         dst->count++;
260
261         dp = diff_queue(NULL, src, dst);
262         dp->renamed_pair = 1;
263         if (!strcmp(src->path, dst->path))
264                 dp->score = rename_src[src_index].score;
265         else
266                 dp->score = score;
267         rename_dst[dst_index].pair = dp;
268 }
269
270 /*
271  * We sort the rename similarity matrix with the score, in descending
272  * order (the most similar first).
273  */
274 static int score_compare(const void *a_, const void *b_)
275 {
276         const struct diff_score *a = a_, *b = b_;
277
278         /* sink the unused ones to the bottom */
279         if (a->dst < 0)
280                 return (0 <= b->dst);
281         else if (b->dst < 0)
282                 return -1;
283
284         if (a->score == b->score)
285                 return b->name_score - a->name_score;
286
287         return b->score - a->score;
288 }
289
290 struct file_similarity {
291         struct hashmap_entry entry;
292         int index;
293         struct diff_filespec *filespec;
294 };
295
296 static unsigned int hash_filespec(struct repository *r,
297                                   struct diff_filespec *filespec)
298 {
299         if (!filespec->oid_valid) {
300                 if (diff_populate_filespec(r, filespec, NULL))
301                         return 0;
302                 hash_object_file(r->hash_algo, filespec->data, filespec->size,
303                                  "blob", &filespec->oid);
304         }
305         return oidhash(&filespec->oid);
306 }
307
308 static int find_identical_files(struct hashmap *srcs,
309                                 int dst_index,
310                                 struct diff_options *options)
311 {
312         int renames = 0;
313         struct diff_filespec *target = rename_dst[dst_index].two;
314         struct file_similarity *p, *best = NULL;
315         int i = 100, best_score = -1;
316         unsigned int hash = hash_filespec(options->repo, target);
317
318         /*
319          * Find the best source match for specified destination.
320          */
321         p = hashmap_get_entry_from_hash(srcs, hash, NULL,
322                                         struct file_similarity, entry);
323         hashmap_for_each_entry_from(srcs, p, entry) {
324                 int score;
325                 struct diff_filespec *source = p->filespec;
326
327                 /* False hash collision? */
328                 if (!oideq(&source->oid, &target->oid))
329                         continue;
330                 /* Non-regular files? If so, the modes must match! */
331                 if (!S_ISREG(source->mode) || !S_ISREG(target->mode)) {
332                         if (source->mode != target->mode)
333                                 continue;
334                 }
335                 /* Give higher scores to sources that haven't been used already */
336                 score = !source->rename_used;
337                 if (source->rename_used && options->detect_rename != DIFF_DETECT_COPY)
338                         continue;
339                 score += basename_same(source, target);
340                 if (score > best_score) {
341                         best = p;
342                         best_score = score;
343                         if (score == 2)
344                                 break;
345                 }
346
347                 /* Too many identical alternatives? Pick one */
348                 if (!--i)
349                         break;
350         }
351         if (best) {
352                 record_rename_pair(dst_index, best->index, MAX_SCORE);
353                 renames++;
354         }
355         return renames;
356 }
357
358 static void insert_file_table(struct repository *r,
359                               struct hashmap *table, int index,
360                               struct diff_filespec *filespec)
361 {
362         struct file_similarity *entry = xmalloc(sizeof(*entry));
363
364         entry->index = index;
365         entry->filespec = filespec;
366
367         hashmap_entry_init(&entry->entry, hash_filespec(r, filespec));
368         hashmap_add(table, &entry->entry);
369 }
370
371 /*
372  * Find exact renames first.
373  *
374  * The first round matches up the up-to-date entries,
375  * and then during the second round we try to match
376  * cache-dirty entries as well.
377  */
378 static int find_exact_renames(struct diff_options *options)
379 {
380         int i, renames = 0;
381         struct hashmap file_table;
382
383         /* Add all sources to the hash table in reverse order, because
384          * later on they will be retrieved in LIFO order.
385          */
386         hashmap_init(&file_table, NULL, NULL, rename_src_nr);
387         for (i = rename_src_nr-1; i >= 0; i--)
388                 insert_file_table(options->repo,
389                                   &file_table, i,
390                                   rename_src[i].p->one);
391
392         /* Walk the destinations and find best source match */
393         for (i = 0; i < rename_dst_nr; i++)
394                 renames += find_identical_files(&file_table, i, options);
395
396         /* Free the hash data structure and entries */
397         hashmap_clear_and_free(&file_table, struct file_similarity, entry);
398
399         return renames;
400 }
401
402 #define NUM_CANDIDATE_PER_DST 4
403 static void record_if_better(struct diff_score m[], struct diff_score *o)
404 {
405         int i, worst;
406
407         /* find the worst one */
408         worst = 0;
409         for (i = 1; i < NUM_CANDIDATE_PER_DST; i++)
410                 if (score_compare(&m[i], &m[worst]) > 0)
411                         worst = i;
412
413         /* is it better than the worst one? */
414         if (score_compare(&m[worst], o) > 0)
415                 m[worst] = *o;
416 }
417
418 /*
419  * Returns:
420  * 0 if we are under the limit;
421  * 1 if we need to disable inexact rename detection;
422  * 2 if we would be under the limit if we were given -C instead of -C -C.
423  */
424 static int too_many_rename_candidates(int num_destinations, int num_sources,
425                                       struct diff_options *options)
426 {
427         int rename_limit = options->rename_limit;
428         int i, limited_sources;
429
430         options->needed_rename_limit = 0;
431
432         /*
433          * This basically does a test for the rename matrix not
434          * growing larger than a "rename_limit" square matrix, ie:
435          *
436          *    num_destinations * num_sources > rename_limit * rename_limit
437          *
438          * We use st_mult() to check overflow conditions; in the
439          * exceptional circumstance that size_t isn't large enough to hold
440          * the multiplication, the system won't be able to allocate enough
441          * memory for the matrix anyway.
442          */
443         if (rename_limit <= 0)
444                 rename_limit = 32767;
445         if (st_mult(num_destinations, num_sources)
446             <= st_mult(rename_limit, rename_limit))
447                 return 0;
448
449         options->needed_rename_limit =
450                 num_sources > num_destinations ? num_sources : num_destinations;
451
452         /* Are we running under -C -C? */
453         if (!options->flags.find_copies_harder)
454                 return 1;
455
456         /* Would we bust the limit if we were running under -C? */
457         for (limited_sources = i = 0; i < num_sources; i++) {
458                 if (diff_unmodified_pair(rename_src[i].p))
459                         continue;
460                 limited_sources++;
461         }
462         if (st_mult(num_destinations, limited_sources)
463             <= st_mult(rename_limit, rename_limit))
464                 return 2;
465         return 1;
466 }
467
468 static int find_renames(struct diff_score *mx, int dst_cnt, int minimum_score, int copies)
469 {
470         int count = 0, i;
471
472         for (i = 0; i < dst_cnt * NUM_CANDIDATE_PER_DST; i++) {
473                 struct diff_rename_dst *dst;
474
475                 if ((mx[i].dst < 0) ||
476                     (mx[i].score < minimum_score))
477                         break; /* there is no more usable pair. */
478                 dst = &rename_dst[mx[i].dst];
479                 if (dst->pair)
480                         continue; /* already done, either exact or fuzzy. */
481                 if (!copies && rename_src[mx[i].src].p->one->rename_used)
482                         continue;
483                 record_rename_pair(mx[i].dst, mx[i].src, mx[i].score);
484                 count++;
485         }
486         return count;
487 }
488
489 void diffcore_rename(struct diff_options *options)
490 {
491         int detect_rename = options->detect_rename;
492         int minimum_score = options->rename_score;
493         struct diff_queue_struct *q = &diff_queued_diff;
494         struct diff_queue_struct outq;
495         struct diff_score *mx;
496         int i, j, rename_count, skip_unmodified = 0;
497         int num_destinations, dst_cnt;
498         struct progress *progress = NULL;
499
500         if (!minimum_score)
501                 minimum_score = DEFAULT_RENAME_SCORE;
502
503         for (i = 0; i < q->nr; i++) {
504                 struct diff_filepair *p = q->queue[i];
505                 if (!DIFF_FILE_VALID(p->one)) {
506                         if (!DIFF_FILE_VALID(p->two))
507                                 continue; /* unmerged */
508                         else if (options->single_follow &&
509                                  strcmp(options->single_follow, p->two->path))
510                                 continue; /* not interested */
511                         else if (!options->flags.rename_empty &&
512                                  is_empty_blob_oid(&p->two->oid))
513                                 continue;
514                         else if (add_rename_dst(p->two) < 0) {
515                                 warning("skipping rename detection, detected"
516                                         " duplicate destination '%s'",
517                                         p->two->path);
518                                 goto cleanup;
519                         }
520                 }
521                 else if (!options->flags.rename_empty &&
522                          is_empty_blob_oid(&p->one->oid))
523                         continue;
524                 else if (!DIFF_PAIR_UNMERGED(p) && !DIFF_FILE_VALID(p->two)) {
525                         /*
526                          * If the source is a broken "delete", and
527                          * they did not really want to get broken,
528                          * that means the source actually stays.
529                          * So we increment the "rename_used" score
530                          * by one, to indicate ourselves as a user
531                          */
532                         if (p->broken_pair && !p->score)
533                                 p->one->rename_used++;
534                         register_rename_src(p);
535                 }
536                 else if (detect_rename == DIFF_DETECT_COPY) {
537                         /*
538                          * Increment the "rename_used" score by
539                          * one, to indicate ourselves as a user.
540                          */
541                         p->one->rename_used++;
542                         register_rename_src(p);
543                 }
544         }
545         if (rename_dst_nr == 0 || rename_src_nr == 0)
546                 goto cleanup; /* nothing to do */
547
548         /*
549          * We really want to cull the candidates list early
550          * with cheap tests in order to avoid doing deltas.
551          */
552         rename_count = find_exact_renames(options);
553
554         /* Did we only want exact renames? */
555         if (minimum_score == MAX_SCORE)
556                 goto cleanup;
557
558         /*
559          * Calculate how many renames are left (but all the source
560          * files still remain as options for rename/copies!)
561          */
562         num_destinations = (rename_dst_nr - rename_count);
563
564         /* All done? */
565         if (!num_destinations)
566                 goto cleanup;
567
568         switch (too_many_rename_candidates(num_destinations, rename_src_nr,
569                                            options)) {
570         case 1:
571                 goto cleanup;
572         case 2:
573                 options->degraded_cc_to_c = 1;
574                 skip_unmodified = 1;
575                 break;
576         default:
577                 break;
578         }
579
580         if (options->show_rename_progress) {
581                 progress = start_delayed_progress(
582                                 _("Performing inexact rename detection"),
583                                 (uint64_t)num_destinations * (uint64_t)rename_src_nr);
584         }
585
586         mx = xcalloc(st_mult(NUM_CANDIDATE_PER_DST, num_destinations),
587                      sizeof(*mx));
588         for (dst_cnt = i = 0; i < rename_dst_nr; i++) {
589                 struct diff_filespec *two = rename_dst[i].two;
590                 struct diff_score *m;
591
592                 if (rename_dst[i].pair)
593                         continue; /* dealt with exact match already. */
594
595                 m = &mx[dst_cnt * NUM_CANDIDATE_PER_DST];
596                 for (j = 0; j < NUM_CANDIDATE_PER_DST; j++)
597                         m[j].dst = -1;
598
599                 for (j = 0; j < rename_src_nr; j++) {
600                         struct diff_filespec *one = rename_src[j].p->one;
601                         struct diff_score this_src;
602
603                         if (skip_unmodified &&
604                             diff_unmodified_pair(rename_src[j].p))
605                                 continue;
606
607                         this_src.score = estimate_similarity(options->repo,
608                                                              one, two,
609                                                              minimum_score,
610                                                              skip_unmodified);
611                         this_src.name_score = basename_same(one, two);
612                         this_src.dst = i;
613                         this_src.src = j;
614                         record_if_better(m, &this_src);
615                         /*
616                          * Once we run estimate_similarity,
617                          * We do not need the text anymore.
618                          */
619                         diff_free_filespec_blob(one);
620                         diff_free_filespec_blob(two);
621                 }
622                 dst_cnt++;
623                 display_progress(progress,
624                                  (uint64_t)dst_cnt * (uint64_t)rename_src_nr);
625         }
626         stop_progress(&progress);
627
628         /* cost matrix sorted by most to least similar pair */
629         STABLE_QSORT(mx, dst_cnt * NUM_CANDIDATE_PER_DST, score_compare);
630
631         rename_count += find_renames(mx, dst_cnt, minimum_score, 0);
632         if (detect_rename == DIFF_DETECT_COPY)
633                 rename_count += find_renames(mx, dst_cnt, minimum_score, 1);
634         free(mx);
635
636  cleanup:
637         /* At this point, we have found some renames and copies and they
638          * are recorded in rename_dst.  The original list is still in *q.
639          */
640         DIFF_QUEUE_CLEAR(&outq);
641         for (i = 0; i < q->nr; i++) {
642                 struct diff_filepair *p = q->queue[i];
643                 struct diff_filepair *pair_to_free = NULL;
644
645                 if (DIFF_PAIR_UNMERGED(p)) {
646                         diff_q(&outq, p);
647                 }
648                 else if (!DIFF_FILE_VALID(p->one) && DIFF_FILE_VALID(p->two)) {
649                         /*
650                          * Creation
651                          *
652                          * We would output this create record if it has
653                          * not been turned into a rename/copy already.
654                          */
655                         struct diff_rename_dst *dst = locate_rename_dst(p->two);
656                         if (dst && dst->pair) {
657                                 diff_q(&outq, dst->pair);
658                                 pair_to_free = p;
659                         }
660                         else
661                                 /* no matching rename/copy source, so
662                                  * record this as a creation.
663                                  */
664                                 diff_q(&outq, p);
665                 }
666                 else if (DIFF_FILE_VALID(p->one) && !DIFF_FILE_VALID(p->two)) {
667                         /*
668                          * Deletion
669                          *
670                          * We would output this delete record if:
671                          *
672                          * (1) this is a broken delete and the counterpart
673                          *     broken create remains in the output; or
674                          * (2) this is not a broken delete, and rename_dst
675                          *     does not have a rename/copy to move p->one->path
676                          *     out of existence.
677                          *
678                          * Otherwise, the counterpart broken create
679                          * has been turned into a rename-edit; or
680                          * delete did not have a matching create to
681                          * begin with.
682                          */
683                         if (DIFF_PAIR_BROKEN(p)) {
684                                 /* broken delete */
685                                 struct diff_rename_dst *dst = locate_rename_dst(p->one);
686                                 if (dst && dst->pair)
687                                         /* counterpart is now rename/copy */
688                                         pair_to_free = p;
689                         }
690                         else {
691                                 if (p->one->rename_used)
692                                         /* this path remains */
693                                         pair_to_free = p;
694                         }
695
696                         if (pair_to_free)
697                                 ;
698                         else
699                                 diff_q(&outq, p);
700                 }
701                 else if (!diff_unmodified_pair(p))
702                         /* all the usual ones need to be kept */
703                         diff_q(&outq, p);
704                 else
705                         /* no need to keep unmodified pairs */
706                         pair_to_free = p;
707
708                 if (pair_to_free)
709                         diff_free_filepair(pair_to_free);
710         }
711         diff_debug_queue("done copying original", &outq);
712
713         free(q->queue);
714         *q = outq;
715         diff_debug_queue("done collapsing", q);
716
717         for (i = 0; i < rename_dst_nr; i++)
718                 free_filespec(rename_dst[i].two);
719
720         FREE_AND_NULL(rename_dst);
721         rename_dst_nr = rename_dst_alloc = 0;
722         FREE_AND_NULL(rename_src);
723         rename_src_nr = rename_src_alloc = 0;
724         return;
725 }