]> git.ipfire.org Git - thirdparty/git.git/blob - diffcore-rename.c
alloc.h: move ALLOC_GROW() functions from cache.h
[thirdparty/git.git] / diffcore-rename.c
1 /*
2 *
3 * Copyright (C) 2005 Junio C Hamano
4 */
5 #include "cache.h"
6 #include "alloc.h"
7 #include "diff.h"
8 #include "diffcore.h"
9 #include "object-store.h"
10 #include "hashmap.h"
11 #include "progress.h"
12 #include "promisor-remote.h"
13 #include "strmap.h"
14
15 /* Table of rename/copy destinations */
16
17 static struct diff_rename_dst {
18 struct diff_filepair *p;
19 struct diff_filespec *filespec_to_free;
20 int is_rename; /* false -> just a create; true -> rename or copy */
21 } *rename_dst;
22 static int rename_dst_nr, rename_dst_alloc;
23 /* Mapping from break source pathname to break destination index */
24 static struct strintmap *break_idx = NULL;
25
26 static struct diff_rename_dst *locate_rename_dst(struct diff_filepair *p)
27 {
28 /* Lookup by p->ONE->path */
29 int idx = break_idx ? strintmap_get(break_idx, p->one->path) : -1;
30 return (idx == -1) ? NULL : &rename_dst[idx];
31 }
32
33 /*
34 * Returns 0 on success, -1 if we found a duplicate.
35 */
36 static int add_rename_dst(struct diff_filepair *p)
37 {
38 ALLOC_GROW(rename_dst, rename_dst_nr + 1, rename_dst_alloc);
39 rename_dst[rename_dst_nr].p = p;
40 rename_dst[rename_dst_nr].filespec_to_free = NULL;
41 rename_dst[rename_dst_nr].is_rename = 0;
42 rename_dst_nr++;
43 return 0;
44 }
45
46 /* Table of rename/copy src files */
47 static struct diff_rename_src {
48 struct diff_filepair *p;
49 unsigned short score; /* to remember the break score */
50 } *rename_src;
51 static int rename_src_nr, rename_src_alloc;
52
53 static void register_rename_src(struct diff_filepair *p)
54 {
55 if (p->broken_pair) {
56 if (!break_idx) {
57 break_idx = xmalloc(sizeof(*break_idx));
58 strintmap_init_with_options(break_idx, -1, NULL, 0);
59 }
60 strintmap_set(break_idx, p->one->path, rename_dst_nr);
61 }
62
63 ALLOC_GROW(rename_src, rename_src_nr + 1, rename_src_alloc);
64 rename_src[rename_src_nr].p = p;
65 rename_src[rename_src_nr].score = p->score;
66 rename_src_nr++;
67 }
68
69 static int basename_same(struct diff_filespec *src, struct diff_filespec *dst)
70 {
71 int src_len = strlen(src->path), dst_len = strlen(dst->path);
72 while (src_len && dst_len) {
73 char c1 = src->path[--src_len];
74 char c2 = dst->path[--dst_len];
75 if (c1 != c2)
76 return 0;
77 if (c1 == '/')
78 return 1;
79 }
80 return (!src_len || src->path[src_len - 1] == '/') &&
81 (!dst_len || dst->path[dst_len - 1] == '/');
82 }
83
84 struct diff_score {
85 int src; /* index in rename_src */
86 int dst; /* index in rename_dst */
87 unsigned short score;
88 short name_score;
89 };
90
91 struct inexact_prefetch_options {
92 struct repository *repo;
93 int skip_unmodified;
94 };
95 static void inexact_prefetch(void *prefetch_options)
96 {
97 struct inexact_prefetch_options *options = prefetch_options;
98 int i;
99 struct oid_array to_fetch = OID_ARRAY_INIT;
100
101 for (i = 0; i < rename_dst_nr; i++) {
102 if (rename_dst[i].p->renamed_pair)
103 /*
104 * The loop in diffcore_rename() will not need these
105 * blobs, so skip prefetching.
106 */
107 continue; /* already found exact match */
108 diff_add_if_missing(options->repo, &to_fetch,
109 rename_dst[i].p->two);
110 }
111 for (i = 0; i < rename_src_nr; i++) {
112 if (options->skip_unmodified &&
113 diff_unmodified_pair(rename_src[i].p))
114 /*
115 * The loop in diffcore_rename() will not need these
116 * blobs, so skip prefetching.
117 */
118 continue;
119 diff_add_if_missing(options->repo, &to_fetch,
120 rename_src[i].p->one);
121 }
122 promisor_remote_get_direct(options->repo, to_fetch.oid, to_fetch.nr);
123 oid_array_clear(&to_fetch);
124 }
125
126 static int estimate_similarity(struct repository *r,
127 struct diff_filespec *src,
128 struct diff_filespec *dst,
129 int minimum_score,
130 struct diff_populate_filespec_options *dpf_opt)
131 {
132 /* src points at a file that existed in the original tree (or
133 * optionally a file in the destination tree) and dst points
134 * at a newly created file. They may be quite similar, in which
135 * case we want to say src is renamed to dst or src is copied into
136 * dst, and then some edit has been applied to dst.
137 *
138 * Compare them and return how similar they are, representing
139 * the score as an integer between 0 and MAX_SCORE.
140 *
141 * When there is an exact match, it is considered a better
142 * match than anything else; the destination does not even
143 * call into this function in that case.
144 */
145 unsigned long max_size, delta_size, base_size, src_copied, literal_added;
146 int score;
147
148 /* We deal only with regular files. Symlink renames are handled
149 * only when they are exact matches --- in other words, no edits
150 * after renaming.
151 */
152 if (!S_ISREG(src->mode) || !S_ISREG(dst->mode))
153 return 0;
154
155 /*
156 * Need to check that source and destination sizes are
157 * filled in before comparing them.
158 *
159 * If we already have "cnt_data" filled in, we know it's
160 * all good (avoid checking the size for zero, as that
161 * is a possible size - we really should have a flag to
162 * say whether the size is valid or not!)
163 */
164 dpf_opt->check_size_only = 1;
165
166 if (!src->cnt_data &&
167 diff_populate_filespec(r, src, dpf_opt))
168 return 0;
169 if (!dst->cnt_data &&
170 diff_populate_filespec(r, dst, dpf_opt))
171 return 0;
172
173 max_size = ((src->size > dst->size) ? src->size : dst->size);
174 base_size = ((src->size < dst->size) ? src->size : dst->size);
175 delta_size = max_size - base_size;
176
177 /* We would not consider edits that change the file size so
178 * drastically. delta_size must be smaller than
179 * (MAX_SCORE-minimum_score)/MAX_SCORE * min(src->size, dst->size).
180 *
181 * Note that base_size == 0 case is handled here already
182 * and the final score computation below would not have a
183 * divide-by-zero issue.
184 */
185 if (max_size * (MAX_SCORE-minimum_score) < delta_size * MAX_SCORE)
186 return 0;
187
188 dpf_opt->check_size_only = 0;
189
190 if (!src->cnt_data && diff_populate_filespec(r, src, dpf_opt))
191 return 0;
192 if (!dst->cnt_data && diff_populate_filespec(r, dst, dpf_opt))
193 return 0;
194
195 if (diffcore_count_changes(r, src, dst,
196 &src->cnt_data, &dst->cnt_data,
197 &src_copied, &literal_added))
198 return 0;
199
200 /* How similar are they?
201 * what percentage of material in dst are from source?
202 */
203 if (!dst->size)
204 score = 0; /* should not happen */
205 else
206 score = (int)(src_copied * MAX_SCORE / max_size);
207 return score;
208 }
209
210 static void record_rename_pair(int dst_index, int src_index, int score)
211 {
212 struct diff_filepair *src = rename_src[src_index].p;
213 struct diff_filepair *dst = rename_dst[dst_index].p;
214
215 if (dst->renamed_pair)
216 die("internal error: dst already matched.");
217
218 src->one->rename_used++;
219 src->one->count++;
220
221 rename_dst[dst_index].filespec_to_free = dst->one;
222 rename_dst[dst_index].is_rename = 1;
223
224 dst->one = src->one;
225 dst->renamed_pair = 1;
226 if (!strcmp(dst->one->path, dst->two->path))
227 dst->score = rename_src[src_index].score;
228 else
229 dst->score = score;
230 }
231
232 /*
233 * We sort the rename similarity matrix with the score, in descending
234 * order (the most similar first).
235 */
236 static int score_compare(const void *a_, const void *b_)
237 {
238 const struct diff_score *a = a_, *b = b_;
239
240 /* sink the unused ones to the bottom */
241 if (a->dst < 0)
242 return (0 <= b->dst);
243 else if (b->dst < 0)
244 return -1;
245
246 if (a->score == b->score)
247 return b->name_score - a->name_score;
248
249 return b->score - a->score;
250 }
251
252 struct file_similarity {
253 struct hashmap_entry entry;
254 int index;
255 struct diff_filespec *filespec;
256 };
257
258 static unsigned int hash_filespec(struct repository *r,
259 struct diff_filespec *filespec)
260 {
261 if (!filespec->oid_valid) {
262 if (diff_populate_filespec(r, filespec, NULL))
263 return 0;
264 hash_object_file(r->hash_algo, filespec->data, filespec->size,
265 OBJ_BLOB, &filespec->oid);
266 }
267 return oidhash(&filespec->oid);
268 }
269
270 static int find_identical_files(struct hashmap *srcs,
271 int dst_index,
272 struct diff_options *options)
273 {
274 int renames = 0;
275 struct diff_filespec *target = rename_dst[dst_index].p->two;
276 struct file_similarity *p, *best = NULL;
277 int i = 100, best_score = -1;
278 unsigned int hash = hash_filespec(options->repo, target);
279
280 /*
281 * Find the best source match for specified destination.
282 */
283 p = hashmap_get_entry_from_hash(srcs, hash, NULL,
284 struct file_similarity, entry);
285 hashmap_for_each_entry_from(srcs, p, entry) {
286 int score;
287 struct diff_filespec *source = p->filespec;
288
289 /* False hash collision? */
290 if (!oideq(&source->oid, &target->oid))
291 continue;
292 /* Non-regular files? If so, the modes must match! */
293 if (!S_ISREG(source->mode) || !S_ISREG(target->mode)) {
294 if (source->mode != target->mode)
295 continue;
296 }
297 /* Give higher scores to sources that haven't been used already */
298 score = !source->rename_used;
299 if (source->rename_used && options->detect_rename != DIFF_DETECT_COPY)
300 continue;
301 score += basename_same(source, target);
302 if (score > best_score) {
303 best = p;
304 best_score = score;
305 if (score == 2)
306 break;
307 }
308
309 /* Too many identical alternatives? Pick one */
310 if (!--i)
311 break;
312 }
313 if (best) {
314 record_rename_pair(dst_index, best->index, MAX_SCORE);
315 renames++;
316 }
317 return renames;
318 }
319
320 static void insert_file_table(struct repository *r,
321 struct mem_pool *pool,
322 struct hashmap *table, int index,
323 struct diff_filespec *filespec)
324 {
325 struct file_similarity *entry = mem_pool_alloc(pool, sizeof(*entry));
326
327 entry->index = index;
328 entry->filespec = filespec;
329
330 hashmap_entry_init(&entry->entry, hash_filespec(r, filespec));
331 hashmap_add(table, &entry->entry);
332 }
333
334 /*
335 * Find exact renames first.
336 *
337 * The first round matches up the up-to-date entries,
338 * and then during the second round we try to match
339 * cache-dirty entries as well.
340 */
341 static int find_exact_renames(struct diff_options *options,
342 struct mem_pool *pool)
343 {
344 int i, renames = 0;
345 struct hashmap file_table;
346
347 /* Add all sources to the hash table in reverse order, because
348 * later on they will be retrieved in LIFO order.
349 */
350 hashmap_init(&file_table, NULL, NULL, rename_src_nr);
351 for (i = rename_src_nr-1; i >= 0; i--)
352 insert_file_table(options->repo, pool,
353 &file_table, i,
354 rename_src[i].p->one);
355
356 /* Walk the destinations and find best source match */
357 for (i = 0; i < rename_dst_nr; i++)
358 renames += find_identical_files(&file_table, i, options);
359
360 /* Free the hash data structure (entries will be freed with the pool) */
361 hashmap_clear(&file_table);
362
363 return renames;
364 }
365
366 struct dir_rename_info {
367 struct strintmap idx_map;
368 struct strmap dir_rename_guess;
369 struct strmap *dir_rename_count;
370 struct strintmap *relevant_source_dirs;
371 unsigned setup;
372 };
373
374 static char *get_dirname(const char *filename)
375 {
376 char *slash = strrchr(filename, '/');
377 return slash ? xstrndup(filename, slash - filename) : xstrdup("");
378 }
379
380 static void dirname_munge(char *filename)
381 {
382 char *slash = strrchr(filename, '/');
383 if (!slash)
384 slash = filename;
385 *slash = '\0';
386 }
387
388 static const char *get_highest_rename_path(struct strintmap *counts)
389 {
390 int highest_count = 0;
391 const char *highest_destination_dir = NULL;
392 struct hashmap_iter iter;
393 struct strmap_entry *entry;
394
395 strintmap_for_each_entry(counts, &iter, entry) {
396 const char *destination_dir = entry->key;
397 intptr_t count = (intptr_t)entry->value;
398 if (count > highest_count) {
399 highest_count = count;
400 highest_destination_dir = destination_dir;
401 }
402 }
403 return highest_destination_dir;
404 }
405
406 static char *UNKNOWN_DIR = "/"; /* placeholder -- short, illegal directory */
407
408 static int dir_rename_already_determinable(struct strintmap *counts)
409 {
410 struct hashmap_iter iter;
411 struct strmap_entry *entry;
412 int first = 0, second = 0, unknown = 0;
413 strintmap_for_each_entry(counts, &iter, entry) {
414 const char *destination_dir = entry->key;
415 intptr_t count = (intptr_t)entry->value;
416 if (!strcmp(destination_dir, UNKNOWN_DIR)) {
417 unknown = count;
418 } else if (count >= first) {
419 second = first;
420 first = count;
421 } else if (count >= second) {
422 second = count;
423 }
424 }
425 return first > second + unknown;
426 }
427
428 static void increment_count(struct dir_rename_info *info,
429 char *old_dir,
430 char *new_dir)
431 {
432 struct strintmap *counts;
433 struct strmap_entry *e;
434
435 /* Get the {new_dirs -> counts} mapping using old_dir */
436 e = strmap_get_entry(info->dir_rename_count, old_dir);
437 if (e) {
438 counts = e->value;
439 } else {
440 counts = xmalloc(sizeof(*counts));
441 strintmap_init_with_options(counts, 0, NULL, 1);
442 strmap_put(info->dir_rename_count, old_dir, counts);
443 }
444
445 /* Increment the count for new_dir */
446 strintmap_incr(counts, new_dir, 1);
447 }
448
449 static void update_dir_rename_counts(struct dir_rename_info *info,
450 struct strintmap *dirs_removed,
451 const char *oldname,
452 const char *newname)
453 {
454 char *old_dir;
455 char *new_dir;
456 const char new_dir_first_char = newname[0];
457 int first_time_in_loop = 1;
458
459 if (!info->setup)
460 /*
461 * info->setup is 0 here in two cases: (1) all auxiliary
462 * vars (like dirs_removed) were NULL so
463 * initialize_dir_rename_info() returned early, or (2)
464 * either break detection or copy detection are active so
465 * that we never called initialize_dir_rename_info(). In
466 * the former case, we don't have enough info to know if
467 * directories were renamed (because dirs_removed lets us
468 * know about a necessary prerequisite, namely if they were
469 * removed), and in the latter, we don't care about
470 * directory renames or find_basename_matches.
471 *
472 * This matters because both basename and inexact matching
473 * will also call update_dir_rename_counts(). In either of
474 * the above two cases info->dir_rename_counts will not
475 * have been properly initialized which prevents us from
476 * updating it, but in these two cases we don't care about
477 * dir_rename_counts anyway, so we can just exit early.
478 */
479 return;
480
481
482 old_dir = xstrdup(oldname);
483 new_dir = xstrdup(newname);
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 struct strmap *cached_pairs)
573 {
574 struct hashmap_iter iter;
575 struct strmap_entry *entry;
576 int i;
577
578 if (!dirs_removed && !relevant_sources) {
579 info->setup = 0;
580 return;
581 }
582 info->setup = 1;
583
584 info->dir_rename_count = dir_rename_count;
585 if (!info->dir_rename_count) {
586 info->dir_rename_count = xmalloc(sizeof(*dir_rename_count));
587 strmap_init(info->dir_rename_count);
588 }
589 strintmap_init_with_options(&info->idx_map, -1, NULL, 0);
590 strmap_init_with_options(&info->dir_rename_guess, NULL, 0);
591
592 /* Setup info->relevant_source_dirs */
593 info->relevant_source_dirs = NULL;
594 if (dirs_removed || !relevant_sources) {
595 info->relevant_source_dirs = dirs_removed; /* might be NULL */
596 } else {
597 info->relevant_source_dirs = xmalloc(sizeof(struct strintmap));
598 strintmap_init(info->relevant_source_dirs, 0 /* unused */);
599 strintmap_for_each_entry(relevant_sources, &iter, entry) {
600 char *dirname = get_dirname(entry->key);
601 if (!dirs_removed ||
602 strintmap_contains(dirs_removed, dirname))
603 strintmap_set(info->relevant_source_dirs,
604 dirname, 0 /* value irrelevant */);
605 free(dirname);
606 }
607 }
608
609 /*
610 * Loop setting up both info->idx_map, and doing setup of
611 * info->dir_rename_count.
612 */
613 for (i = 0; i < rename_dst_nr; ++i) {
614 /*
615 * For non-renamed files, make idx_map contain mapping of
616 * filename -> index (index within rename_dst, that is)
617 */
618 if (!rename_dst[i].is_rename) {
619 char *filename = rename_dst[i].p->two->path;
620 strintmap_set(&info->idx_map, filename, i);
621 continue;
622 }
623
624 /*
625 * For everything else (i.e. renamed files), make
626 * dir_rename_count contain a map of a map:
627 * old_directory -> {new_directory -> count}
628 * In other words, for every pair look at the directories for
629 * the old filename and the new filename and count how many
630 * times that pairing occurs.
631 */
632 update_dir_rename_counts(info, dirs_removed,
633 rename_dst[i].p->one->path,
634 rename_dst[i].p->two->path);
635 }
636
637 /* Add cached_pairs to counts */
638 strmap_for_each_entry(cached_pairs, &iter, entry) {
639 const char *old_name = entry->key;
640 const char *new_name = entry->value;
641 if (!new_name)
642 /* known delete; ignore it */
643 continue;
644
645 update_dir_rename_counts(info, dirs_removed, old_name, new_name);
646 }
647
648 /*
649 * Now we collapse
650 * dir_rename_count: old_directory -> {new_directory -> count}
651 * down to
652 * dir_rename_guess: old_directory -> best_new_directory
653 * where best_new_directory is the one with the highest count.
654 */
655 strmap_for_each_entry(info->dir_rename_count, &iter, entry) {
656 /* entry->key is source_dir */
657 struct strintmap *counts = entry->value;
658 char *best_newdir;
659
660 best_newdir = xstrdup(get_highest_rename_path(counts));
661 strmap_put(&info->dir_rename_guess, entry->key,
662 best_newdir);
663 }
664 }
665
666 void partial_clear_dir_rename_count(struct strmap *dir_rename_count)
667 {
668 struct hashmap_iter iter;
669 struct strmap_entry *entry;
670
671 strmap_for_each_entry(dir_rename_count, &iter, entry) {
672 struct strintmap *counts = entry->value;
673 strintmap_clear(counts);
674 }
675 strmap_partial_clear(dir_rename_count, 1);
676 }
677
678 static void cleanup_dir_rename_info(struct dir_rename_info *info,
679 struct strintmap *dirs_removed,
680 int keep_dir_rename_count)
681 {
682 struct hashmap_iter iter;
683 struct strmap_entry *entry;
684 struct string_list to_remove = STRING_LIST_INIT_NODUP;
685 int i;
686
687 if (!info->setup)
688 return;
689
690 /* idx_map */
691 strintmap_clear(&info->idx_map);
692
693 /* dir_rename_guess */
694 strmap_clear(&info->dir_rename_guess, 1);
695
696 /* relevant_source_dirs */
697 if (info->relevant_source_dirs &&
698 info->relevant_source_dirs != dirs_removed) {
699 strintmap_clear(info->relevant_source_dirs);
700 FREE_AND_NULL(info->relevant_source_dirs);
701 }
702
703 /* dir_rename_count */
704 if (!keep_dir_rename_count) {
705 partial_clear_dir_rename_count(info->dir_rename_count);
706 strmap_clear(info->dir_rename_count, 1);
707 FREE_AND_NULL(info->dir_rename_count);
708 return;
709 }
710
711 /*
712 * Although dir_rename_count was passed in
713 * diffcore_rename_extended() and we want to keep it around and
714 * return it to that caller, we first want to remove any counts in
715 * the maps associated with UNKNOWN_DIR entries and any data
716 * associated with directories that weren't renamed.
717 */
718 strmap_for_each_entry(info->dir_rename_count, &iter, entry) {
719 const char *source_dir = entry->key;
720 struct strintmap *counts = entry->value;
721
722 if (!strintmap_get(dirs_removed, source_dir)) {
723 string_list_append(&to_remove, source_dir);
724 strintmap_clear(counts);
725 continue;
726 }
727
728 if (strintmap_contains(counts, UNKNOWN_DIR))
729 strintmap_remove(counts, UNKNOWN_DIR);
730 }
731 for (i = 0; i < to_remove.nr; ++i)
732 strmap_remove(info->dir_rename_count,
733 to_remove.items[i].string, 1);
734 string_list_clear(&to_remove, 0);
735 }
736
737 static const char *get_basename(const char *filename)
738 {
739 /*
740 * gitbasename() has to worry about special drives, multiple
741 * directory separator characters, trailing slashes, NULL or
742 * empty strings, etc. We only work on filenames as stored in
743 * git, and thus get to ignore all those complications.
744 */
745 const char *base = strrchr(filename, '/');
746 return base ? base + 1 : filename;
747 }
748
749 static int idx_possible_rename(char *filename, struct dir_rename_info *info)
750 {
751 /*
752 * Our comparison of files with the same basename (see
753 * find_basename_matches() below), is only helpful when after exact
754 * rename detection we have exactly one file with a given basename
755 * among the rename sources and also only exactly one file with
756 * that basename among the rename destinations. When we have
757 * multiple files with the same basename in either set, we do not
758 * know which to compare against. However, there are some
759 * filenames that occur in large numbers (particularly
760 * build-related filenames such as 'Makefile', '.gitignore', or
761 * 'build.gradle' that potentially exist within every single
762 * subdirectory), and for performance we want to be able to quickly
763 * find renames for these files too.
764 *
765 * The reason basename comparisons are a useful heuristic was that it
766 * is common for people to move files across directories while keeping
767 * their filename the same. If we had a way of determining or even
768 * making a good educated guess about which directory these non-unique
769 * basename files had moved the file to, we could check it.
770 * Luckily...
771 *
772 * When an entire directory is in fact renamed, we have two factors
773 * helping us out:
774 * (a) the original directory disappeared giving us a hint
775 * about when we can apply an extra heuristic.
776 * (a) we often have several files within that directory and
777 * subdirectories that are renamed without changes
778 * So, rules for a heuristic:
779 * (0) If there basename matches are non-unique (the condition under
780 * which this function is called) AND
781 * (1) the directory in which the file was found has disappeared
782 * (i.e. dirs_removed is non-NULL and has a relevant entry) THEN
783 * (2) use exact renames of files within the directory to determine
784 * where the directory is likely to have been renamed to. IF
785 * there is at least one exact rename from within that
786 * directory, we can proceed.
787 * (3) If there are multiple places the directory could have been
788 * renamed to based on exact renames, ignore all but one of them.
789 * Just use the destination with the most renames going to it.
790 * (4) Check if applying that directory rename to the original file
791 * would result in a destination filename that is in the
792 * potential rename set. If so, return the index of the
793 * destination file (the index within rename_dst).
794 * (5) Compare the original file and returned destination for
795 * similarity, and if they are sufficiently similar, record the
796 * rename.
797 *
798 * This function, idx_possible_rename(), is only responsible for (4).
799 * The conditions/steps in (1)-(3) are handled via setting up
800 * dir_rename_count and dir_rename_guess in
801 * initialize_dir_rename_info(). Steps (0) and (5) are handled by
802 * the caller of this function.
803 */
804 char *old_dir, *new_dir;
805 struct strbuf new_path = STRBUF_INIT;
806 int idx;
807
808 if (!info->setup)
809 return -1;
810
811 old_dir = get_dirname(filename);
812 new_dir = strmap_get(&info->dir_rename_guess, old_dir);
813 free(old_dir);
814 if (!new_dir)
815 return -1;
816
817 strbuf_addstr(&new_path, new_dir);
818 strbuf_addch(&new_path, '/');
819 strbuf_addstr(&new_path, get_basename(filename));
820
821 idx = strintmap_get(&info->idx_map, new_path.buf);
822 strbuf_release(&new_path);
823 return idx;
824 }
825
826 struct basename_prefetch_options {
827 struct repository *repo;
828 struct strintmap *relevant_sources;
829 struct strintmap *sources;
830 struct strintmap *dests;
831 struct dir_rename_info *info;
832 };
833 static void basename_prefetch(void *prefetch_options)
834 {
835 struct basename_prefetch_options *options = prefetch_options;
836 struct strintmap *relevant_sources = options->relevant_sources;
837 struct strintmap *sources = options->sources;
838 struct strintmap *dests = options->dests;
839 struct dir_rename_info *info = options->info;
840 int i;
841 struct oid_array to_fetch = OID_ARRAY_INIT;
842
843 /*
844 * TODO: The following loops mirror the code/logic from
845 * find_basename_matches(), though not quite exactly. Maybe
846 * abstract the iteration logic out somehow?
847 */
848 for (i = 0; i < rename_src_nr; ++i) {
849 char *filename = rename_src[i].p->one->path;
850 const char *base = NULL;
851 intptr_t src_index;
852 intptr_t dst_index;
853
854 /* Skip irrelevant sources */
855 if (relevant_sources &&
856 !strintmap_contains(relevant_sources, filename))
857 continue;
858
859 /*
860 * If the basename is unique among remaining sources, then
861 * src_index will equal 'i' and we can attempt to match it
862 * to a unique basename in the destinations. Otherwise,
863 * use directory rename heuristics, if possible.
864 */
865 base = get_basename(filename);
866 src_index = strintmap_get(sources, base);
867 assert(src_index == -1 || src_index == i);
868
869 if (strintmap_contains(dests, base)) {
870 struct diff_filespec *one, *two;
871
872 /* Find a matching destination, if possible */
873 dst_index = strintmap_get(dests, base);
874 if (src_index == -1 || dst_index == -1) {
875 src_index = i;
876 dst_index = idx_possible_rename(filename, info);
877 }
878 if (dst_index == -1)
879 continue;
880
881 /* Ignore this dest if already used in a rename */
882 if (rename_dst[dst_index].is_rename)
883 continue; /* already used previously */
884
885 one = rename_src[src_index].p->one;
886 two = rename_dst[dst_index].p->two;
887
888 /* Add the pairs */
889 diff_add_if_missing(options->repo, &to_fetch, two);
890 diff_add_if_missing(options->repo, &to_fetch, one);
891 }
892 }
893
894 promisor_remote_get_direct(options->repo, to_fetch.oid, to_fetch.nr);
895 oid_array_clear(&to_fetch);
896 }
897
898 static int find_basename_matches(struct diff_options *options,
899 int minimum_score,
900 struct dir_rename_info *info,
901 struct strintmap *relevant_sources,
902 struct strintmap *dirs_removed)
903 {
904 /*
905 * When I checked in early 2020, over 76% of file renames in linux
906 * just moved files to a different directory but kept the same
907 * basename. gcc did that with over 64% of renames, gecko did it
908 * with over 79%, and WebKit did it with over 89%.
909 *
910 * Therefore we can bypass the normal exhaustive NxM matrix
911 * comparison of similarities between all potential rename sources
912 * and destinations by instead using file basename as a hint (i.e.
913 * the portion of the filename after the last '/'), checking for
914 * similarity between files with the same basename, and if we find
915 * a pair that are sufficiently similar, record the rename pair and
916 * exclude those two from the NxM matrix.
917 *
918 * This *might* cause us to find a less than optimal pairing (if
919 * there is another file that we are even more similar to but has a
920 * different basename). Given the huge performance advantage
921 * basename matching provides, and given the frequency with which
922 * people use the same basename in real world projects, that's a
923 * trade-off we are willing to accept when doing just rename
924 * detection.
925 *
926 * If someone wants copy detection that implies they are willing to
927 * spend more cycles to find similarities between files, so it may
928 * be less likely that this heuristic is wanted. If someone is
929 * doing break detection, that means they do not want filename
930 * similarity to imply any form of content similiarity, and thus
931 * this heuristic would definitely be incompatible.
932 */
933
934 int i, renames = 0;
935 struct strintmap sources;
936 struct strintmap dests;
937 struct diff_populate_filespec_options dpf_options = {
938 .check_binary = 0,
939 .missing_object_cb = NULL,
940 .missing_object_data = NULL
941 };
942 struct basename_prefetch_options prefetch_options = {
943 .repo = options->repo,
944 .relevant_sources = relevant_sources,
945 .sources = &sources,
946 .dests = &dests,
947 .info = info
948 };
949
950 /*
951 * Create maps of basename -> fullname(s) for remaining sources and
952 * dests.
953 */
954 strintmap_init_with_options(&sources, -1, NULL, 0);
955 strintmap_init_with_options(&dests, -1, NULL, 0);
956 for (i = 0; i < rename_src_nr; ++i) {
957 char *filename = rename_src[i].p->one->path;
958 const char *base;
959
960 /* exact renames removed in remove_unneeded_paths_from_src() */
961 assert(!rename_src[i].p->one->rename_used);
962
963 /* Record index within rename_src (i) if basename is unique */
964 base = get_basename(filename);
965 if (strintmap_contains(&sources, base))
966 strintmap_set(&sources, base, -1);
967 else
968 strintmap_set(&sources, base, i);
969 }
970 for (i = 0; i < rename_dst_nr; ++i) {
971 char *filename = rename_dst[i].p->two->path;
972 const char *base;
973
974 if (rename_dst[i].is_rename)
975 continue; /* involved in exact match already. */
976
977 /* Record index within rename_dst (i) if basename is unique */
978 base = get_basename(filename);
979 if (strintmap_contains(&dests, base))
980 strintmap_set(&dests, base, -1);
981 else
982 strintmap_set(&dests, base, i);
983 }
984
985 if (options->repo == the_repository && has_promisor_remote()) {
986 dpf_options.missing_object_cb = basename_prefetch;
987 dpf_options.missing_object_data = &prefetch_options;
988 }
989
990 /* Now look for basename matchups and do similarity estimation */
991 for (i = 0; i < rename_src_nr; ++i) {
992 char *filename = rename_src[i].p->one->path;
993 const char *base = NULL;
994 intptr_t src_index;
995 intptr_t dst_index;
996
997 /* Skip irrelevant sources */
998 if (relevant_sources &&
999 !strintmap_contains(relevant_sources, filename))
1000 continue;
1001
1002 /*
1003 * If the basename is unique among remaining sources, then
1004 * src_index will equal 'i' and we can attempt to match it
1005 * to a unique basename in the destinations. Otherwise,
1006 * use directory rename heuristics, if possible.
1007 */
1008 base = get_basename(filename);
1009 src_index = strintmap_get(&sources, base);
1010 assert(src_index == -1 || src_index == i);
1011
1012 if (strintmap_contains(&dests, base)) {
1013 struct diff_filespec *one, *two;
1014 int score;
1015
1016 /* Find a matching destination, if possible */
1017 dst_index = strintmap_get(&dests, base);
1018 if (src_index == -1 || dst_index == -1) {
1019 src_index = i;
1020 dst_index = idx_possible_rename(filename, info);
1021 }
1022 if (dst_index == -1)
1023 continue;
1024
1025 /* Ignore this dest if already used in a rename */
1026 if (rename_dst[dst_index].is_rename)
1027 continue; /* already used previously */
1028
1029 /* Estimate the similarity */
1030 one = rename_src[src_index].p->one;
1031 two = rename_dst[dst_index].p->two;
1032 score = estimate_similarity(options->repo, one, two,
1033 minimum_score, &dpf_options);
1034
1035 /* If sufficiently similar, record as rename pair */
1036 if (score < minimum_score)
1037 continue;
1038 record_rename_pair(dst_index, src_index, score);
1039 renames++;
1040 update_dir_rename_counts(info, dirs_removed,
1041 one->path, two->path);
1042
1043 /*
1044 * Found a rename so don't need text anymore; if we
1045 * didn't find a rename, the filespec_blob would get
1046 * re-used when doing the matrix of comparisons.
1047 */
1048 diff_free_filespec_blob(one);
1049 diff_free_filespec_blob(two);
1050 }
1051 }
1052
1053 strintmap_clear(&sources);
1054 strintmap_clear(&dests);
1055
1056 return renames;
1057 }
1058
1059 #define NUM_CANDIDATE_PER_DST 4
1060 static void record_if_better(struct diff_score m[], struct diff_score *o)
1061 {
1062 int i, worst;
1063
1064 /* find the worst one */
1065 worst = 0;
1066 for (i = 1; i < NUM_CANDIDATE_PER_DST; i++)
1067 if (score_compare(&m[i], &m[worst]) > 0)
1068 worst = i;
1069
1070 /* is it better than the worst one? */
1071 if (score_compare(&m[worst], o) > 0)
1072 m[worst] = *o;
1073 }
1074
1075 /*
1076 * Returns:
1077 * 0 if we are under the limit;
1078 * 1 if we need to disable inexact rename detection;
1079 * 2 if we would be under the limit if we were given -C instead of -C -C.
1080 */
1081 static int too_many_rename_candidates(int num_destinations, int num_sources,
1082 struct diff_options *options)
1083 {
1084 int rename_limit = options->rename_limit;
1085 int i, limited_sources;
1086
1087 options->needed_rename_limit = 0;
1088
1089 /*
1090 * This basically does a test for the rename matrix not
1091 * growing larger than a "rename_limit" square matrix, ie:
1092 *
1093 * num_destinations * num_sources > rename_limit * rename_limit
1094 *
1095 * We use st_mult() to check overflow conditions; in the
1096 * exceptional circumstance that size_t isn't large enough to hold
1097 * the multiplication, the system won't be able to allocate enough
1098 * memory for the matrix anyway.
1099 */
1100 if (rename_limit <= 0)
1101 return 0; /* treat as unlimited */
1102 if (st_mult(num_destinations, num_sources)
1103 <= st_mult(rename_limit, rename_limit))
1104 return 0;
1105
1106 options->needed_rename_limit =
1107 num_sources > num_destinations ? num_sources : num_destinations;
1108
1109 /* Are we running under -C -C? */
1110 if (!options->flags.find_copies_harder)
1111 return 1;
1112
1113 /* Would we bust the limit if we were running under -C? */
1114 for (limited_sources = i = 0; i < num_sources; i++) {
1115 if (diff_unmodified_pair(rename_src[i].p))
1116 continue;
1117 limited_sources++;
1118 }
1119 if (st_mult(num_destinations, limited_sources)
1120 <= st_mult(rename_limit, rename_limit))
1121 return 2;
1122 return 1;
1123 }
1124
1125 static int find_renames(struct diff_score *mx,
1126 int dst_cnt,
1127 int minimum_score,
1128 int copies,
1129 struct dir_rename_info *info,
1130 struct strintmap *dirs_removed)
1131 {
1132 int count = 0, i;
1133
1134 for (i = 0; i < dst_cnt * NUM_CANDIDATE_PER_DST; i++) {
1135 struct diff_rename_dst *dst;
1136
1137 if ((mx[i].dst < 0) ||
1138 (mx[i].score < minimum_score))
1139 break; /* there is no more usable pair. */
1140 dst = &rename_dst[mx[i].dst];
1141 if (dst->is_rename)
1142 continue; /* already done, either exact or fuzzy. */
1143 if (!copies && rename_src[mx[i].src].p->one->rename_used)
1144 continue;
1145 record_rename_pair(mx[i].dst, mx[i].src, mx[i].score);
1146 count++;
1147 update_dir_rename_counts(info, dirs_removed,
1148 rename_src[mx[i].src].p->one->path,
1149 rename_dst[mx[i].dst].p->two->path);
1150 }
1151 return count;
1152 }
1153
1154 static void remove_unneeded_paths_from_src(int detecting_copies,
1155 struct strintmap *interesting)
1156 {
1157 int i, new_num_src;
1158
1159 if (detecting_copies && !interesting)
1160 return; /* nothing to remove */
1161 if (break_idx)
1162 return; /* culling incompatible with break detection */
1163
1164 /*
1165 * Note on reasons why we cull unneeded sources but not destinations:
1166 * 1) Pairings are stored in rename_dst (not rename_src), which we
1167 * need to keep around. So, we just can't cull rename_dst even
1168 * if we wanted to. But doing so wouldn't help because...
1169 *
1170 * 2) There is a matrix pairwise comparison that follows the
1171 * "Performing inexact rename detection" progress message.
1172 * Iterating over the destinations is done in the outer loop,
1173 * hence we only iterate over each of those once and we can
1174 * easily skip the outer loop early if the destination isn't
1175 * relevant. That's only one check per destination path to
1176 * skip.
1177 *
1178 * By contrast, the sources are iterated in the inner loop; if
1179 * we check whether a source can be skipped, then we'll be
1180 * checking it N separate times, once for each destination.
1181 * We don't want to have to iterate over known-not-needed
1182 * sources N times each, so avoid that by removing the sources
1183 * from rename_src here.
1184 */
1185 for (i = 0, new_num_src = 0; i < rename_src_nr; i++) {
1186 struct diff_filespec *one = rename_src[i].p->one;
1187
1188 /*
1189 * renames are stored in rename_dst, so if a rename has
1190 * already been detected using this source, we can just
1191 * remove the source knowing rename_dst has its info.
1192 */
1193 if (!detecting_copies && one->rename_used)
1194 continue;
1195
1196 /* If we don't care about the source path, skip it */
1197 if (interesting && !strintmap_contains(interesting, one->path))
1198 continue;
1199
1200 if (new_num_src < i)
1201 memcpy(&rename_src[new_num_src], &rename_src[i],
1202 sizeof(struct diff_rename_src));
1203 new_num_src++;
1204 }
1205
1206 rename_src_nr = new_num_src;
1207 }
1208
1209 static void handle_early_known_dir_renames(struct dir_rename_info *info,
1210 struct strintmap *relevant_sources,
1211 struct strintmap *dirs_removed)
1212 {
1213 /*
1214 * Directory renames are determined via an aggregate of all renames
1215 * under them and using a "majority wins" rule. The fact that
1216 * "majority wins", though, means we don't need all the renames
1217 * under the given directory, we only need enough to ensure we have
1218 * a majority.
1219 */
1220
1221 int i, new_num_src;
1222 struct hashmap_iter iter;
1223 struct strmap_entry *entry;
1224
1225 if (!dirs_removed || !relevant_sources)
1226 return; /* nothing to cull */
1227 if (break_idx)
1228 return; /* culling incompatbile with break detection */
1229
1230 /*
1231 * Supplement dir_rename_count with number of potential renames,
1232 * marking all potential rename sources as mapping to UNKNOWN_DIR.
1233 */
1234 for (i = 0; i < rename_src_nr; i++) {
1235 char *old_dir;
1236 struct diff_filespec *one = rename_src[i].p->one;
1237
1238 /*
1239 * sources that are part of a rename will have already been
1240 * removed by a prior call to remove_unneeded_paths_from_src()
1241 */
1242 assert(!one->rename_used);
1243
1244 old_dir = get_dirname(one->path);
1245 while (*old_dir != '\0' &&
1246 NOT_RELEVANT != strintmap_get(dirs_removed, old_dir)) {
1247 char *freeme = old_dir;
1248
1249 increment_count(info, old_dir, UNKNOWN_DIR);
1250 old_dir = get_dirname(old_dir);
1251
1252 /* Free resources we don't need anymore */
1253 free(freeme);
1254 }
1255 /*
1256 * old_dir and new_dir free'd in increment_count, but
1257 * get_dirname() gives us a new pointer we need to free for
1258 * old_dir. Also, if the loop runs 0 times we need old_dir
1259 * to be freed.
1260 */
1261 free(old_dir);
1262 }
1263
1264 /*
1265 * For any directory which we need a potential rename detected for
1266 * (i.e. those marked as RELEVANT_FOR_SELF in dirs_removed), check
1267 * whether we have enough renames to satisfy the "majority rules"
1268 * requirement such that detecting any more renames of files under
1269 * it won't change the result. For any such directory, mark that
1270 * we no longer need to detect a rename for it. However, since we
1271 * might need to still detect renames for an ancestor of that
1272 * directory, use RELEVANT_FOR_ANCESTOR.
1273 */
1274 strmap_for_each_entry(info->dir_rename_count, &iter, entry) {
1275 /* entry->key is source_dir */
1276 struct strintmap *counts = entry->value;
1277
1278 if (strintmap_get(dirs_removed, entry->key) ==
1279 RELEVANT_FOR_SELF &&
1280 dir_rename_already_determinable(counts)) {
1281 strintmap_set(dirs_removed, entry->key,
1282 RELEVANT_FOR_ANCESTOR);
1283 }
1284 }
1285
1286 for (i = 0, new_num_src = 0; i < rename_src_nr; i++) {
1287 struct diff_filespec *one = rename_src[i].p->one;
1288 int val;
1289
1290 val = strintmap_get(relevant_sources, one->path);
1291
1292 /*
1293 * sources that were not found in relevant_sources should
1294 * have already been removed by a prior call to
1295 * remove_unneeded_paths_from_src()
1296 */
1297 assert(val != -1);
1298
1299 if (val == RELEVANT_LOCATION) {
1300 int removable = 1;
1301 char *dir = get_dirname(one->path);
1302 while (1) {
1303 char *freeme = dir;
1304 int res = strintmap_get(dirs_removed, dir);
1305
1306 /* Quit if not found or irrelevant */
1307 if (res == NOT_RELEVANT)
1308 break;
1309 /* If RELEVANT_FOR_SELF, can't remove */
1310 if (res == RELEVANT_FOR_SELF) {
1311 removable = 0;
1312 break;
1313 }
1314 /* Else continue searching upwards */
1315 assert(res == RELEVANT_FOR_ANCESTOR);
1316 dir = get_dirname(dir);
1317 free(freeme);
1318 }
1319 free(dir);
1320 if (removable) {
1321 strintmap_set(relevant_sources, one->path,
1322 RELEVANT_NO_MORE);
1323 continue;
1324 }
1325 }
1326
1327 if (new_num_src < i)
1328 memcpy(&rename_src[new_num_src], &rename_src[i],
1329 sizeof(struct diff_rename_src));
1330 new_num_src++;
1331 }
1332
1333 rename_src_nr = new_num_src;
1334 }
1335
1336 static void free_filespec_data(struct diff_filespec *spec)
1337 {
1338 if (!--spec->count)
1339 diff_free_filespec_data(spec);
1340 }
1341
1342 static void pool_free_filespec(struct mem_pool *pool,
1343 struct diff_filespec *spec)
1344 {
1345 if (!pool) {
1346 free_filespec(spec);
1347 return;
1348 }
1349
1350 /*
1351 * Similar to free_filespec(), but only frees the data. The spec
1352 * itself was allocated in the pool and should not be individually
1353 * freed.
1354 */
1355 free_filespec_data(spec);
1356 }
1357
1358 void pool_diff_free_filepair(struct mem_pool *pool,
1359 struct diff_filepair *p)
1360 {
1361 if (!pool) {
1362 diff_free_filepair(p);
1363 return;
1364 }
1365
1366 /*
1367 * Similar to diff_free_filepair() but only frees the data from the
1368 * filespecs; not the filespecs or the filepair which were
1369 * allocated from the pool.
1370 */
1371 free_filespec_data(p->one);
1372 free_filespec_data(p->two);
1373 }
1374
1375 void diffcore_rename_extended(struct diff_options *options,
1376 struct mem_pool *pool,
1377 struct strintmap *relevant_sources,
1378 struct strintmap *dirs_removed,
1379 struct strmap *dir_rename_count,
1380 struct strmap *cached_pairs)
1381 {
1382 int detect_rename = options->detect_rename;
1383 int minimum_score = options->rename_score;
1384 struct diff_queue_struct *q = &diff_queued_diff;
1385 struct diff_queue_struct outq;
1386 struct diff_score *mx;
1387 int i, j, rename_count, skip_unmodified = 0;
1388 int num_destinations, dst_cnt;
1389 int num_sources, want_copies;
1390 struct progress *progress = NULL;
1391 struct mem_pool local_pool;
1392 struct dir_rename_info info;
1393 struct diff_populate_filespec_options dpf_options = {
1394 .check_binary = 0,
1395 .missing_object_cb = NULL,
1396 .missing_object_data = NULL
1397 };
1398 struct inexact_prefetch_options prefetch_options = {
1399 .repo = options->repo
1400 };
1401
1402 trace2_region_enter("diff", "setup", options->repo);
1403 info.setup = 0;
1404 assert(!dir_rename_count || strmap_empty(dir_rename_count));
1405 want_copies = (detect_rename == DIFF_DETECT_COPY);
1406 if (dirs_removed && (break_idx || want_copies))
1407 BUG("dirs_removed incompatible with break/copy detection");
1408 if (break_idx && relevant_sources)
1409 BUG("break detection incompatible with source specification");
1410 if (!minimum_score)
1411 minimum_score = DEFAULT_RENAME_SCORE;
1412
1413 for (i = 0; i < q->nr; i++) {
1414 struct diff_filepair *p = q->queue[i];
1415 if (!DIFF_FILE_VALID(p->one)) {
1416 if (!DIFF_FILE_VALID(p->two))
1417 continue; /* unmerged */
1418 else if (options->single_follow &&
1419 strcmp(options->single_follow, p->two->path))
1420 continue; /* not interested */
1421 else if (!options->flags.rename_empty &&
1422 is_empty_blob_oid(&p->two->oid))
1423 continue;
1424 else if (add_rename_dst(p) < 0) {
1425 warning("skipping rename detection, detected"
1426 " duplicate destination '%s'",
1427 p->two->path);
1428 goto cleanup;
1429 }
1430 }
1431 else if (!options->flags.rename_empty &&
1432 is_empty_blob_oid(&p->one->oid))
1433 continue;
1434 else if (!DIFF_PAIR_UNMERGED(p) && !DIFF_FILE_VALID(p->two)) {
1435 /*
1436 * If the source is a broken "delete", and
1437 * they did not really want to get broken,
1438 * that means the source actually stays.
1439 * So we increment the "rename_used" score
1440 * by one, to indicate ourselves as a user
1441 */
1442 if (p->broken_pair && !p->score)
1443 p->one->rename_used++;
1444 register_rename_src(p);
1445 }
1446 else if (want_copies) {
1447 /*
1448 * Increment the "rename_used" score by
1449 * one, to indicate ourselves as a user.
1450 */
1451 p->one->rename_used++;
1452 register_rename_src(p);
1453 }
1454 }
1455 trace2_region_leave("diff", "setup", options->repo);
1456 if (rename_dst_nr == 0 || rename_src_nr == 0)
1457 goto cleanup; /* nothing to do */
1458
1459 trace2_region_enter("diff", "exact renames", options->repo);
1460 mem_pool_init(&local_pool, 32*1024);
1461 /*
1462 * We really want to cull the candidates list early
1463 * with cheap tests in order to avoid doing deltas.
1464 */
1465 rename_count = find_exact_renames(options, &local_pool);
1466 /*
1467 * Discard local_pool immediately instead of at "cleanup:" in order
1468 * to reduce maximum memory usage; inexact rename detection uses up
1469 * a fair amount of memory, and mem_pools can too.
1470 */
1471 mem_pool_discard(&local_pool, 0);
1472 trace2_region_leave("diff", "exact renames", options->repo);
1473
1474 /* Did we only want exact renames? */
1475 if (minimum_score == MAX_SCORE)
1476 goto cleanup;
1477
1478 num_sources = rename_src_nr;
1479
1480 if (want_copies || break_idx) {
1481 /*
1482 * Cull sources:
1483 * - remove ones corresponding to exact renames
1484 * - remove ones not found in relevant_sources
1485 */
1486 trace2_region_enter("diff", "cull after exact", options->repo);
1487 remove_unneeded_paths_from_src(want_copies, relevant_sources);
1488 trace2_region_leave("diff", "cull after exact", options->repo);
1489 } else {
1490 /* Determine minimum score to match basenames */
1491 double factor = 0.5;
1492 char *basename_factor = getenv("GIT_BASENAME_FACTOR");
1493 int min_basename_score;
1494
1495 if (basename_factor)
1496 factor = strtol(basename_factor, NULL, 10)/100.0;
1497 assert(factor >= 0.0 && factor <= 1.0);
1498 min_basename_score = minimum_score +
1499 (int)(factor * (MAX_SCORE - minimum_score));
1500
1501 /*
1502 * Cull sources:
1503 * - remove ones involved in renames (found via exact match)
1504 */
1505 trace2_region_enter("diff", "cull after exact", options->repo);
1506 remove_unneeded_paths_from_src(want_copies, NULL);
1507 trace2_region_leave("diff", "cull after exact", options->repo);
1508
1509 /* Preparation for basename-driven matching. */
1510 trace2_region_enter("diff", "dir rename setup", options->repo);
1511 initialize_dir_rename_info(&info, relevant_sources,
1512 dirs_removed, dir_rename_count,
1513 cached_pairs);
1514 trace2_region_leave("diff", "dir rename setup", options->repo);
1515
1516 /* Utilize file basenames to quickly find renames. */
1517 trace2_region_enter("diff", "basename matches", options->repo);
1518 rename_count += find_basename_matches(options,
1519 min_basename_score,
1520 &info,
1521 relevant_sources,
1522 dirs_removed);
1523 trace2_region_leave("diff", "basename matches", options->repo);
1524
1525 /*
1526 * Cull sources, again:
1527 * - remove ones involved in renames (found via basenames)
1528 * - remove ones not found in relevant_sources
1529 * and
1530 * - remove ones in relevant_sources which are needed only
1531 * for directory renames IF no ancestory directory
1532 * actually needs to know any more individual path
1533 * renames under them
1534 */
1535 trace2_region_enter("diff", "cull basename", options->repo);
1536 remove_unneeded_paths_from_src(want_copies, relevant_sources);
1537 handle_early_known_dir_renames(&info, relevant_sources,
1538 dirs_removed);
1539 trace2_region_leave("diff", "cull basename", options->repo);
1540 }
1541
1542 /* Calculate how many rename destinations are left */
1543 num_destinations = (rename_dst_nr - rename_count);
1544 num_sources = rename_src_nr; /* rename_src_nr reflects lower number */
1545
1546 /* All done? */
1547 if (!num_destinations || !num_sources)
1548 goto cleanup;
1549
1550 switch (too_many_rename_candidates(num_destinations, num_sources,
1551 options)) {
1552 case 1:
1553 goto cleanup;
1554 case 2:
1555 options->degraded_cc_to_c = 1;
1556 skip_unmodified = 1;
1557 break;
1558 default:
1559 break;
1560 }
1561
1562 trace2_region_enter("diff", "inexact renames", options->repo);
1563 if (options->show_rename_progress) {
1564 progress = start_delayed_progress(
1565 _("Performing inexact rename detection"),
1566 (uint64_t)num_destinations * (uint64_t)num_sources);
1567 }
1568
1569 /* Finish setting up dpf_options */
1570 prefetch_options.skip_unmodified = skip_unmodified;
1571 if (options->repo == the_repository && has_promisor_remote()) {
1572 dpf_options.missing_object_cb = inexact_prefetch;
1573 dpf_options.missing_object_data = &prefetch_options;
1574 }
1575
1576 CALLOC_ARRAY(mx, st_mult(NUM_CANDIDATE_PER_DST, num_destinations));
1577 for (dst_cnt = i = 0; i < rename_dst_nr; i++) {
1578 struct diff_filespec *two = rename_dst[i].p->two;
1579 struct diff_score *m;
1580
1581 if (rename_dst[i].is_rename)
1582 continue; /* exact or basename match already handled */
1583
1584 m = &mx[dst_cnt * NUM_CANDIDATE_PER_DST];
1585 for (j = 0; j < NUM_CANDIDATE_PER_DST; j++)
1586 m[j].dst = -1;
1587
1588 for (j = 0; j < rename_src_nr; j++) {
1589 struct diff_filespec *one = rename_src[j].p->one;
1590 struct diff_score this_src;
1591
1592 assert(!one->rename_used || want_copies || break_idx);
1593
1594 if (skip_unmodified &&
1595 diff_unmodified_pair(rename_src[j].p))
1596 continue;
1597
1598 this_src.score = estimate_similarity(options->repo,
1599 one, two,
1600 minimum_score,
1601 &dpf_options);
1602 this_src.name_score = basename_same(one, two);
1603 this_src.dst = i;
1604 this_src.src = j;
1605 record_if_better(m, &this_src);
1606 /*
1607 * Once we run estimate_similarity,
1608 * We do not need the text anymore.
1609 */
1610 diff_free_filespec_blob(one);
1611 diff_free_filespec_blob(two);
1612 }
1613 dst_cnt++;
1614 display_progress(progress,
1615 (uint64_t)dst_cnt * (uint64_t)num_sources);
1616 }
1617 stop_progress(&progress);
1618
1619 /* cost matrix sorted by most to least similar pair */
1620 STABLE_QSORT(mx, dst_cnt * NUM_CANDIDATE_PER_DST, score_compare);
1621
1622 rename_count += find_renames(mx, dst_cnt, minimum_score, 0,
1623 &info, dirs_removed);
1624 if (want_copies)
1625 rename_count += find_renames(mx, dst_cnt, minimum_score, 1,
1626 &info, dirs_removed);
1627 free(mx);
1628 trace2_region_leave("diff", "inexact renames", options->repo);
1629
1630 cleanup:
1631 /* At this point, we have found some renames and copies and they
1632 * are recorded in rename_dst. The original list is still in *q.
1633 */
1634 trace2_region_enter("diff", "write back to queue", options->repo);
1635 DIFF_QUEUE_CLEAR(&outq);
1636 for (i = 0; i < q->nr; i++) {
1637 struct diff_filepair *p = q->queue[i];
1638 struct diff_filepair *pair_to_free = NULL;
1639
1640 if (DIFF_PAIR_UNMERGED(p)) {
1641 diff_q(&outq, p);
1642 }
1643 else if (!DIFF_FILE_VALID(p->one) && DIFF_FILE_VALID(p->two)) {
1644 /* Creation */
1645 diff_q(&outq, p);
1646 }
1647 else if (DIFF_FILE_VALID(p->one) && !DIFF_FILE_VALID(p->two)) {
1648 /*
1649 * Deletion
1650 *
1651 * We would output this delete record if:
1652 *
1653 * (1) this is a broken delete and the counterpart
1654 * broken create remains in the output; or
1655 * (2) this is not a broken delete, and rename_dst
1656 * does not have a rename/copy to move p->one->path
1657 * out of existence.
1658 *
1659 * Otherwise, the counterpart broken create
1660 * has been turned into a rename-edit; or
1661 * delete did not have a matching create to
1662 * begin with.
1663 */
1664 if (DIFF_PAIR_BROKEN(p)) {
1665 /* broken delete */
1666 struct diff_rename_dst *dst = locate_rename_dst(p);
1667 if (!dst)
1668 BUG("tracking failed somehow; failed to find associated dst for broken pair");
1669 if (dst->is_rename)
1670 /* counterpart is now rename/copy */
1671 pair_to_free = p;
1672 }
1673 else {
1674 if (p->one->rename_used)
1675 /* this path remains */
1676 pair_to_free = p;
1677 }
1678
1679 if (!pair_to_free)
1680 diff_q(&outq, p);
1681 }
1682 else if (!diff_unmodified_pair(p))
1683 /* all the usual ones need to be kept */
1684 diff_q(&outq, p);
1685 else
1686 /* no need to keep unmodified pairs */
1687 pair_to_free = p;
1688
1689 if (pair_to_free)
1690 pool_diff_free_filepair(pool, pair_to_free);
1691 }
1692 diff_debug_queue("done copying original", &outq);
1693
1694 free(q->queue);
1695 *q = outq;
1696 diff_debug_queue("done collapsing", q);
1697
1698 for (i = 0; i < rename_dst_nr; i++)
1699 if (rename_dst[i].filespec_to_free)
1700 pool_free_filespec(pool, rename_dst[i].filespec_to_free);
1701
1702 cleanup_dir_rename_info(&info, dirs_removed, dir_rename_count != NULL);
1703 FREE_AND_NULL(rename_dst);
1704 rename_dst_nr = rename_dst_alloc = 0;
1705 FREE_AND_NULL(rename_src);
1706 rename_src_nr = rename_src_alloc = 0;
1707 if (break_idx) {
1708 strintmap_clear(break_idx);
1709 FREE_AND_NULL(break_idx);
1710 }
1711 trace2_region_leave("diff", "write back to queue", options->repo);
1712 return;
1713 }
1714
1715 void diffcore_rename(struct diff_options *options)
1716 {
1717 diffcore_rename_extended(options, NULL, NULL, NULL, NULL, NULL);
1718 }