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