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