Git 2.32
[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 struct dir_rename_info {
371         struct strintmap idx_map;
372         struct strmap dir_rename_guess;
373         struct strmap *dir_rename_count;
374         struct strintmap *relevant_source_dirs;
375         unsigned setup;
376 };
377
378 static char *get_dirname(const char *filename)
379 {
380         char *slash = strrchr(filename, '/');
381         return slash ? xstrndup(filename, slash - filename) : xstrdup("");
382 }
383
384 static void dirname_munge(char *filename)
385 {
386         char *slash = strrchr(filename, '/');
387         if (!slash)
388                 slash = filename;
389         *slash = '\0';
390 }
391
392 static const char *get_highest_rename_path(struct strintmap *counts)
393 {
394         int highest_count = 0;
395         const char *highest_destination_dir = NULL;
396         struct hashmap_iter iter;
397         struct strmap_entry *entry;
398
399         strintmap_for_each_entry(counts, &iter, entry) {
400                 const char *destination_dir = entry->key;
401                 intptr_t count = (intptr_t)entry->value;
402                 if (count > highest_count) {
403                         highest_count = count;
404                         highest_destination_dir = destination_dir;
405                 }
406         }
407         return highest_destination_dir;
408 }
409
410 static char *UNKNOWN_DIR = "/";  /* placeholder -- short, illegal directory */
411
412 static int dir_rename_already_determinable(struct strintmap *counts)
413 {
414         struct hashmap_iter iter;
415         struct strmap_entry *entry;
416         int first = 0, second = 0, unknown = 0;
417         strintmap_for_each_entry(counts, &iter, entry) {
418                 const char *destination_dir = entry->key;
419                 intptr_t count = (intptr_t)entry->value;
420                 if (!strcmp(destination_dir, UNKNOWN_DIR)) {
421                         unknown = count;
422                 } else if (count >= first) {
423                         second = first;
424                         first = count;
425                 } else if (count >= second) {
426                         second = count;
427                 }
428         }
429         return first > second + unknown;
430 }
431
432 static void increment_count(struct dir_rename_info *info,
433                             char *old_dir,
434                             char *new_dir)
435 {
436         struct strintmap *counts;
437         struct strmap_entry *e;
438
439         /* Get the {new_dirs -> counts} mapping using old_dir */
440         e = strmap_get_entry(info->dir_rename_count, old_dir);
441         if (e) {
442                 counts = e->value;
443         } else {
444                 counts = xmalloc(sizeof(*counts));
445                 strintmap_init_with_options(counts, 0, NULL, 1);
446                 strmap_put(info->dir_rename_count, old_dir, counts);
447         }
448
449         /* Increment the count for new_dir */
450         strintmap_incr(counts, new_dir, 1);
451 }
452
453 static void update_dir_rename_counts(struct dir_rename_info *info,
454                                      struct strintmap *dirs_removed,
455                                      const char *oldname,
456                                      const char *newname)
457 {
458         char *old_dir = xstrdup(oldname);
459         char *new_dir = xstrdup(newname);
460         char new_dir_first_char = new_dir[0];
461         int first_time_in_loop = 1;
462
463         if (!info->setup)
464                 /*
465                  * info->setup is 0 here in two cases: (1) all auxiliary
466                  * vars (like dirs_removed) were NULL so
467                  * initialize_dir_rename_info() returned early, or (2)
468                  * either break detection or copy detection are active so
469                  * that we never called initialize_dir_rename_info().  In
470                  * the former case, we don't have enough info to know if
471                  * directories were renamed (because dirs_removed lets us
472                  * know about a necessary prerequisite, namely if they were
473                  * removed), and in the latter, we don't care about
474                  * directory renames or find_basename_matches.
475                  *
476                  * This matters because both basename and inexact matching
477                  * will also call update_dir_rename_counts().  In either of
478                  * the above two cases info->dir_rename_counts will not
479                  * have been properly initialized which prevents us from
480                  * updating it, but in these two cases we don't care about
481                  * dir_rename_counts anyway, so we can just exit early.
482                  */
483                 return;
484
485         while (1) {
486                 int drd_flag = NOT_RELEVANT;
487
488                 /* Get old_dir, skip if its directory isn't relevant. */
489                 dirname_munge(old_dir);
490                 if (info->relevant_source_dirs &&
491                     !strintmap_contains(info->relevant_source_dirs, old_dir))
492                         break;
493
494                 /* Get new_dir */
495                 dirname_munge(new_dir);
496
497                 /*
498                  * When renaming
499                  *   "a/b/c/d/e/foo.c" -> "a/b/some/thing/else/e/foo.c"
500                  * then this suggests that both
501                  *   a/b/c/d/e/ => a/b/some/thing/else/e/
502                  *   a/b/c/d/   => a/b/some/thing/else/
503                  * so we want to increment counters for both.  We do NOT,
504                  * however, also want to suggest that there was the following
505                  * rename:
506                  *   a/b/c/ => a/b/some/thing/
507                  * so we need to quit at that point.
508                  *
509                  * Note the when first_time_in_loop, we only strip off the
510                  * basename, and we don't care if that's different.
511                  */
512                 if (!first_time_in_loop) {
513                         char *old_sub_dir = strchr(old_dir, '\0')+1;
514                         char *new_sub_dir = strchr(new_dir, '\0')+1;
515                         if (!*new_dir) {
516                                 /*
517                                  * Special case when renaming to root directory,
518                                  * i.e. when new_dir == "".  In this case, we had
519                                  * something like
520                                  *    a/b/subdir => subdir
521                                  * and so dirname_munge() sets things up so that
522                                  *    old_dir = "a/b\0subdir\0"
523                                  *    new_dir = "\0ubdir\0"
524                                  * We didn't have a '/' to overwrite a '\0' onto
525                                  * in new_dir, so we have to compare differently.
526                                  */
527                                 if (new_dir_first_char != old_sub_dir[0] ||
528                                     strcmp(old_sub_dir+1, new_sub_dir))
529                                         break;
530                         } else {
531                                 if (strcmp(old_sub_dir, new_sub_dir))
532                                         break;
533                         }
534                 }
535
536                 /*
537                  * Above we suggested that we'd keep recording renames for
538                  * all ancestor directories where the trailing directories
539                  * matched, i.e. for
540                  *   "a/b/c/d/e/foo.c" -> "a/b/some/thing/else/e/foo.c"
541                  * we'd increment rename counts for each of
542                  *   a/b/c/d/e/ => a/b/some/thing/else/e/
543                  *   a/b/c/d/   => a/b/some/thing/else/
544                  * However, we only need the rename counts for directories
545                  * in dirs_removed whose value is RELEVANT_FOR_SELF.
546                  * However, we add one special case of also recording it for
547                  * first_time_in_loop because find_basename_matches() can
548                  * use that as a hint to find a good pairing.
549                  */
550                 if (dirs_removed)
551                         drd_flag = strintmap_get(dirs_removed, old_dir);
552                 if (drd_flag == RELEVANT_FOR_SELF || first_time_in_loop)
553                         increment_count(info, old_dir, new_dir);
554
555                 first_time_in_loop = 0;
556                 if (drd_flag == NOT_RELEVANT)
557                         break;
558                 /* If we hit toplevel directory ("") for old or new dir, quit */
559                 if (!*old_dir || !*new_dir)
560                         break;
561         }
562
563         /* Free resources we don't need anymore */
564         free(old_dir);
565         free(new_dir);
566 }
567
568 static void initialize_dir_rename_info(struct dir_rename_info *info,
569                                        struct strintmap *relevant_sources,
570                                        struct strintmap *dirs_removed,
571                                        struct strmap *dir_rename_count)
572 {
573         struct hashmap_iter iter;
574         struct strmap_entry *entry;
575         int i;
576
577         if (!dirs_removed && !relevant_sources) {
578                 info->setup = 0;
579                 return;
580         }
581         info->setup = 1;
582
583         info->dir_rename_count = dir_rename_count;
584         if (!info->dir_rename_count) {
585                 info->dir_rename_count = xmalloc(sizeof(*dir_rename_count));
586                 strmap_init(info->dir_rename_count);
587         }
588         strintmap_init_with_options(&info->idx_map, -1, NULL, 0);
589         strmap_init_with_options(&info->dir_rename_guess, NULL, 0);
590
591         /* Setup info->relevant_source_dirs */
592         info->relevant_source_dirs = NULL;
593         if (dirs_removed || !relevant_sources) {
594                 info->relevant_source_dirs = dirs_removed; /* might be NULL */
595         } else {
596                 info->relevant_source_dirs = xmalloc(sizeof(struct strintmap));
597                 strintmap_init(info->relevant_source_dirs, 0 /* unused */);
598                 strintmap_for_each_entry(relevant_sources, &iter, entry) {
599                         char *dirname = get_dirname(entry->key);
600                         if (!dirs_removed ||
601                             strintmap_contains(dirs_removed, dirname))
602                                 strintmap_set(info->relevant_source_dirs,
603                                               dirname, 0 /* value irrelevant */);
604                         free(dirname);
605                 }
606         }
607
608         /*
609          * Loop setting up both info->idx_map, and doing setup of
610          * info->dir_rename_count.
611          */
612         for (i = 0; i < rename_dst_nr; ++i) {
613                 /*
614                  * For non-renamed files, make idx_map contain mapping of
615                  *   filename -> index (index within rename_dst, that is)
616                  */
617                 if (!rename_dst[i].is_rename) {
618                         char *filename = rename_dst[i].p->two->path;
619                         strintmap_set(&info->idx_map, filename, i);
620                         continue;
621                 }
622
623                 /*
624                  * For everything else (i.e. renamed files), make
625                  * dir_rename_count contain a map of a map:
626                  *   old_directory -> {new_directory -> count}
627                  * In other words, for every pair look at the directories for
628                  * the old filename and the new filename and count how many
629                  * times that pairing occurs.
630                  */
631                 update_dir_rename_counts(info, dirs_removed,
632                                          rename_dst[i].p->one->path,
633                                          rename_dst[i].p->two->path);
634         }
635
636         /*
637          * Now we collapse
638          *    dir_rename_count: old_directory -> {new_directory -> count}
639          * down to
640          *    dir_rename_guess: old_directory -> best_new_directory
641          * where best_new_directory is the one with the highest count.
642          */
643         strmap_for_each_entry(info->dir_rename_count, &iter, entry) {
644                 /* entry->key is source_dir */
645                 struct strintmap *counts = entry->value;
646                 char *best_newdir;
647
648                 best_newdir = xstrdup(get_highest_rename_path(counts));
649                 strmap_put(&info->dir_rename_guess, entry->key,
650                            best_newdir);
651         }
652 }
653
654 void partial_clear_dir_rename_count(struct strmap *dir_rename_count)
655 {
656         struct hashmap_iter iter;
657         struct strmap_entry *entry;
658
659         strmap_for_each_entry(dir_rename_count, &iter, entry) {
660                 struct strintmap *counts = entry->value;
661                 strintmap_clear(counts);
662         }
663         strmap_partial_clear(dir_rename_count, 1);
664 }
665
666 static void cleanup_dir_rename_info(struct dir_rename_info *info,
667                                     struct strintmap *dirs_removed,
668                                     int keep_dir_rename_count)
669 {
670         struct hashmap_iter iter;
671         struct strmap_entry *entry;
672         struct string_list to_remove = STRING_LIST_INIT_NODUP;
673         int i;
674
675         if (!info->setup)
676                 return;
677
678         /* idx_map */
679         strintmap_clear(&info->idx_map);
680
681         /* dir_rename_guess */
682         strmap_clear(&info->dir_rename_guess, 1);
683
684         /* relevant_source_dirs */
685         if (info->relevant_source_dirs &&
686             info->relevant_source_dirs != dirs_removed) {
687                 strintmap_clear(info->relevant_source_dirs);
688                 FREE_AND_NULL(info->relevant_source_dirs);
689         }
690
691         /* dir_rename_count */
692         if (!keep_dir_rename_count) {
693                 partial_clear_dir_rename_count(info->dir_rename_count);
694                 strmap_clear(info->dir_rename_count, 1);
695                 FREE_AND_NULL(info->dir_rename_count);
696                 return;
697         }
698
699         /*
700          * Although dir_rename_count was passed in
701          * diffcore_rename_extended() and we want to keep it around and
702          * return it to that caller, we first want to remove any counts in
703          * the maps associated with UNKNOWN_DIR entries and any data
704          * associated with directories that weren't renamed.
705          */
706         strmap_for_each_entry(info->dir_rename_count, &iter, entry) {
707                 const char *source_dir = entry->key;
708                 struct strintmap *counts = entry->value;
709
710                 if (!strintmap_get(dirs_removed, source_dir)) {
711                         string_list_append(&to_remove, source_dir);
712                         strintmap_clear(counts);
713                         continue;
714                 }
715
716                 if (strintmap_contains(counts, UNKNOWN_DIR))
717                         strintmap_remove(counts, UNKNOWN_DIR);
718         }
719         for (i = 0; i < to_remove.nr; ++i)
720                 strmap_remove(info->dir_rename_count,
721                               to_remove.items[i].string, 1);
722         string_list_clear(&to_remove, 0);
723 }
724
725 static const char *get_basename(const char *filename)
726 {
727         /*
728          * gitbasename() has to worry about special drives, multiple
729          * directory separator characters, trailing slashes, NULL or
730          * empty strings, etc.  We only work on filenames as stored in
731          * git, and thus get to ignore all those complications.
732          */
733         const char *base = strrchr(filename, '/');
734         return base ? base + 1 : filename;
735 }
736
737 static int idx_possible_rename(char *filename, struct dir_rename_info *info)
738 {
739         /*
740          * Our comparison of files with the same basename (see
741          * find_basename_matches() below), is only helpful when after exact
742          * rename detection we have exactly one file with a given basename
743          * among the rename sources and also only exactly one file with
744          * that basename among the rename destinations.  When we have
745          * multiple files with the same basename in either set, we do not
746          * know which to compare against.  However, there are some
747          * filenames that occur in large numbers (particularly
748          * build-related filenames such as 'Makefile', '.gitignore', or
749          * 'build.gradle' that potentially exist within every single
750          * subdirectory), and for performance we want to be able to quickly
751          * find renames for these files too.
752          *
753          * The reason basename comparisons are a useful heuristic was that it
754          * is common for people to move files across directories while keeping
755          * their filename the same.  If we had a way of determining or even
756          * making a good educated guess about which directory these non-unique
757          * basename files had moved the file to, we could check it.
758          * Luckily...
759          *
760          * When an entire directory is in fact renamed, we have two factors
761          * helping us out:
762          *   (a) the original directory disappeared giving us a hint
763          *       about when we can apply an extra heuristic.
764          *   (a) we often have several files within that directory and
765          *       subdirectories that are renamed without changes
766          * So, rules for a heuristic:
767          *   (0) If there basename matches are non-unique (the condition under
768          *       which this function is called) AND
769          *   (1) the directory in which the file was found has disappeared
770          *       (i.e. dirs_removed is non-NULL and has a relevant entry) THEN
771          *   (2) use exact renames of files within the directory to determine
772          *       where the directory is likely to have been renamed to.  IF
773          *       there is at least one exact rename from within that
774          *       directory, we can proceed.
775          *   (3) If there are multiple places the directory could have been
776          *       renamed to based on exact renames, ignore all but one of them.
777          *       Just use the destination with the most renames going to it.
778          *   (4) Check if applying that directory rename to the original file
779          *       would result in a destination filename that is in the
780          *       potential rename set.  If so, return the index of the
781          *       destination file (the index within rename_dst).
782          *   (5) Compare the original file and returned destination for
783          *       similarity, and if they are sufficiently similar, record the
784          *       rename.
785          *
786          * This function, idx_possible_rename(), is only responsible for (4).
787          * The conditions/steps in (1)-(3) are handled via setting up
788          * dir_rename_count and dir_rename_guess in
789          * initialize_dir_rename_info().  Steps (0) and (5) are handled by
790          * the caller of this function.
791          */
792         char *old_dir, *new_dir;
793         struct strbuf new_path = STRBUF_INIT;
794         int idx;
795
796         if (!info->setup)
797                 return -1;
798
799         old_dir = get_dirname(filename);
800         new_dir = strmap_get(&info->dir_rename_guess, old_dir);
801         free(old_dir);
802         if (!new_dir)
803                 return -1;
804
805         strbuf_addstr(&new_path, new_dir);
806         strbuf_addch(&new_path, '/');
807         strbuf_addstr(&new_path, get_basename(filename));
808
809         idx = strintmap_get(&info->idx_map, new_path.buf);
810         strbuf_release(&new_path);
811         return idx;
812 }
813
814 static int find_basename_matches(struct diff_options *options,
815                                  int minimum_score,
816                                  struct dir_rename_info *info,
817                                  struct strintmap *relevant_sources,
818                                  struct strintmap *dirs_removed)
819 {
820         /*
821          * When I checked in early 2020, over 76% of file renames in linux
822          * just moved files to a different directory but kept the same
823          * basename.  gcc did that with over 64% of renames, gecko did it
824          * with over 79%, and WebKit did it with over 89%.
825          *
826          * Therefore we can bypass the normal exhaustive NxM matrix
827          * comparison of similarities between all potential rename sources
828          * and destinations by instead using file basename as a hint (i.e.
829          * the portion of the filename after the last '/'), checking for
830          * similarity between files with the same basename, and if we find
831          * a pair that are sufficiently similar, record the rename pair and
832          * exclude those two from the NxM matrix.
833          *
834          * This *might* cause us to find a less than optimal pairing (if
835          * there is another file that we are even more similar to but has a
836          * different basename).  Given the huge performance advantage
837          * basename matching provides, and given the frequency with which
838          * people use the same basename in real world projects, that's a
839          * trade-off we are willing to accept when doing just rename
840          * detection.
841          *
842          * If someone wants copy detection that implies they are willing to
843          * spend more cycles to find similarities between files, so it may
844          * be less likely that this heuristic is wanted.  If someone is
845          * doing break detection, that means they do not want filename
846          * similarity to imply any form of content similiarity, and thus
847          * this heuristic would definitely be incompatible.
848          */
849
850         int i, renames = 0;
851         struct strintmap sources;
852         struct strintmap dests;
853
854         /*
855          * The prefeteching stuff wants to know if it can skip prefetching
856          * blobs that are unmodified...and will then do a little extra work
857          * to verify that the oids are indeed different before prefetching.
858          * Unmodified blobs are only relevant when doing copy detection;
859          * when limiting to rename detection, diffcore_rename[_extended]()
860          * will never be called with unmodified source paths fed to us, so
861          * the extra work necessary to check if rename_src entries are
862          * unmodified would be a small waste.
863          */
864         int skip_unmodified = 0;
865
866         /*
867          * Create maps of basename -> fullname(s) for remaining sources and
868          * dests.
869          */
870         strintmap_init_with_options(&sources, -1, NULL, 0);
871         strintmap_init_with_options(&dests, -1, NULL, 0);
872         for (i = 0; i < rename_src_nr; ++i) {
873                 char *filename = rename_src[i].p->one->path;
874                 const char *base;
875
876                 /* exact renames removed in remove_unneeded_paths_from_src() */
877                 assert(!rename_src[i].p->one->rename_used);
878
879                 /* Record index within rename_src (i) if basename is unique */
880                 base = get_basename(filename);
881                 if (strintmap_contains(&sources, base))
882                         strintmap_set(&sources, base, -1);
883                 else
884                         strintmap_set(&sources, base, i);
885         }
886         for (i = 0; i < rename_dst_nr; ++i) {
887                 char *filename = rename_dst[i].p->two->path;
888                 const char *base;
889
890                 if (rename_dst[i].is_rename)
891                         continue; /* involved in exact match already. */
892
893                 /* Record index within rename_dst (i) if basename is unique */
894                 base = get_basename(filename);
895                 if (strintmap_contains(&dests, base))
896                         strintmap_set(&dests, base, -1);
897                 else
898                         strintmap_set(&dests, base, i);
899         }
900
901         /* Now look for basename matchups and do similarity estimation */
902         for (i = 0; i < rename_src_nr; ++i) {
903                 char *filename = rename_src[i].p->one->path;
904                 const char *base = NULL;
905                 intptr_t src_index;
906                 intptr_t dst_index;
907
908                 /* Skip irrelevant sources */
909                 if (relevant_sources &&
910                     !strintmap_contains(relevant_sources, filename))
911                         continue;
912
913                 /*
914                  * If the basename is unique among remaining sources, then
915                  * src_index will equal 'i' and we can attempt to match it
916                  * to a unique basename in the destinations.  Otherwise,
917                  * use directory rename heuristics, if possible.
918                  */
919                 base = get_basename(filename);
920                 src_index = strintmap_get(&sources, base);
921                 assert(src_index == -1 || src_index == i);
922
923                 if (strintmap_contains(&dests, base)) {
924                         struct diff_filespec *one, *two;
925                         int score;
926
927                         /* Find a matching destination, if possible */
928                         dst_index = strintmap_get(&dests, base);
929                         if (src_index == -1 || dst_index == -1) {
930                                 src_index = i;
931                                 dst_index = idx_possible_rename(filename, info);
932                         }
933                         if (dst_index == -1)
934                                 continue;
935
936                         /* Ignore this dest if already used in a rename */
937                         if (rename_dst[dst_index].is_rename)
938                                 continue; /* already used previously */
939
940                         /* Estimate the similarity */
941                         one = rename_src[src_index].p->one;
942                         two = rename_dst[dst_index].p->two;
943                         score = estimate_similarity(options->repo, one, two,
944                                                     minimum_score, skip_unmodified);
945
946                         /* If sufficiently similar, record as rename pair */
947                         if (score < minimum_score)
948                                 continue;
949                         record_rename_pair(dst_index, src_index, score);
950                         renames++;
951                         update_dir_rename_counts(info, dirs_removed,
952                                                  one->path, two->path);
953
954                         /*
955                          * Found a rename so don't need text anymore; if we
956                          * didn't find a rename, the filespec_blob would get
957                          * re-used when doing the matrix of comparisons.
958                          */
959                         diff_free_filespec_blob(one);
960                         diff_free_filespec_blob(two);
961                 }
962         }
963
964         strintmap_clear(&sources);
965         strintmap_clear(&dests);
966
967         return renames;
968 }
969
970 #define NUM_CANDIDATE_PER_DST 4
971 static void record_if_better(struct diff_score m[], struct diff_score *o)
972 {
973         int i, worst;
974
975         /* find the worst one */
976         worst = 0;
977         for (i = 1; i < NUM_CANDIDATE_PER_DST; i++)
978                 if (score_compare(&m[i], &m[worst]) > 0)
979                         worst = i;
980
981         /* is it better than the worst one? */
982         if (score_compare(&m[worst], o) > 0)
983                 m[worst] = *o;
984 }
985
986 /*
987  * Returns:
988  * 0 if we are under the limit;
989  * 1 if we need to disable inexact rename detection;
990  * 2 if we would be under the limit if we were given -C instead of -C -C.
991  */
992 static int too_many_rename_candidates(int num_destinations, int num_sources,
993                                       struct diff_options *options)
994 {
995         int rename_limit = options->rename_limit;
996         int i, limited_sources;
997
998         options->needed_rename_limit = 0;
999
1000         /*
1001          * This basically does a test for the rename matrix not
1002          * growing larger than a "rename_limit" square matrix, ie:
1003          *
1004          *    num_destinations * num_sources > rename_limit * rename_limit
1005          *
1006          * We use st_mult() to check overflow conditions; in the
1007          * exceptional circumstance that size_t isn't large enough to hold
1008          * the multiplication, the system won't be able to allocate enough
1009          * memory for the matrix anyway.
1010          */
1011         if (rename_limit <= 0)
1012                 rename_limit = 32767;
1013         if (st_mult(num_destinations, num_sources)
1014             <= st_mult(rename_limit, rename_limit))
1015                 return 0;
1016
1017         options->needed_rename_limit =
1018                 num_sources > num_destinations ? num_sources : num_destinations;
1019
1020         /* Are we running under -C -C? */
1021         if (!options->flags.find_copies_harder)
1022                 return 1;
1023
1024         /* Would we bust the limit if we were running under -C? */
1025         for (limited_sources = i = 0; i < num_sources; i++) {
1026                 if (diff_unmodified_pair(rename_src[i].p))
1027                         continue;
1028                 limited_sources++;
1029         }
1030         if (st_mult(num_destinations, limited_sources)
1031             <= st_mult(rename_limit, rename_limit))
1032                 return 2;
1033         return 1;
1034 }
1035
1036 static int find_renames(struct diff_score *mx,
1037                         int dst_cnt,
1038                         int minimum_score,
1039                         int copies,
1040                         struct dir_rename_info *info,
1041                         struct strintmap *dirs_removed)
1042 {
1043         int count = 0, i;
1044
1045         for (i = 0; i < dst_cnt * NUM_CANDIDATE_PER_DST; i++) {
1046                 struct diff_rename_dst *dst;
1047
1048                 if ((mx[i].dst < 0) ||
1049                     (mx[i].score < minimum_score))
1050                         break; /* there is no more usable pair. */
1051                 dst = &rename_dst[mx[i].dst];
1052                 if (dst->is_rename)
1053                         continue; /* already done, either exact or fuzzy. */
1054                 if (!copies && rename_src[mx[i].src].p->one->rename_used)
1055                         continue;
1056                 record_rename_pair(mx[i].dst, mx[i].src, mx[i].score);
1057                 count++;
1058                 update_dir_rename_counts(info, dirs_removed,
1059                                          rename_src[mx[i].src].p->one->path,
1060                                          rename_dst[mx[i].dst].p->two->path);
1061         }
1062         return count;
1063 }
1064
1065 static void remove_unneeded_paths_from_src(int detecting_copies,
1066                                            struct strintmap *interesting)
1067 {
1068         int i, new_num_src;
1069
1070         if (detecting_copies && !interesting)
1071                 return; /* nothing to remove */
1072         if (break_idx)
1073                 return; /* culling incompatible with break detection */
1074
1075         /*
1076          * Note on reasons why we cull unneeded sources but not destinations:
1077          *   1) Pairings are stored in rename_dst (not rename_src), which we
1078          *      need to keep around.  So, we just can't cull rename_dst even
1079          *      if we wanted to.  But doing so wouldn't help because...
1080          *
1081          *   2) There is a matrix pairwise comparison that follows the
1082          *      "Performing inexact rename detection" progress message.
1083          *      Iterating over the destinations is done in the outer loop,
1084          *      hence we only iterate over each of those once and we can
1085          *      easily skip the outer loop early if the destination isn't
1086          *      relevant.  That's only one check per destination path to
1087          *      skip.
1088          *
1089          *      By contrast, the sources are iterated in the inner loop; if
1090          *      we check whether a source can be skipped, then we'll be
1091          *      checking it N separate times, once for each destination.
1092          *      We don't want to have to iterate over known-not-needed
1093          *      sources N times each, so avoid that by removing the sources
1094          *      from rename_src here.
1095          */
1096         for (i = 0, new_num_src = 0; i < rename_src_nr; i++) {
1097                 struct diff_filespec *one = rename_src[i].p->one;
1098
1099                 /*
1100                  * renames are stored in rename_dst, so if a rename has
1101                  * already been detected using this source, we can just
1102                  * remove the source knowing rename_dst has its info.
1103                  */
1104                 if (!detecting_copies && one->rename_used)
1105                         continue;
1106
1107                 /* If we don't care about the source path, skip it */
1108                 if (interesting && !strintmap_contains(interesting, one->path))
1109                         continue;
1110
1111                 if (new_num_src < i)
1112                         memcpy(&rename_src[new_num_src], &rename_src[i],
1113                                sizeof(struct diff_rename_src));
1114                 new_num_src++;
1115         }
1116
1117         rename_src_nr = new_num_src;
1118 }
1119
1120 static void handle_early_known_dir_renames(struct dir_rename_info *info,
1121                                            struct strintmap *relevant_sources,
1122                                            struct strintmap *dirs_removed)
1123 {
1124         /*
1125          * Directory renames are determined via an aggregate of all renames
1126          * under them and using a "majority wins" rule.  The fact that
1127          * "majority wins", though, means we don't need all the renames
1128          * under the given directory, we only need enough to ensure we have
1129          * a majority.
1130          */
1131
1132         int i, new_num_src;
1133         struct hashmap_iter iter;
1134         struct strmap_entry *entry;
1135
1136         if (!dirs_removed || !relevant_sources)
1137                 return; /* nothing to cull */
1138         if (break_idx)
1139                 return; /* culling incompatbile with break detection */
1140
1141         /*
1142          * Supplement dir_rename_count with number of potential renames,
1143          * marking all potential rename sources as mapping to UNKNOWN_DIR.
1144          */
1145         for (i = 0; i < rename_src_nr; i++) {
1146                 char *old_dir;
1147                 struct diff_filespec *one = rename_src[i].p->one;
1148
1149                 /*
1150                  * sources that are part of a rename will have already been
1151                  * removed by a prior call to remove_unneeded_paths_from_src()
1152                  */
1153                 assert(!one->rename_used);
1154
1155                 old_dir = get_dirname(one->path);
1156                 while (*old_dir != '\0' &&
1157                        NOT_RELEVANT != strintmap_get(dirs_removed, old_dir)) {
1158                         char *freeme = old_dir;
1159
1160                         increment_count(info, old_dir, UNKNOWN_DIR);
1161                         old_dir = get_dirname(old_dir);
1162
1163                         /* Free resources we don't need anymore */
1164                         free(freeme);
1165                 }
1166                 /*
1167                  * old_dir and new_dir free'd in increment_count, but
1168                  * get_dirname() gives us a new pointer we need to free for
1169                  * old_dir.  Also, if the loop runs 0 times we need old_dir
1170                  * to be freed.
1171                  */
1172                 free(old_dir);
1173         }
1174
1175         /*
1176          * For any directory which we need a potential rename detected for
1177          * (i.e. those marked as RELEVANT_FOR_SELF in dirs_removed), check
1178          * whether we have enough renames to satisfy the "majority rules"
1179          * requirement such that detecting any more renames of files under
1180          * it won't change the result.  For any such directory, mark that
1181          * we no longer need to detect a rename for it.  However, since we
1182          * might need to still detect renames for an ancestor of that
1183          * directory, use RELEVANT_FOR_ANCESTOR.
1184          */
1185         strmap_for_each_entry(info->dir_rename_count, &iter, entry) {
1186                 /* entry->key is source_dir */
1187                 struct strintmap *counts = entry->value;
1188
1189                 if (strintmap_get(dirs_removed, entry->key) ==
1190                     RELEVANT_FOR_SELF &&
1191                     dir_rename_already_determinable(counts)) {
1192                         strintmap_set(dirs_removed, entry->key,
1193                                       RELEVANT_FOR_ANCESTOR);
1194                 }
1195         }
1196
1197         for (i = 0, new_num_src = 0; i < rename_src_nr; i++) {
1198                 struct diff_filespec *one = rename_src[i].p->one;
1199                 int val;
1200
1201                 val = strintmap_get(relevant_sources, one->path);
1202
1203                 /*
1204                  * sources that were not found in relevant_sources should
1205                  * have already been removed by a prior call to
1206                  * remove_unneeded_paths_from_src()
1207                  */
1208                 assert(val != -1);
1209
1210                 if (val == RELEVANT_LOCATION) {
1211                         int removable = 1;
1212                         char *dir = get_dirname(one->path);
1213                         while (1) {
1214                                 char *freeme = dir;
1215                                 int res = strintmap_get(dirs_removed, dir);
1216
1217                                 /* Quit if not found or irrelevant */
1218                                 if (res == NOT_RELEVANT)
1219                                         break;
1220                                 /* If RELEVANT_FOR_SELF, can't remove */
1221                                 if (res == RELEVANT_FOR_SELF) {
1222                                         removable = 0;
1223                                         break;
1224                                 }
1225                                 /* Else continue searching upwards */
1226                                 assert(res == RELEVANT_FOR_ANCESTOR);
1227                                 dir = get_dirname(dir);
1228                                 free(freeme);
1229                         }
1230                         free(dir);
1231                         if (removable) {
1232                                 strintmap_set(relevant_sources, one->path,
1233                                               RELEVANT_NO_MORE);
1234                                 continue;
1235                         }
1236                 }
1237
1238                 if (new_num_src < i)
1239                         memcpy(&rename_src[new_num_src], &rename_src[i],
1240                                sizeof(struct diff_rename_src));
1241                 new_num_src++;
1242         }
1243
1244         rename_src_nr = new_num_src;
1245 }
1246
1247 void diffcore_rename_extended(struct diff_options *options,
1248                               struct strintmap *relevant_sources,
1249                               struct strintmap *dirs_removed,
1250                               struct strmap *dir_rename_count)
1251 {
1252         int detect_rename = options->detect_rename;
1253         int minimum_score = options->rename_score;
1254         struct diff_queue_struct *q = &diff_queued_diff;
1255         struct diff_queue_struct outq;
1256         struct diff_score *mx;
1257         int i, j, rename_count, skip_unmodified = 0;
1258         int num_destinations, dst_cnt;
1259         int num_sources, want_copies;
1260         struct progress *progress = NULL;
1261         struct dir_rename_info info;
1262
1263         trace2_region_enter("diff", "setup", options->repo);
1264         info.setup = 0;
1265         assert(!dir_rename_count || strmap_empty(dir_rename_count));
1266         want_copies = (detect_rename == DIFF_DETECT_COPY);
1267         if (dirs_removed && (break_idx || want_copies))
1268                 BUG("dirs_removed incompatible with break/copy detection");
1269         if (break_idx && relevant_sources)
1270                 BUG("break detection incompatible with source specification");
1271         if (!minimum_score)
1272                 minimum_score = DEFAULT_RENAME_SCORE;
1273
1274         for (i = 0; i < q->nr; i++) {
1275                 struct diff_filepair *p = q->queue[i];
1276                 if (!DIFF_FILE_VALID(p->one)) {
1277                         if (!DIFF_FILE_VALID(p->two))
1278                                 continue; /* unmerged */
1279                         else if (options->single_follow &&
1280                                  strcmp(options->single_follow, p->two->path))
1281                                 continue; /* not interested */
1282                         else if (!options->flags.rename_empty &&
1283                                  is_empty_blob_oid(&p->two->oid))
1284                                 continue;
1285                         else if (add_rename_dst(p) < 0) {
1286                                 warning("skipping rename detection, detected"
1287                                         " duplicate destination '%s'",
1288                                         p->two->path);
1289                                 goto cleanup;
1290                         }
1291                 }
1292                 else if (!options->flags.rename_empty &&
1293                          is_empty_blob_oid(&p->one->oid))
1294                         continue;
1295                 else if (!DIFF_PAIR_UNMERGED(p) && !DIFF_FILE_VALID(p->two)) {
1296                         /*
1297                          * If the source is a broken "delete", and
1298                          * they did not really want to get broken,
1299                          * that means the source actually stays.
1300                          * So we increment the "rename_used" score
1301                          * by one, to indicate ourselves as a user
1302                          */
1303                         if (p->broken_pair && !p->score)
1304                                 p->one->rename_used++;
1305                         register_rename_src(p);
1306                 }
1307                 else if (want_copies) {
1308                         /*
1309                          * Increment the "rename_used" score by
1310                          * one, to indicate ourselves as a user.
1311                          */
1312                         p->one->rename_used++;
1313                         register_rename_src(p);
1314                 }
1315         }
1316         trace2_region_leave("diff", "setup", options->repo);
1317         if (rename_dst_nr == 0 || rename_src_nr == 0)
1318                 goto cleanup; /* nothing to do */
1319
1320         trace2_region_enter("diff", "exact renames", options->repo);
1321         /*
1322          * We really want to cull the candidates list early
1323          * with cheap tests in order to avoid doing deltas.
1324          */
1325         rename_count = find_exact_renames(options);
1326         trace2_region_leave("diff", "exact renames", options->repo);
1327
1328         /* Did we only want exact renames? */
1329         if (minimum_score == MAX_SCORE)
1330                 goto cleanup;
1331
1332         num_sources = rename_src_nr;
1333
1334         if (want_copies || break_idx) {
1335                 /*
1336                  * Cull sources:
1337                  *   - remove ones corresponding to exact renames
1338                  *   - remove ones not found in relevant_sources
1339                  */
1340                 trace2_region_enter("diff", "cull after exact", options->repo);
1341                 remove_unneeded_paths_from_src(want_copies, relevant_sources);
1342                 trace2_region_leave("diff", "cull after exact", options->repo);
1343         } else {
1344                 /* Determine minimum score to match basenames */
1345                 double factor = 0.5;
1346                 char *basename_factor = getenv("GIT_BASENAME_FACTOR");
1347                 int min_basename_score;
1348
1349                 if (basename_factor)
1350                         factor = strtol(basename_factor, NULL, 10)/100.0;
1351                 assert(factor >= 0.0 && factor <= 1.0);
1352                 min_basename_score = minimum_score +
1353                         (int)(factor * (MAX_SCORE - minimum_score));
1354
1355                 /*
1356                  * Cull sources:
1357                  *   - remove ones involved in renames (found via exact match)
1358                  */
1359                 trace2_region_enter("diff", "cull after exact", options->repo);
1360                 remove_unneeded_paths_from_src(want_copies, NULL);
1361                 trace2_region_leave("diff", "cull after exact", options->repo);
1362
1363                 /* Preparation for basename-driven matching. */
1364                 trace2_region_enter("diff", "dir rename setup", options->repo);
1365                 initialize_dir_rename_info(&info, relevant_sources,
1366                                            dirs_removed, dir_rename_count);
1367                 trace2_region_leave("diff", "dir rename setup", options->repo);
1368
1369                 /* Utilize file basenames to quickly find renames. */
1370                 trace2_region_enter("diff", "basename matches", options->repo);
1371                 rename_count += find_basename_matches(options,
1372                                                       min_basename_score,
1373                                                       &info,
1374                                                       relevant_sources,
1375                                                       dirs_removed);
1376                 trace2_region_leave("diff", "basename matches", options->repo);
1377
1378                 /*
1379                  * Cull sources, again:
1380                  *   - remove ones involved in renames (found via basenames)
1381                  *   - remove ones not found in relevant_sources
1382                  * and
1383                  *   - remove ones in relevant_sources which are needed only
1384                  *     for directory renames IF no ancestory directory
1385                  *     actually needs to know any more individual path
1386                  *     renames under them
1387                  */
1388                 trace2_region_enter("diff", "cull basename", options->repo);
1389                 remove_unneeded_paths_from_src(want_copies, relevant_sources);
1390                 handle_early_known_dir_renames(&info, relevant_sources,
1391                                                dirs_removed);
1392                 trace2_region_leave("diff", "cull basename", options->repo);
1393         }
1394
1395         /* Calculate how many rename destinations are left */
1396         num_destinations = (rename_dst_nr - rename_count);
1397         num_sources = rename_src_nr; /* rename_src_nr reflects lower number */
1398
1399         /* All done? */
1400         if (!num_destinations || !num_sources)
1401                 goto cleanup;
1402
1403         switch (too_many_rename_candidates(num_destinations, num_sources,
1404                                            options)) {
1405         case 1:
1406                 goto cleanup;
1407         case 2:
1408                 options->degraded_cc_to_c = 1;
1409                 skip_unmodified = 1;
1410                 break;
1411         default:
1412                 break;
1413         }
1414
1415         trace2_region_enter("diff", "inexact renames", options->repo);
1416         if (options->show_rename_progress) {
1417                 progress = start_delayed_progress(
1418                                 _("Performing inexact rename detection"),
1419                                 (uint64_t)num_destinations * (uint64_t)num_sources);
1420         }
1421
1422         CALLOC_ARRAY(mx, st_mult(NUM_CANDIDATE_PER_DST, num_destinations));
1423         for (dst_cnt = i = 0; i < rename_dst_nr; i++) {
1424                 struct diff_filespec *two = rename_dst[i].p->two;
1425                 struct diff_score *m;
1426
1427                 if (rename_dst[i].is_rename)
1428                         continue; /* exact or basename match already handled */
1429
1430                 m = &mx[dst_cnt * NUM_CANDIDATE_PER_DST];
1431                 for (j = 0; j < NUM_CANDIDATE_PER_DST; j++)
1432                         m[j].dst = -1;
1433
1434                 for (j = 0; j < rename_src_nr; j++) {
1435                         struct diff_filespec *one = rename_src[j].p->one;
1436                         struct diff_score this_src;
1437
1438                         assert(!one->rename_used || want_copies || break_idx);
1439
1440                         if (skip_unmodified &&
1441                             diff_unmodified_pair(rename_src[j].p))
1442                                 continue;
1443
1444                         this_src.score = estimate_similarity(options->repo,
1445                                                              one, two,
1446                                                              minimum_score,
1447                                                              skip_unmodified);
1448                         this_src.name_score = basename_same(one, two);
1449                         this_src.dst = i;
1450                         this_src.src = j;
1451                         record_if_better(m, &this_src);
1452                         /*
1453                          * Once we run estimate_similarity,
1454                          * We do not need the text anymore.
1455                          */
1456                         diff_free_filespec_blob(one);
1457                         diff_free_filespec_blob(two);
1458                 }
1459                 dst_cnt++;
1460                 display_progress(progress,
1461                                  (uint64_t)dst_cnt * (uint64_t)num_sources);
1462         }
1463         stop_progress(&progress);
1464
1465         /* cost matrix sorted by most to least similar pair */
1466         STABLE_QSORT(mx, dst_cnt * NUM_CANDIDATE_PER_DST, score_compare);
1467
1468         rename_count += find_renames(mx, dst_cnt, minimum_score, 0,
1469                                      &info, dirs_removed);
1470         if (want_copies)
1471                 rename_count += find_renames(mx, dst_cnt, minimum_score, 1,
1472                                              &info, dirs_removed);
1473         free(mx);
1474         trace2_region_leave("diff", "inexact renames", options->repo);
1475
1476  cleanup:
1477         /* At this point, we have found some renames and copies and they
1478          * are recorded in rename_dst.  The original list is still in *q.
1479          */
1480         trace2_region_enter("diff", "write back to queue", options->repo);
1481         DIFF_QUEUE_CLEAR(&outq);
1482         for (i = 0; i < q->nr; i++) {
1483                 struct diff_filepair *p = q->queue[i];
1484                 struct diff_filepair *pair_to_free = NULL;
1485
1486                 if (DIFF_PAIR_UNMERGED(p)) {
1487                         diff_q(&outq, p);
1488                 }
1489                 else if (!DIFF_FILE_VALID(p->one) && DIFF_FILE_VALID(p->two)) {
1490                         /* Creation */
1491                         diff_q(&outq, p);
1492                 }
1493                 else if (DIFF_FILE_VALID(p->one) && !DIFF_FILE_VALID(p->two)) {
1494                         /*
1495                          * Deletion
1496                          *
1497                          * We would output this delete record if:
1498                          *
1499                          * (1) this is a broken delete and the counterpart
1500                          *     broken create remains in the output; or
1501                          * (2) this is not a broken delete, and rename_dst
1502                          *     does not have a rename/copy to move p->one->path
1503                          *     out of existence.
1504                          *
1505                          * Otherwise, the counterpart broken create
1506                          * has been turned into a rename-edit; or
1507                          * delete did not have a matching create to
1508                          * begin with.
1509                          */
1510                         if (DIFF_PAIR_BROKEN(p)) {
1511                                 /* broken delete */
1512                                 struct diff_rename_dst *dst = locate_rename_dst(p);
1513                                 if (!dst)
1514                                         BUG("tracking failed somehow; failed to find associated dst for broken pair");
1515                                 if (dst->is_rename)
1516                                         /* counterpart is now rename/copy */
1517                                         pair_to_free = p;
1518                         }
1519                         else {
1520                                 if (p->one->rename_used)
1521                                         /* this path remains */
1522                                         pair_to_free = p;
1523                         }
1524
1525                         if (!pair_to_free)
1526                                 diff_q(&outq, p);
1527                 }
1528                 else if (!diff_unmodified_pair(p))
1529                         /* all the usual ones need to be kept */
1530                         diff_q(&outq, p);
1531                 else
1532                         /* no need to keep unmodified pairs; FIXME: remove earlier? */
1533                         pair_to_free = p;
1534
1535                 if (pair_to_free)
1536                         diff_free_filepair(pair_to_free);
1537         }
1538         diff_debug_queue("done copying original", &outq);
1539
1540         free(q->queue);
1541         *q = outq;
1542         diff_debug_queue("done collapsing", q);
1543
1544         for (i = 0; i < rename_dst_nr; i++)
1545                 if (rename_dst[i].filespec_to_free)
1546                         free_filespec(rename_dst[i].filespec_to_free);
1547
1548         cleanup_dir_rename_info(&info, dirs_removed, dir_rename_count != NULL);
1549         FREE_AND_NULL(rename_dst);
1550         rename_dst_nr = rename_dst_alloc = 0;
1551         FREE_AND_NULL(rename_src);
1552         rename_src_nr = rename_src_alloc = 0;
1553         if (break_idx) {
1554                 strintmap_clear(break_idx);
1555                 FREE_AND_NULL(break_idx);
1556         }
1557         trace2_region_leave("diff", "write back to queue", options->repo);
1558         return;
1559 }
1560
1561 void diffcore_rename(struct diff_options *options)
1562 {
1563         diffcore_rename_extended(options, NULL, NULL, NULL);
1564 }