Merge branch 'js/fsmonitor-unpack-fix'
[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 #include "strmap.h"
13
14 /* Table of rename/copy destinations */
15
16 static struct diff_rename_dst {
17         struct diff_filepair *p;
18         struct diff_filespec *filespec_to_free;
19         int is_rename; /* false -> just a create; true -> rename or copy */
20 } *rename_dst;
21 static int rename_dst_nr, rename_dst_alloc;
22 /* Mapping from break source pathname to break destination index */
23 static struct strintmap *break_idx = NULL;
24
25 static struct diff_rename_dst *locate_rename_dst(struct diff_filepair *p)
26 {
27         /* Lookup by p->ONE->path */
28         int idx = break_idx ? strintmap_get(break_idx, p->one->path) : -1;
29         return (idx == -1) ? NULL : &rename_dst[idx];
30 }
31
32 /*
33  * Returns 0 on success, -1 if we found a duplicate.
34  */
35 static int add_rename_dst(struct diff_filepair *p)
36 {
37         ALLOC_GROW(rename_dst, rename_dst_nr + 1, rename_dst_alloc);
38         rename_dst[rename_dst_nr].p = p;
39         rename_dst[rename_dst_nr].filespec_to_free = NULL;
40         rename_dst[rename_dst_nr].is_rename = 0;
41         rename_dst_nr++;
42         return 0;
43 }
44
45 /* Table of rename/copy src files */
46 static struct diff_rename_src {
47         struct diff_filepair *p;
48         unsigned short score; /* to remember the break score */
49 } *rename_src;
50 static int rename_src_nr, rename_src_alloc;
51
52 static void register_rename_src(struct diff_filepair *p)
53 {
54         if (p->broken_pair) {
55                 if (!break_idx) {
56                         break_idx = xmalloc(sizeof(*break_idx));
57                         strintmap_init(break_idx, -1);
58                 }
59                 strintmap_set(break_idx, p->one->path, rename_dst_nr);
60         }
61
62         ALLOC_GROW(rename_src, rename_src_nr + 1, rename_src_alloc);
63         rename_src[rename_src_nr].p = p;
64         rename_src[rename_src_nr].score = p->score;
65         rename_src_nr++;
66 }
67
68 static int basename_same(struct diff_filespec *src, struct diff_filespec *dst)
69 {
70         int src_len = strlen(src->path), dst_len = strlen(dst->path);
71         while (src_len && dst_len) {
72                 char c1 = src->path[--src_len];
73                 char c2 = dst->path[--dst_len];
74                 if (c1 != c2)
75                         return 0;
76                 if (c1 == '/')
77                         return 1;
78         }
79         return (!src_len || src->path[src_len - 1] == '/') &&
80                 (!dst_len || dst->path[dst_len - 1] == '/');
81 }
82
83 struct diff_score {
84         int src; /* index in rename_src */
85         int dst; /* index in rename_dst */
86         unsigned short score;
87         short name_score;
88 };
89
90 struct prefetch_options {
91         struct repository *repo;
92         int skip_unmodified;
93 };
94 static void prefetch(void *prefetch_options)
95 {
96         struct prefetch_options *options = prefetch_options;
97         int i;
98         struct oid_array to_fetch = OID_ARRAY_INIT;
99
100         for (i = 0; i < rename_dst_nr; i++) {
101                 if (rename_dst[i].p->renamed_pair)
102                         /*
103                          * The loop in diffcore_rename() will not need these
104                          * blobs, so skip prefetching.
105                          */
106                         continue; /* already found exact match */
107                 diff_add_if_missing(options->repo, &to_fetch,
108                                     rename_dst[i].p->two);
109         }
110         for (i = 0; i < rename_src_nr; i++) {
111                 if (options->skip_unmodified &&
112                     diff_unmodified_pair(rename_src[i].p))
113                         /*
114                          * The loop in diffcore_rename() will not need these
115                          * blobs, so skip prefetching.
116                          */
117                         continue;
118                 diff_add_if_missing(options->repo, &to_fetch,
119                                     rename_src[i].p->one);
120         }
121         promisor_remote_get_direct(options->repo, to_fetch.oid, to_fetch.nr);
122         oid_array_clear(&to_fetch);
123 }
124
125 static int estimate_similarity(struct repository *r,
126                                struct diff_filespec *src,
127                                struct diff_filespec *dst,
128                                int minimum_score,
129                                int skip_unmodified)
130 {
131         /* src points at a file that existed in the original tree (or
132          * optionally a file in the destination tree) and dst points
133          * at a newly created file.  They may be quite similar, in which
134          * case we want to say src is renamed to dst or src is copied into
135          * dst, and then some edit has been applied to dst.
136          *
137          * Compare them and return how similar they are, representing
138          * the score as an integer between 0 and MAX_SCORE.
139          *
140          * When there is an exact match, it is considered a better
141          * match than anything else; the destination does not even
142          * call into this function in that case.
143          */
144         unsigned long max_size, delta_size, base_size, src_copied, literal_added;
145         int score;
146         struct diff_populate_filespec_options dpf_options = {
147                 .check_size_only = 1
148         };
149         struct prefetch_options prefetch_options = {r, skip_unmodified};
150
151         if (r == the_repository && has_promisor_remote()) {
152                 dpf_options.missing_object_cb = prefetch;
153                 dpf_options.missing_object_data = &prefetch_options;
154         }
155
156         /* We deal only with regular files.  Symlink renames are handled
157          * only when they are exact matches --- in other words, no edits
158          * after renaming.
159          */
160         if (!S_ISREG(src->mode) || !S_ISREG(dst->mode))
161                 return 0;
162
163         /*
164          * Need to check that source and destination sizes are
165          * filled in before comparing them.
166          *
167          * If we already have "cnt_data" filled in, we know it's
168          * all good (avoid checking the size for zero, as that
169          * is a possible size - we really should have a flag to
170          * say whether the size is valid or not!)
171          */
172         if (!src->cnt_data &&
173             diff_populate_filespec(r, src, &dpf_options))
174                 return 0;
175         if (!dst->cnt_data &&
176             diff_populate_filespec(r, dst, &dpf_options))
177                 return 0;
178
179         max_size = ((src->size > dst->size) ? src->size : dst->size);
180         base_size = ((src->size < dst->size) ? src->size : dst->size);
181         delta_size = max_size - base_size;
182
183         /* We would not consider edits that change the file size so
184          * drastically.  delta_size must be smaller than
185          * (MAX_SCORE-minimum_score)/MAX_SCORE * min(src->size, dst->size).
186          *
187          * Note that base_size == 0 case is handled here already
188          * and the final score computation below would not have a
189          * divide-by-zero issue.
190          */
191         if (max_size * (MAX_SCORE-minimum_score) < delta_size * MAX_SCORE)
192                 return 0;
193
194         dpf_options.check_size_only = 0;
195
196         if (!src->cnt_data && diff_populate_filespec(r, src, &dpf_options))
197                 return 0;
198         if (!dst->cnt_data && diff_populate_filespec(r, dst, &dpf_options))
199                 return 0;
200
201         if (diffcore_count_changes(r, src, dst,
202                                    &src->cnt_data, &dst->cnt_data,
203                                    &src_copied, &literal_added))
204                 return 0;
205
206         /* How similar are they?
207          * what percentage of material in dst are from source?
208          */
209         if (!dst->size)
210                 score = 0; /* should not happen */
211         else
212                 score = (int)(src_copied * MAX_SCORE / max_size);
213         return score;
214 }
215
216 static void record_rename_pair(int dst_index, int src_index, int score)
217 {
218         struct diff_filepair *src = rename_src[src_index].p;
219         struct diff_filepair *dst = rename_dst[dst_index].p;
220
221         if (dst->renamed_pair)
222                 die("internal error: dst already matched.");
223
224         src->one->rename_used++;
225         src->one->count++;
226
227         rename_dst[dst_index].filespec_to_free = dst->one;
228         rename_dst[dst_index].is_rename = 1;
229
230         dst->one = src->one;
231         dst->renamed_pair = 1;
232         if (!strcmp(dst->one->path, dst->two->path))
233                 dst->score = rename_src[src_index].score;
234         else
235                 dst->score = score;
236 }
237
238 /*
239  * We sort the rename similarity matrix with the score, in descending
240  * order (the most similar first).
241  */
242 static int score_compare(const void *a_, const void *b_)
243 {
244         const struct diff_score *a = a_, *b = b_;
245
246         /* sink the unused ones to the bottom */
247         if (a->dst < 0)
248                 return (0 <= b->dst);
249         else if (b->dst < 0)
250                 return -1;
251
252         if (a->score == b->score)
253                 return b->name_score - a->name_score;
254
255         return b->score - a->score;
256 }
257
258 struct file_similarity {
259         struct hashmap_entry entry;
260         int index;
261         struct diff_filespec *filespec;
262 };
263
264 static unsigned int hash_filespec(struct repository *r,
265                                   struct diff_filespec *filespec)
266 {
267         if (!filespec->oid_valid) {
268                 if (diff_populate_filespec(r, filespec, NULL))
269                         return 0;
270                 hash_object_file(r->hash_algo, filespec->data, filespec->size,
271                                  "blob", &filespec->oid);
272         }
273         return oidhash(&filespec->oid);
274 }
275
276 static int find_identical_files(struct hashmap *srcs,
277                                 int dst_index,
278                                 struct diff_options *options)
279 {
280         int renames = 0;
281         struct diff_filespec *target = rename_dst[dst_index].p->two;
282         struct file_similarity *p, *best = NULL;
283         int i = 100, best_score = -1;
284         unsigned int hash = hash_filespec(options->repo, target);
285
286         /*
287          * Find the best source match for specified destination.
288          */
289         p = hashmap_get_entry_from_hash(srcs, hash, NULL,
290                                         struct file_similarity, entry);
291         hashmap_for_each_entry_from(srcs, p, entry) {
292                 int score;
293                 struct diff_filespec *source = p->filespec;
294
295                 /* False hash collision? */
296                 if (!oideq(&source->oid, &target->oid))
297                         continue;
298                 /* Non-regular files? If so, the modes must match! */
299                 if (!S_ISREG(source->mode) || !S_ISREG(target->mode)) {
300                         if (source->mode != target->mode)
301                                 continue;
302                 }
303                 /* Give higher scores to sources that haven't been used already */
304                 score = !source->rename_used;
305                 if (source->rename_used && options->detect_rename != DIFF_DETECT_COPY)
306                         continue;
307                 score += basename_same(source, target);
308                 if (score > best_score) {
309                         best = p;
310                         best_score = score;
311                         if (score == 2)
312                                 break;
313                 }
314
315                 /* Too many identical alternatives? Pick one */
316                 if (!--i)
317                         break;
318         }
319         if (best) {
320                 record_rename_pair(dst_index, best->index, MAX_SCORE);
321                 renames++;
322         }
323         return renames;
324 }
325
326 static void insert_file_table(struct repository *r,
327                               struct hashmap *table, int index,
328                               struct diff_filespec *filespec)
329 {
330         struct file_similarity *entry = xmalloc(sizeof(*entry));
331
332         entry->index = index;
333         entry->filespec = filespec;
334
335         hashmap_entry_init(&entry->entry, hash_filespec(r, filespec));
336         hashmap_add(table, &entry->entry);
337 }
338
339 /*
340  * Find exact renames first.
341  *
342  * The first round matches up the up-to-date entries,
343  * and then during the second round we try to match
344  * cache-dirty entries as well.
345  */
346 static int find_exact_renames(struct diff_options *options)
347 {
348         int i, renames = 0;
349         struct hashmap file_table;
350
351         /* Add all sources to the hash table in reverse order, because
352          * later on they will be retrieved in LIFO order.
353          */
354         hashmap_init(&file_table, NULL, NULL, rename_src_nr);
355         for (i = rename_src_nr-1; i >= 0; i--)
356                 insert_file_table(options->repo,
357                                   &file_table, i,
358                                   rename_src[i].p->one);
359
360         /* Walk the destinations and find best source match */
361         for (i = 0; i < rename_dst_nr; i++)
362                 renames += find_identical_files(&file_table, i, options);
363
364         /* Free the hash data structure and entries */
365         hashmap_clear_and_free(&file_table, struct file_similarity, entry);
366
367         return renames;
368 }
369
370 static const char *get_basename(const char *filename)
371 {
372         /*
373          * gitbasename() has to worry about special drives, multiple
374          * directory separator characters, trailing slashes, NULL or
375          * empty strings, etc.  We only work on filenames as stored in
376          * git, and thus get to ignore all those complications.
377          */
378         const char *base = strrchr(filename, '/');
379         return base ? base + 1 : filename;
380 }
381
382 static int find_basename_matches(struct diff_options *options,
383                                  int minimum_score)
384 {
385         /*
386          * When I checked in early 2020, over 76% of file renames in linux
387          * just moved files to a different directory but kept the same
388          * basename.  gcc did that with over 64% of renames, gecko did it
389          * with over 79%, and WebKit did it with over 89%.
390          *
391          * Therefore we can bypass the normal exhaustive NxM matrix
392          * comparison of similarities between all potential rename sources
393          * and destinations by instead using file basename as a hint (i.e.
394          * the portion of the filename after the last '/'), checking for
395          * similarity between files with the same basename, and if we find
396          * a pair that are sufficiently similar, record the rename pair and
397          * exclude those two from the NxM matrix.
398          *
399          * This *might* cause us to find a less than optimal pairing (if
400          * there is another file that we are even more similar to but has a
401          * different basename).  Given the huge performance advantage
402          * basename matching provides, and given the frequency with which
403          * people use the same basename in real world projects, that's a
404          * trade-off we are willing to accept when doing just rename
405          * detection.
406          *
407          * If someone wants copy detection that implies they are willing to
408          * spend more cycles to find similarities between files, so it may
409          * be less likely that this heuristic is wanted.  If someone is
410          * doing break detection, that means they do not want filename
411          * similarity to imply any form of content similiarity, and thus
412          * this heuristic would definitely be incompatible.
413          */
414
415         int i, renames = 0;
416         struct strintmap sources;
417         struct strintmap dests;
418         struct hashmap_iter iter;
419         struct strmap_entry *entry;
420
421         /*
422          * The prefeteching stuff wants to know if it can skip prefetching
423          * blobs that are unmodified...and will then do a little extra work
424          * to verify that the oids are indeed different before prefetching.
425          * Unmodified blobs are only relevant when doing copy detection;
426          * when limiting to rename detection, diffcore_rename[_extended]()
427          * will never be called with unmodified source paths fed to us, so
428          * the extra work necessary to check if rename_src entries are
429          * unmodified would be a small waste.
430          */
431         int skip_unmodified = 0;
432
433         /*
434          * Create maps of basename -> fullname(s) for remaining sources and
435          * dests.
436          */
437         strintmap_init_with_options(&sources, -1, NULL, 0);
438         strintmap_init_with_options(&dests, -1, NULL, 0);
439         for (i = 0; i < rename_src_nr; ++i) {
440                 char *filename = rename_src[i].p->one->path;
441                 const char *base;
442
443                 /* exact renames removed in remove_unneeded_paths_from_src() */
444                 assert(!rename_src[i].p->one->rename_used);
445
446                 /* Record index within rename_src (i) if basename is unique */
447                 base = get_basename(filename);
448                 if (strintmap_contains(&sources, base))
449                         strintmap_set(&sources, base, -1);
450                 else
451                         strintmap_set(&sources, base, i);
452         }
453         for (i = 0; i < rename_dst_nr; ++i) {
454                 char *filename = rename_dst[i].p->two->path;
455                 const char *base;
456
457                 if (rename_dst[i].is_rename)
458                         continue; /* involved in exact match already. */
459
460                 /* Record index within rename_dst (i) if basename is unique */
461                 base = get_basename(filename);
462                 if (strintmap_contains(&dests, base))
463                         strintmap_set(&dests, base, -1);
464                 else
465                         strintmap_set(&dests, base, i);
466         }
467
468         /* Now look for basename matchups and do similarity estimation */
469         strintmap_for_each_entry(&sources, &iter, entry) {
470                 const char *base = entry->key;
471                 intptr_t src_index = (intptr_t)entry->value;
472                 intptr_t dst_index;
473                 if (src_index == -1)
474                         continue;
475
476                 if (0 <= (dst_index = strintmap_get(&dests, base))) {
477                         struct diff_filespec *one, *two;
478                         int score;
479
480                         /* Estimate the similarity */
481                         one = rename_src[src_index].p->one;
482                         two = rename_dst[dst_index].p->two;
483                         score = estimate_similarity(options->repo, one, two,
484                                                     minimum_score, skip_unmodified);
485
486                         /* If sufficiently similar, record as rename pair */
487                         if (score < minimum_score)
488                                 continue;
489                         record_rename_pair(dst_index, src_index, score);
490                         renames++;
491
492                         /*
493                          * Found a rename so don't need text anymore; if we
494                          * didn't find a rename, the filespec_blob would get
495                          * re-used when doing the matrix of comparisons.
496                          */
497                         diff_free_filespec_blob(one);
498                         diff_free_filespec_blob(two);
499                 }
500         }
501
502         strintmap_clear(&sources);
503         strintmap_clear(&dests);
504
505         return renames;
506 }
507
508 #define NUM_CANDIDATE_PER_DST 4
509 static void record_if_better(struct diff_score m[], struct diff_score *o)
510 {
511         int i, worst;
512
513         /* find the worst one */
514         worst = 0;
515         for (i = 1; i < NUM_CANDIDATE_PER_DST; i++)
516                 if (score_compare(&m[i], &m[worst]) > 0)
517                         worst = i;
518
519         /* is it better than the worst one? */
520         if (score_compare(&m[worst], o) > 0)
521                 m[worst] = *o;
522 }
523
524 /*
525  * Returns:
526  * 0 if we are under the limit;
527  * 1 if we need to disable inexact rename detection;
528  * 2 if we would be under the limit if we were given -C instead of -C -C.
529  */
530 static int too_many_rename_candidates(int num_destinations, int num_sources,
531                                       struct diff_options *options)
532 {
533         int rename_limit = options->rename_limit;
534         int i, limited_sources;
535
536         options->needed_rename_limit = 0;
537
538         /*
539          * This basically does a test for the rename matrix not
540          * growing larger than a "rename_limit" square matrix, ie:
541          *
542          *    num_destinations * num_sources > rename_limit * rename_limit
543          *
544          * We use st_mult() to check overflow conditions; in the
545          * exceptional circumstance that size_t isn't large enough to hold
546          * the multiplication, the system won't be able to allocate enough
547          * memory for the matrix anyway.
548          */
549         if (rename_limit <= 0)
550                 rename_limit = 32767;
551         if (st_mult(num_destinations, num_sources)
552             <= st_mult(rename_limit, rename_limit))
553                 return 0;
554
555         options->needed_rename_limit =
556                 num_sources > num_destinations ? num_sources : num_destinations;
557
558         /* Are we running under -C -C? */
559         if (!options->flags.find_copies_harder)
560                 return 1;
561
562         /* Would we bust the limit if we were running under -C? */
563         for (limited_sources = i = 0; i < num_sources; i++) {
564                 if (diff_unmodified_pair(rename_src[i].p))
565                         continue;
566                 limited_sources++;
567         }
568         if (st_mult(num_destinations, limited_sources)
569             <= st_mult(rename_limit, rename_limit))
570                 return 2;
571         return 1;
572 }
573
574 static int find_renames(struct diff_score *mx, int dst_cnt, int minimum_score, int copies)
575 {
576         int count = 0, i;
577
578         for (i = 0; i < dst_cnt * NUM_CANDIDATE_PER_DST; i++) {
579                 struct diff_rename_dst *dst;
580
581                 if ((mx[i].dst < 0) ||
582                     (mx[i].score < minimum_score))
583                         break; /* there is no more usable pair. */
584                 dst = &rename_dst[mx[i].dst];
585                 if (dst->is_rename)
586                         continue; /* already done, either exact or fuzzy. */
587                 if (!copies && rename_src[mx[i].src].p->one->rename_used)
588                         continue;
589                 record_rename_pair(mx[i].dst, mx[i].src, mx[i].score);
590                 count++;
591         }
592         return count;
593 }
594
595 static void remove_unneeded_paths_from_src(int detecting_copies)
596 {
597         int i, new_num_src;
598
599         if (detecting_copies)
600                 return; /* nothing to remove */
601         if (break_idx)
602                 return; /* culling incompatible with break detection */
603
604         /*
605          * Note on reasons why we cull unneeded sources but not destinations:
606          *   1) Pairings are stored in rename_dst (not rename_src), which we
607          *      need to keep around.  So, we just can't cull rename_dst even
608          *      if we wanted to.  But doing so wouldn't help because...
609          *
610          *   2) There is a matrix pairwise comparison that follows the
611          *      "Performing inexact rename detection" progress message.
612          *      Iterating over the destinations is done in the outer loop,
613          *      hence we only iterate over each of those once and we can
614          *      easily skip the outer loop early if the destination isn't
615          *      relevant.  That's only one check per destination path to
616          *      skip.
617          *
618          *      By contrast, the sources are iterated in the inner loop; if
619          *      we check whether a source can be skipped, then we'll be
620          *      checking it N separate times, once for each destination.
621          *      We don't want to have to iterate over known-not-needed
622          *      sources N times each, so avoid that by removing the sources
623          *      from rename_src here.
624          */
625         for (i = 0, new_num_src = 0; i < rename_src_nr; i++) {
626                 /*
627                  * renames are stored in rename_dst, so if a rename has
628                  * already been detected using this source, we can just
629                  * remove the source knowing rename_dst has its info.
630                  */
631                 if (rename_src[i].p->one->rename_used)
632                         continue;
633
634                 if (new_num_src < i)
635                         memcpy(&rename_src[new_num_src], &rename_src[i],
636                                sizeof(struct diff_rename_src));
637                 new_num_src++;
638         }
639
640         rename_src_nr = new_num_src;
641 }
642
643 void diffcore_rename(struct diff_options *options)
644 {
645         int detect_rename = options->detect_rename;
646         int minimum_score = options->rename_score;
647         struct diff_queue_struct *q = &diff_queued_diff;
648         struct diff_queue_struct outq;
649         struct diff_score *mx;
650         int i, j, rename_count, skip_unmodified = 0;
651         int num_destinations, dst_cnt;
652         int num_sources, want_copies;
653         struct progress *progress = NULL;
654
655         trace2_region_enter("diff", "setup", options->repo);
656         want_copies = (detect_rename == DIFF_DETECT_COPY);
657         if (!minimum_score)
658                 minimum_score = DEFAULT_RENAME_SCORE;
659
660         for (i = 0; i < q->nr; i++) {
661                 struct diff_filepair *p = q->queue[i];
662                 if (!DIFF_FILE_VALID(p->one)) {
663                         if (!DIFF_FILE_VALID(p->two))
664                                 continue; /* unmerged */
665                         else if (options->single_follow &&
666                                  strcmp(options->single_follow, p->two->path))
667                                 continue; /* not interested */
668                         else if (!options->flags.rename_empty &&
669                                  is_empty_blob_oid(&p->two->oid))
670                                 continue;
671                         else if (add_rename_dst(p) < 0) {
672                                 warning("skipping rename detection, detected"
673                                         " duplicate destination '%s'",
674                                         p->two->path);
675                                 goto cleanup;
676                         }
677                 }
678                 else if (!options->flags.rename_empty &&
679                          is_empty_blob_oid(&p->one->oid))
680                         continue;
681                 else if (!DIFF_PAIR_UNMERGED(p) && !DIFF_FILE_VALID(p->two)) {
682                         /*
683                          * If the source is a broken "delete", and
684                          * they did not really want to get broken,
685                          * that means the source actually stays.
686                          * So we increment the "rename_used" score
687                          * by one, to indicate ourselves as a user
688                          */
689                         if (p->broken_pair && !p->score)
690                                 p->one->rename_used++;
691                         register_rename_src(p);
692                 }
693                 else if (want_copies) {
694                         /*
695                          * Increment the "rename_used" score by
696                          * one, to indicate ourselves as a user.
697                          */
698                         p->one->rename_used++;
699                         register_rename_src(p);
700                 }
701         }
702         trace2_region_leave("diff", "setup", options->repo);
703         if (rename_dst_nr == 0 || rename_src_nr == 0)
704                 goto cleanup; /* nothing to do */
705
706         trace2_region_enter("diff", "exact renames", options->repo);
707         /*
708          * We really want to cull the candidates list early
709          * with cheap tests in order to avoid doing deltas.
710          */
711         rename_count = find_exact_renames(options);
712         trace2_region_leave("diff", "exact renames", options->repo);
713
714         /* Did we only want exact renames? */
715         if (minimum_score == MAX_SCORE)
716                 goto cleanup;
717
718         num_sources = rename_src_nr;
719
720         if (want_copies || break_idx) {
721                 /*
722                  * Cull sources:
723                  *   - remove ones corresponding to exact renames
724                  */
725                 trace2_region_enter("diff", "cull after exact", options->repo);
726                 remove_unneeded_paths_from_src(want_copies);
727                 trace2_region_leave("diff", "cull after exact", options->repo);
728         } else {
729                 /* Determine minimum score to match basenames */
730                 double factor = 0.5;
731                 char *basename_factor = getenv("GIT_BASENAME_FACTOR");
732                 int min_basename_score;
733
734                 if (basename_factor)
735                         factor = strtol(basename_factor, NULL, 10)/100.0;
736                 assert(factor >= 0.0 && factor <= 1.0);
737                 min_basename_score = minimum_score +
738                         (int)(factor * (MAX_SCORE - minimum_score));
739
740                 /*
741                  * Cull sources:
742                  *   - remove ones involved in renames (found via exact match)
743                  */
744                 trace2_region_enter("diff", "cull after exact", options->repo);
745                 remove_unneeded_paths_from_src(want_copies);
746                 trace2_region_leave("diff", "cull after exact", options->repo);
747
748                 /* Utilize file basenames to quickly find renames. */
749                 trace2_region_enter("diff", "basename matches", options->repo);
750                 rename_count += find_basename_matches(options,
751                                                       min_basename_score);
752                 trace2_region_leave("diff", "basename matches", options->repo);
753
754                 /*
755                  * Cull sources, again:
756                  *   - remove ones involved in renames (found via basenames)
757                  */
758                 trace2_region_enter("diff", "cull basename", options->repo);
759                 remove_unneeded_paths_from_src(want_copies);
760                 trace2_region_leave("diff", "cull basename", options->repo);
761         }
762
763         /* Calculate how many rename destinations are left */
764         num_destinations = (rename_dst_nr - rename_count);
765         num_sources = rename_src_nr; /* rename_src_nr reflects lower number */
766
767         /* All done? */
768         if (!num_destinations || !num_sources)
769                 goto cleanup;
770
771         switch (too_many_rename_candidates(num_destinations, num_sources,
772                                            options)) {
773         case 1:
774                 goto cleanup;
775         case 2:
776                 options->degraded_cc_to_c = 1;
777                 skip_unmodified = 1;
778                 break;
779         default:
780                 break;
781         }
782
783         trace2_region_enter("diff", "inexact renames", options->repo);
784         if (options->show_rename_progress) {
785                 progress = start_delayed_progress(
786                                 _("Performing inexact rename detection"),
787                                 (uint64_t)num_destinations * (uint64_t)num_sources);
788         }
789
790         mx = xcalloc(st_mult(NUM_CANDIDATE_PER_DST, num_destinations),
791                      sizeof(*mx));
792         for (dst_cnt = i = 0; i < rename_dst_nr; i++) {
793                 struct diff_filespec *two = rename_dst[i].p->two;
794                 struct diff_score *m;
795
796                 if (rename_dst[i].is_rename)
797                         continue; /* exact or basename match already handled */
798
799                 m = &mx[dst_cnt * NUM_CANDIDATE_PER_DST];
800                 for (j = 0; j < NUM_CANDIDATE_PER_DST; j++)
801                         m[j].dst = -1;
802
803                 for (j = 0; j < rename_src_nr; j++) {
804                         struct diff_filespec *one = rename_src[j].p->one;
805                         struct diff_score this_src;
806
807                         assert(!one->rename_used || want_copies || break_idx);
808
809                         if (skip_unmodified &&
810                             diff_unmodified_pair(rename_src[j].p))
811                                 continue;
812
813                         this_src.score = estimate_similarity(options->repo,
814                                                              one, two,
815                                                              minimum_score,
816                                                              skip_unmodified);
817                         this_src.name_score = basename_same(one, two);
818                         this_src.dst = i;
819                         this_src.src = j;
820                         record_if_better(m, &this_src);
821                         /*
822                          * Once we run estimate_similarity,
823                          * We do not need the text anymore.
824                          */
825                         diff_free_filespec_blob(one);
826                         diff_free_filespec_blob(two);
827                 }
828                 dst_cnt++;
829                 display_progress(progress,
830                                  (uint64_t)dst_cnt * (uint64_t)num_sources);
831         }
832         stop_progress(&progress);
833
834         /* cost matrix sorted by most to least similar pair */
835         STABLE_QSORT(mx, dst_cnt * NUM_CANDIDATE_PER_DST, score_compare);
836
837         rename_count += find_renames(mx, dst_cnt, minimum_score, 0);
838         if (want_copies)
839                 rename_count += find_renames(mx, dst_cnt, minimum_score, 1);
840         free(mx);
841         trace2_region_leave("diff", "inexact renames", options->repo);
842
843  cleanup:
844         /* At this point, we have found some renames and copies and they
845          * are recorded in rename_dst.  The original list is still in *q.
846          */
847         trace2_region_enter("diff", "write back to queue", options->repo);
848         DIFF_QUEUE_CLEAR(&outq);
849         for (i = 0; i < q->nr; i++) {
850                 struct diff_filepair *p = q->queue[i];
851                 struct diff_filepair *pair_to_free = NULL;
852
853                 if (DIFF_PAIR_UNMERGED(p)) {
854                         diff_q(&outq, p);
855                 }
856                 else if (!DIFF_FILE_VALID(p->one) && DIFF_FILE_VALID(p->two)) {
857                         /* Creation */
858                         diff_q(&outq, p);
859                 }
860                 else if (DIFF_FILE_VALID(p->one) && !DIFF_FILE_VALID(p->two)) {
861                         /*
862                          * Deletion
863                          *
864                          * We would output this delete record if:
865                          *
866                          * (1) this is a broken delete and the counterpart
867                          *     broken create remains in the output; or
868                          * (2) this is not a broken delete, and rename_dst
869                          *     does not have a rename/copy to move p->one->path
870                          *     out of existence.
871                          *
872                          * Otherwise, the counterpart broken create
873                          * has been turned into a rename-edit; or
874                          * delete did not have a matching create to
875                          * begin with.
876                          */
877                         if (DIFF_PAIR_BROKEN(p)) {
878                                 /* broken delete */
879                                 struct diff_rename_dst *dst = locate_rename_dst(p);
880                                 if (!dst)
881                                         BUG("tracking failed somehow; failed to find associated dst for broken pair");
882                                 if (dst->is_rename)
883                                         /* counterpart is now rename/copy */
884                                         pair_to_free = p;
885                         }
886                         else {
887                                 if (p->one->rename_used)
888                                         /* this path remains */
889                                         pair_to_free = p;
890                         }
891
892                         if (!pair_to_free)
893                                 diff_q(&outq, p);
894                 }
895                 else if (!diff_unmodified_pair(p))
896                         /* all the usual ones need to be kept */
897                         diff_q(&outq, p);
898                 else
899                         /* no need to keep unmodified pairs; FIXME: remove earlier? */
900                         pair_to_free = p;
901
902                 if (pair_to_free)
903                         diff_free_filepair(pair_to_free);
904         }
905         diff_debug_queue("done copying original", &outq);
906
907         free(q->queue);
908         *q = outq;
909         diff_debug_queue("done collapsing", q);
910
911         for (i = 0; i < rename_dst_nr; i++)
912                 if (rename_dst[i].filespec_to_free)
913                         free_filespec(rename_dst[i].filespec_to_free);
914
915         FREE_AND_NULL(rename_dst);
916         rename_dst_nr = rename_dst_alloc = 0;
917         FREE_AND_NULL(rename_src);
918         rename_src_nr = rename_src_alloc = 0;
919         if (break_idx) {
920                 strintmap_clear(break_idx);
921                 FREE_AND_NULL(break_idx);
922         }
923         trace2_region_leave("diff", "write back to queue", options->repo);
924         return;
925 }