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