git-cvsserver: protect against NULL in crypt(3)
[git.git] / diffcore-rename.c
blobc95857b51ff0f19643a698d4226e03763e973d79
1 /*
3 * Copyright (C) 2005 Junio C Hamano
4 */
5 #include "cache.h"
6 #include "diff.h"
7 #include "diffcore.h"
8 #include "object-store.h"
9 #include "hashmap.h"
10 #include "progress.h"
11 #include "promisor-remote.h"
12 #include "strmap.h"
14 /* Table of rename/copy destinations */
16 static struct diff_rename_dst {
17 struct diff_filepair *p;
18 struct diff_filespec *filespec_to_free;
19 int is_rename; /* false -> just a create; true -> rename or copy */
20 } *rename_dst;
21 static int rename_dst_nr, rename_dst_alloc;
22 /* Mapping from break source pathname to break destination index */
23 static struct strintmap *break_idx = NULL;
25 static struct diff_rename_dst *locate_rename_dst(struct diff_filepair *p)
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];
33 * Returns 0 on success, -1 if we found a duplicate.
35 static int add_rename_dst(struct diff_filepair *p)
37 ALLOC_GROW(rename_dst, rename_dst_nr + 1, rename_dst_alloc);
38 rename_dst[rename_dst_nr].p = p;
39 rename_dst[rename_dst_nr].filespec_to_free = NULL;
40 rename_dst[rename_dst_nr].is_rename = 0;
41 rename_dst_nr++;
42 return 0;
45 /* Table of rename/copy src files */
46 static struct diff_rename_src {
47 struct diff_filepair *p;
48 unsigned short score; /* to remember the break score */
49 } *rename_src;
50 static int rename_src_nr, rename_src_alloc;
52 static void register_rename_src(struct diff_filepair *p)
54 if (p->broken_pair) {
55 if (!break_idx) {
56 break_idx = xmalloc(sizeof(*break_idx));
57 strintmap_init_with_options(break_idx, -1, NULL, 0);
59 strintmap_set(break_idx, p->one->path, rename_dst_nr);
62 ALLOC_GROW(rename_src, rename_src_nr + 1, rename_src_alloc);
63 rename_src[rename_src_nr].p = p;
64 rename_src[rename_src_nr].score = p->score;
65 rename_src_nr++;
68 static int basename_same(struct diff_filespec *src, struct diff_filespec *dst)
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;
79 return (!src_len || src->path[src_len - 1] == '/') &&
80 (!dst_len || dst->path[dst_len - 1] == '/');
83 struct diff_score {
84 int src; /* index in rename_src */
85 int dst; /* index in rename_dst */
86 unsigned short score;
87 short name_score;
90 struct inexact_prefetch_options {
91 struct repository *repo;
92 int skip_unmodified;
94 static void inexact_prefetch(void *prefetch_options)
96 struct inexact_prefetch_options *options = prefetch_options;
97 int i;
98 struct oid_array to_fetch = OID_ARRAY_INIT;
100 for (i = 0; i < rename_dst_nr; i++) {
101 if (rename_dst[i].p->renamed_pair)
103 * The loop in diffcore_rename() will not need these
104 * blobs, so skip prefetching.
106 continue; /* already found exact match */
107 diff_add_if_missing(options->repo, &to_fetch,
108 rename_dst[i].p->two);
110 for (i = 0; i < rename_src_nr; i++) {
111 if (options->skip_unmodified &&
112 diff_unmodified_pair(rename_src[i].p))
114 * The loop in diffcore_rename() will not need these
115 * blobs, so skip prefetching.
117 continue;
118 diff_add_if_missing(options->repo, &to_fetch,
119 rename_src[i].p->one);
121 promisor_remote_get_direct(options->repo, to_fetch.oid, to_fetch.nr);
122 oid_array_clear(&to_fetch);
125 static int estimate_similarity(struct repository *r,
126 struct diff_filespec *src,
127 struct diff_filespec *dst,
128 int minimum_score,
129 struct diff_populate_filespec_options *dpf_opt)
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.
137 * Compare them and return how similar they are, representing
138 * the score as an integer between 0 and MAX_SCORE.
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.
144 unsigned long max_size, delta_size, base_size, src_copied, literal_added;
145 int score;
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.
151 if (!S_ISREG(src->mode) || !S_ISREG(dst->mode))
152 return 0;
155 * Need to check that source and destination sizes are
156 * filled in before comparing them.
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!)
163 dpf_opt->check_size_only = 1;
165 if (!src->cnt_data &&
166 diff_populate_filespec(r, src, dpf_opt))
167 return 0;
168 if (!dst->cnt_data &&
169 diff_populate_filespec(r, dst, dpf_opt))
170 return 0;
172 max_size = ((src->size > dst->size) ? src->size : dst->size);
173 base_size = ((src->size < dst->size) ? src->size : dst->size);
174 delta_size = max_size - base_size;
176 /* We would not consider edits that change the file size so
177 * drastically. delta_size must be smaller than
178 * (MAX_SCORE-minimum_score)/MAX_SCORE * min(src->size, dst->size).
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.
184 if (max_size * (MAX_SCORE-minimum_score) < delta_size * MAX_SCORE)
185 return 0;
187 dpf_opt->check_size_only = 0;
189 if (!src->cnt_data && diff_populate_filespec(r, src, dpf_opt))
190 return 0;
191 if (!dst->cnt_data && diff_populate_filespec(r, dst, dpf_opt))
192 return 0;
194 if (diffcore_count_changes(r, src, dst,
195 &src->cnt_data, &dst->cnt_data,
196 &src_copied, &literal_added))
197 return 0;
199 /* How similar are they?
200 * what percentage of material in dst are from source?
202 if (!dst->size)
203 score = 0; /* should not happen */
204 else
205 score = (int)(src_copied * MAX_SCORE / max_size);
206 return score;
209 static void record_rename_pair(int dst_index, int src_index, int score)
211 struct diff_filepair *src = rename_src[src_index].p;
212 struct diff_filepair *dst = rename_dst[dst_index].p;
214 if (dst->renamed_pair)
215 die("internal error: dst already matched.");
217 src->one->rename_used++;
218 src->one->count++;
220 rename_dst[dst_index].filespec_to_free = dst->one;
221 rename_dst[dst_index].is_rename = 1;
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;
227 else
228 dst->score = score;
232 * We sort the rename similarity matrix with the score, in descending
233 * order (the most similar first).
235 static int score_compare(const void *a_, const void *b_)
237 const struct diff_score *a = a_, *b = b_;
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;
245 if (a->score == b->score)
246 return b->name_score - a->name_score;
248 return b->score - a->score;
251 struct file_similarity {
252 struct hashmap_entry entry;
253 int index;
254 struct diff_filespec *filespec;
257 static unsigned int hash_filespec(struct repository *r,
258 struct diff_filespec *filespec)
260 if (!filespec->oid_valid) {
261 if (diff_populate_filespec(r, filespec, NULL))
262 return 0;
263 hash_object_file(r->hash_algo, filespec->data, filespec->size,
264 "blob", &filespec->oid);
266 return oidhash(&filespec->oid);
269 static int find_identical_files(struct hashmap *srcs,
270 int dst_index,
271 struct diff_options *options)
273 int renames = 0;
274 struct diff_filespec *target = rename_dst[dst_index].p->two;
275 struct file_similarity *p, *best = NULL;
276 int i = 100, best_score = -1;
277 unsigned int hash = hash_filespec(options->repo, target);
280 * Find the best source match for specified destination.
282 p = hashmap_get_entry_from_hash(srcs, hash, NULL,
283 struct file_similarity, entry);
284 hashmap_for_each_entry_from(srcs, p, entry) {
285 int score;
286 struct diff_filespec *source = p->filespec;
288 /* False hash collision? */
289 if (!oideq(&source->oid, &target->oid))
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)
294 continue;
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;
308 /* Too many identical alternatives? Pick one */
309 if (!--i)
310 break;
312 if (best) {
313 record_rename_pair(dst_index, best->index, MAX_SCORE);
314 renames++;
316 return renames;
319 static void insert_file_table(struct repository *r,
320 struct hashmap *table, int index,
321 struct diff_filespec *filespec)
323 struct file_similarity *entry = xmalloc(sizeof(*entry));
325 entry->index = index;
326 entry->filespec = filespec;
328 hashmap_entry_init(&entry->entry, hash_filespec(r, filespec));
329 hashmap_add(table, &entry->entry);
333 * Find exact renames first.
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.
339 static int find_exact_renames(struct diff_options *options)
341 int i, renames = 0;
342 struct hashmap file_table;
344 /* Add all sources to the hash table in reverse order, because
345 * later on they will be retrieved in LIFO order.
347 hashmap_init(&file_table, NULL, NULL, rename_src_nr);
348 for (i = rename_src_nr-1; i >= 0; i--)
349 insert_file_table(options->repo,
350 &file_table, i,
351 rename_src[i].p->one);
353 /* Walk the destinations and find best source match */
354 for (i = 0; i < rename_dst_nr; i++)
355 renames += find_identical_files(&file_table, i, options);
357 /* Free the hash data structure and entries */
358 hashmap_clear_and_free(&file_table, struct file_similarity, entry);
360 return renames;
363 struct dir_rename_info {
364 struct strintmap idx_map;
365 struct strmap dir_rename_guess;
366 struct strmap *dir_rename_count;
367 struct strintmap *relevant_source_dirs;
368 unsigned setup;
371 static char *get_dirname(const char *filename)
373 char *slash = strrchr(filename, '/');
374 return slash ? xstrndup(filename, slash - filename) : xstrdup("");
377 static void dirname_munge(char *filename)
379 char *slash = strrchr(filename, '/');
380 if (!slash)
381 slash = filename;
382 *slash = '\0';
385 static const char *get_highest_rename_path(struct strintmap *counts)
387 int highest_count = 0;
388 const char *highest_destination_dir = NULL;
389 struct hashmap_iter iter;
390 struct strmap_entry *entry;
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;
400 return highest_destination_dir;
403 static char *UNKNOWN_DIR = "/"; /* placeholder -- short, illegal directory */
405 static int dir_rename_already_determinable(struct strintmap *counts)
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;
422 return first > second + unknown;
425 static void increment_count(struct dir_rename_info *info,
426 char *old_dir,
427 char *new_dir)
429 struct strintmap *counts;
430 struct strmap_entry *e;
432 /* Get the {new_dirs -> counts} mapping using old_dir */
433 e = strmap_get_entry(info->dir_rename_count, old_dir);
434 if (e) {
435 counts = e->value;
436 } else {
437 counts = xmalloc(sizeof(*counts));
438 strintmap_init_with_options(counts, 0, NULL, 1);
439 strmap_put(info->dir_rename_count, old_dir, counts);
442 /* Increment the count for new_dir */
443 strintmap_incr(counts, new_dir, 1);
446 static void update_dir_rename_counts(struct dir_rename_info *info,
447 struct strintmap *dirs_removed,
448 const char *oldname,
449 const char *newname)
451 char *old_dir;
452 char *new_dir;
453 const char new_dir_first_char = newname[0];
454 int first_time_in_loop = 1;
456 if (!info->setup)
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.
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.
476 return;
479 old_dir = xstrdup(oldname);
480 new_dir = xstrdup(newname);
482 while (1) {
483 int drd_flag = NOT_RELEVANT;
485 /* Get old_dir, skip if its directory isn't relevant. */
486 dirname_munge(old_dir);
487 if (info->relevant_source_dirs &&
488 !strintmap_contains(info->relevant_source_dirs, old_dir))
489 break;
491 /* Get new_dir */
492 dirname_munge(new_dir);
495 * When renaming
496 * "a/b/c/d/e/foo.c" -> "a/b/some/thing/else/e/foo.c"
497 * then this suggests that both
498 * a/b/c/d/e/ => a/b/some/thing/else/e/
499 * a/b/c/d/ => a/b/some/thing/else/
500 * so we want to increment counters for both. We do NOT,
501 * however, also want to suggest that there was the following
502 * rename:
503 * a/b/c/ => a/b/some/thing/
504 * so we need to quit at that point.
506 * Note the when first_time_in_loop, we only strip off the
507 * basename, and we don't care if that's different.
509 if (!first_time_in_loop) {
510 char *old_sub_dir = strchr(old_dir, '\0')+1;
511 char *new_sub_dir = strchr(new_dir, '\0')+1;
512 if (!*new_dir) {
514 * Special case when renaming to root directory,
515 * i.e. when new_dir == "". In this case, we had
516 * something like
517 * a/b/subdir => subdir
518 * and so dirname_munge() sets things up so that
519 * old_dir = "a/b\0subdir\0"
520 * new_dir = "\0ubdir\0"
521 * We didn't have a '/' to overwrite a '\0' onto
522 * in new_dir, so we have to compare differently.
524 if (new_dir_first_char != old_sub_dir[0] ||
525 strcmp(old_sub_dir+1, new_sub_dir))
526 break;
527 } else {
528 if (strcmp(old_sub_dir, new_sub_dir))
529 break;
534 * Above we suggested that we'd keep recording renames for
535 * all ancestor directories where the trailing directories
536 * matched, i.e. for
537 * "a/b/c/d/e/foo.c" -> "a/b/some/thing/else/e/foo.c"
538 * we'd increment rename counts for each of
539 * a/b/c/d/e/ => a/b/some/thing/else/e/
540 * a/b/c/d/ => a/b/some/thing/else/
541 * However, we only need the rename counts for directories
542 * in dirs_removed whose value is RELEVANT_FOR_SELF.
543 * However, we add one special case of also recording it for
544 * first_time_in_loop because find_basename_matches() can
545 * use that as a hint to find a good pairing.
547 if (dirs_removed)
548 drd_flag = strintmap_get(dirs_removed, old_dir);
549 if (drd_flag == RELEVANT_FOR_SELF || first_time_in_loop)
550 increment_count(info, old_dir, new_dir);
552 first_time_in_loop = 0;
553 if (drd_flag == NOT_RELEVANT)
554 break;
555 /* If we hit toplevel directory ("") for old or new dir, quit */
556 if (!*old_dir || !*new_dir)
557 break;
560 /* Free resources we don't need anymore */
561 free(old_dir);
562 free(new_dir);
565 static void initialize_dir_rename_info(struct dir_rename_info *info,
566 struct strintmap *relevant_sources,
567 struct strintmap *dirs_removed,
568 struct strmap *dir_rename_count,
569 struct strmap *cached_pairs)
571 struct hashmap_iter iter;
572 struct strmap_entry *entry;
573 int i;
575 if (!dirs_removed && !relevant_sources) {
576 info->setup = 0;
577 return;
579 info->setup = 1;
581 info->dir_rename_count = dir_rename_count;
582 if (!info->dir_rename_count) {
583 info->dir_rename_count = xmalloc(sizeof(*dir_rename_count));
584 strmap_init(info->dir_rename_count);
586 strintmap_init_with_options(&info->idx_map, -1, NULL, 0);
587 strmap_init_with_options(&info->dir_rename_guess, NULL, 0);
589 /* Setup info->relevant_source_dirs */
590 info->relevant_source_dirs = NULL;
591 if (dirs_removed || !relevant_sources) {
592 info->relevant_source_dirs = dirs_removed; /* might be NULL */
593 } else {
594 info->relevant_source_dirs = xmalloc(sizeof(struct strintmap));
595 strintmap_init(info->relevant_source_dirs, 0 /* unused */);
596 strintmap_for_each_entry(relevant_sources, &iter, entry) {
597 char *dirname = get_dirname(entry->key);
598 if (!dirs_removed ||
599 strintmap_contains(dirs_removed, dirname))
600 strintmap_set(info->relevant_source_dirs,
601 dirname, 0 /* value irrelevant */);
602 free(dirname);
607 * Loop setting up both info->idx_map, and doing setup of
608 * info->dir_rename_count.
610 for (i = 0; i < rename_dst_nr; ++i) {
612 * For non-renamed files, make idx_map contain mapping of
613 * filename -> index (index within rename_dst, that is)
615 if (!rename_dst[i].is_rename) {
616 char *filename = rename_dst[i].p->two->path;
617 strintmap_set(&info->idx_map, filename, i);
618 continue;
622 * For everything else (i.e. renamed files), make
623 * dir_rename_count contain a map of a map:
624 * old_directory -> {new_directory -> count}
625 * In other words, for every pair look at the directories for
626 * the old filename and the new filename and count how many
627 * times that pairing occurs.
629 update_dir_rename_counts(info, dirs_removed,
630 rename_dst[i].p->one->path,
631 rename_dst[i].p->two->path);
634 /* Add cached_pairs to counts */
635 strmap_for_each_entry(cached_pairs, &iter, entry) {
636 const char *old_name = entry->key;
637 const char *new_name = entry->value;
638 if (!new_name)
639 /* known delete; ignore it */
640 continue;
642 update_dir_rename_counts(info, dirs_removed, old_name, new_name);
646 * Now we collapse
647 * dir_rename_count: old_directory -> {new_directory -> count}
648 * down to
649 * dir_rename_guess: old_directory -> best_new_directory
650 * where best_new_directory is the one with the highest count.
652 strmap_for_each_entry(info->dir_rename_count, &iter, entry) {
653 /* entry->key is source_dir */
654 struct strintmap *counts = entry->value;
655 char *best_newdir;
657 best_newdir = xstrdup(get_highest_rename_path(counts));
658 strmap_put(&info->dir_rename_guess, entry->key,
659 best_newdir);
663 void partial_clear_dir_rename_count(struct strmap *dir_rename_count)
665 struct hashmap_iter iter;
666 struct strmap_entry *entry;
668 strmap_for_each_entry(dir_rename_count, &iter, entry) {
669 struct strintmap *counts = entry->value;
670 strintmap_clear(counts);
672 strmap_partial_clear(dir_rename_count, 1);
675 static void cleanup_dir_rename_info(struct dir_rename_info *info,
676 struct strintmap *dirs_removed,
677 int keep_dir_rename_count)
679 struct hashmap_iter iter;
680 struct strmap_entry *entry;
681 struct string_list to_remove = STRING_LIST_INIT_NODUP;
682 int i;
684 if (!info->setup)
685 return;
687 /* idx_map */
688 strintmap_clear(&info->idx_map);
690 /* dir_rename_guess */
691 strmap_clear(&info->dir_rename_guess, 1);
693 /* relevant_source_dirs */
694 if (info->relevant_source_dirs &&
695 info->relevant_source_dirs != dirs_removed) {
696 strintmap_clear(info->relevant_source_dirs);
697 FREE_AND_NULL(info->relevant_source_dirs);
700 /* dir_rename_count */
701 if (!keep_dir_rename_count) {
702 partial_clear_dir_rename_count(info->dir_rename_count);
703 strmap_clear(info->dir_rename_count, 1);
704 FREE_AND_NULL(info->dir_rename_count);
705 return;
709 * Although dir_rename_count was passed in
710 * diffcore_rename_extended() and we want to keep it around and
711 * return it to that caller, we first want to remove any counts in
712 * the maps associated with UNKNOWN_DIR entries and any data
713 * associated with directories that weren't renamed.
715 strmap_for_each_entry(info->dir_rename_count, &iter, entry) {
716 const char *source_dir = entry->key;
717 struct strintmap *counts = entry->value;
719 if (!strintmap_get(dirs_removed, source_dir)) {
720 string_list_append(&to_remove, source_dir);
721 strintmap_clear(counts);
722 continue;
725 if (strintmap_contains(counts, UNKNOWN_DIR))
726 strintmap_remove(counts, UNKNOWN_DIR);
728 for (i = 0; i < to_remove.nr; ++i)
729 strmap_remove(info->dir_rename_count,
730 to_remove.items[i].string, 1);
731 string_list_clear(&to_remove, 0);
734 static const char *get_basename(const char *filename)
737 * gitbasename() has to worry about special drives, multiple
738 * directory separator characters, trailing slashes, NULL or
739 * empty strings, etc. We only work on filenames as stored in
740 * git, and thus get to ignore all those complications.
742 const char *base = strrchr(filename, '/');
743 return base ? base + 1 : filename;
746 static int idx_possible_rename(char *filename, struct dir_rename_info *info)
749 * Our comparison of files with the same basename (see
750 * find_basename_matches() below), is only helpful when after exact
751 * rename detection we have exactly one file with a given basename
752 * among the rename sources and also only exactly one file with
753 * that basename among the rename destinations. When we have
754 * multiple files with the same basename in either set, we do not
755 * know which to compare against. However, there are some
756 * filenames that occur in large numbers (particularly
757 * build-related filenames such as 'Makefile', '.gitignore', or
758 * 'build.gradle' that potentially exist within every single
759 * subdirectory), and for performance we want to be able to quickly
760 * find renames for these files too.
762 * The reason basename comparisons are a useful heuristic was that it
763 * is common for people to move files across directories while keeping
764 * their filename the same. If we had a way of determining or even
765 * making a good educated guess about which directory these non-unique
766 * basename files had moved the file to, we could check it.
767 * Luckily...
769 * When an entire directory is in fact renamed, we have two factors
770 * helping us out:
771 * (a) the original directory disappeared giving us a hint
772 * about when we can apply an extra heuristic.
773 * (a) we often have several files within that directory and
774 * subdirectories that are renamed without changes
775 * So, rules for a heuristic:
776 * (0) If there basename matches are non-unique (the condition under
777 * which this function is called) AND
778 * (1) the directory in which the file was found has disappeared
779 * (i.e. dirs_removed is non-NULL and has a relevant entry) THEN
780 * (2) use exact renames of files within the directory to determine
781 * where the directory is likely to have been renamed to. IF
782 * there is at least one exact rename from within that
783 * directory, we can proceed.
784 * (3) If there are multiple places the directory could have been
785 * renamed to based on exact renames, ignore all but one of them.
786 * Just use the destination with the most renames going to it.
787 * (4) Check if applying that directory rename to the original file
788 * would result in a destination filename that is in the
789 * potential rename set. If so, return the index of the
790 * destination file (the index within rename_dst).
791 * (5) Compare the original file and returned destination for
792 * similarity, and if they are sufficiently similar, record the
793 * rename.
795 * This function, idx_possible_rename(), is only responsible for (4).
796 * The conditions/steps in (1)-(3) are handled via setting up
797 * dir_rename_count and dir_rename_guess in
798 * initialize_dir_rename_info(). Steps (0) and (5) are handled by
799 * the caller of this function.
801 char *old_dir, *new_dir;
802 struct strbuf new_path = STRBUF_INIT;
803 int idx;
805 if (!info->setup)
806 return -1;
808 old_dir = get_dirname(filename);
809 new_dir = strmap_get(&info->dir_rename_guess, old_dir);
810 free(old_dir);
811 if (!new_dir)
812 return -1;
814 strbuf_addstr(&new_path, new_dir);
815 strbuf_addch(&new_path, '/');
816 strbuf_addstr(&new_path, get_basename(filename));
818 idx = strintmap_get(&info->idx_map, new_path.buf);
819 strbuf_release(&new_path);
820 return idx;
823 struct basename_prefetch_options {
824 struct repository *repo;
825 struct strintmap *relevant_sources;
826 struct strintmap *sources;
827 struct strintmap *dests;
828 struct dir_rename_info *info;
830 static void basename_prefetch(void *prefetch_options)
832 struct basename_prefetch_options *options = prefetch_options;
833 struct strintmap *relevant_sources = options->relevant_sources;
834 struct strintmap *sources = options->sources;
835 struct strintmap *dests = options->dests;
836 struct dir_rename_info *info = options->info;
837 int i;
838 struct oid_array to_fetch = OID_ARRAY_INIT;
841 * TODO: The following loops mirror the code/logic from
842 * find_basename_matches(), though not quite exactly. Maybe
843 * abstract the iteration logic out somehow?
845 for (i = 0; i < rename_src_nr; ++i) {
846 char *filename = rename_src[i].p->one->path;
847 const char *base = NULL;
848 intptr_t src_index;
849 intptr_t dst_index;
851 /* Skip irrelevant sources */
852 if (relevant_sources &&
853 !strintmap_contains(relevant_sources, filename))
854 continue;
857 * If the basename is unique among remaining sources, then
858 * src_index will equal 'i' and we can attempt to match it
859 * to a unique basename in the destinations. Otherwise,
860 * use directory rename heuristics, if possible.
862 base = get_basename(filename);
863 src_index = strintmap_get(sources, base);
864 assert(src_index == -1 || src_index == i);
866 if (strintmap_contains(dests, base)) {
867 struct diff_filespec *one, *two;
869 /* Find a matching destination, if possible */
870 dst_index = strintmap_get(dests, base);
871 if (src_index == -1 || dst_index == -1) {
872 src_index = i;
873 dst_index = idx_possible_rename(filename, info);
875 if (dst_index == -1)
876 continue;
878 /* Ignore this dest if already used in a rename */
879 if (rename_dst[dst_index].is_rename)
880 continue; /* already used previously */
882 one = rename_src[src_index].p->one;
883 two = rename_dst[dst_index].p->two;
885 /* Add the pairs */
886 diff_add_if_missing(options->repo, &to_fetch, two);
887 diff_add_if_missing(options->repo, &to_fetch, one);
891 promisor_remote_get_direct(options->repo, to_fetch.oid, to_fetch.nr);
892 oid_array_clear(&to_fetch);
895 static int find_basename_matches(struct diff_options *options,
896 int minimum_score,
897 struct dir_rename_info *info,
898 struct strintmap *relevant_sources,
899 struct strintmap *dirs_removed)
902 * When I checked in early 2020, over 76% of file renames in linux
903 * just moved files to a different directory but kept the same
904 * basename. gcc did that with over 64% of renames, gecko did it
905 * with over 79%, and WebKit did it with over 89%.
907 * Therefore we can bypass the normal exhaustive NxM matrix
908 * comparison of similarities between all potential rename sources
909 * and destinations by instead using file basename as a hint (i.e.
910 * the portion of the filename after the last '/'), checking for
911 * similarity between files with the same basename, and if we find
912 * a pair that are sufficiently similar, record the rename pair and
913 * exclude those two from the NxM matrix.
915 * This *might* cause us to find a less than optimal pairing (if
916 * there is another file that we are even more similar to but has a
917 * different basename). Given the huge performance advantage
918 * basename matching provides, and given the frequency with which
919 * people use the same basename in real world projects, that's a
920 * trade-off we are willing to accept when doing just rename
921 * detection.
923 * If someone wants copy detection that implies they are willing to
924 * spend more cycles to find similarities between files, so it may
925 * be less likely that this heuristic is wanted. If someone is
926 * doing break detection, that means they do not want filename
927 * similarity to imply any form of content similiarity, and thus
928 * this heuristic would definitely be incompatible.
931 int i, renames = 0;
932 struct strintmap sources;
933 struct strintmap dests;
934 struct diff_populate_filespec_options dpf_options = {
935 .check_binary = 0,
936 .missing_object_cb = NULL,
937 .missing_object_data = NULL
939 struct basename_prefetch_options prefetch_options = {
940 .repo = options->repo,
941 .relevant_sources = relevant_sources,
942 .sources = &sources,
943 .dests = &dests,
944 .info = info
948 * Create maps of basename -> fullname(s) for remaining sources and
949 * dests.
951 strintmap_init_with_options(&sources, -1, NULL, 0);
952 strintmap_init_with_options(&dests, -1, NULL, 0);
953 for (i = 0; i < rename_src_nr; ++i) {
954 char *filename = rename_src[i].p->one->path;
955 const char *base;
957 /* exact renames removed in remove_unneeded_paths_from_src() */
958 assert(!rename_src[i].p->one->rename_used);
960 /* Record index within rename_src (i) if basename is unique */
961 base = get_basename(filename);
962 if (strintmap_contains(&sources, base))
963 strintmap_set(&sources, base, -1);
964 else
965 strintmap_set(&sources, base, i);
967 for (i = 0; i < rename_dst_nr; ++i) {
968 char *filename = rename_dst[i].p->two->path;
969 const char *base;
971 if (rename_dst[i].is_rename)
972 continue; /* involved in exact match already. */
974 /* Record index within rename_dst (i) if basename is unique */
975 base = get_basename(filename);
976 if (strintmap_contains(&dests, base))
977 strintmap_set(&dests, base, -1);
978 else
979 strintmap_set(&dests, base, i);
982 if (options->repo == the_repository && has_promisor_remote()) {
983 dpf_options.missing_object_cb = basename_prefetch;
984 dpf_options.missing_object_data = &prefetch_options;
987 /* Now look for basename matchups and do similarity estimation */
988 for (i = 0; i < rename_src_nr; ++i) {
989 char *filename = rename_src[i].p->one->path;
990 const char *base = NULL;
991 intptr_t src_index;
992 intptr_t dst_index;
994 /* Skip irrelevant sources */
995 if (relevant_sources &&
996 !strintmap_contains(relevant_sources, filename))
997 continue;
1000 * If the basename is unique among remaining sources, then
1001 * src_index will equal 'i' and we can attempt to match it
1002 * to a unique basename in the destinations. Otherwise,
1003 * use directory rename heuristics, if possible.
1005 base = get_basename(filename);
1006 src_index = strintmap_get(&sources, base);
1007 assert(src_index == -1 || src_index == i);
1009 if (strintmap_contains(&dests, base)) {
1010 struct diff_filespec *one, *two;
1011 int score;
1013 /* Find a matching destination, if possible */
1014 dst_index = strintmap_get(&dests, base);
1015 if (src_index == -1 || dst_index == -1) {
1016 src_index = i;
1017 dst_index = idx_possible_rename(filename, info);
1019 if (dst_index == -1)
1020 continue;
1022 /* Ignore this dest if already used in a rename */
1023 if (rename_dst[dst_index].is_rename)
1024 continue; /* already used previously */
1026 /* Estimate the similarity */
1027 one = rename_src[src_index].p->one;
1028 two = rename_dst[dst_index].p->two;
1029 score = estimate_similarity(options->repo, one, two,
1030 minimum_score, &dpf_options);
1032 /* If sufficiently similar, record as rename pair */
1033 if (score < minimum_score)
1034 continue;
1035 record_rename_pair(dst_index, src_index, score);
1036 renames++;
1037 update_dir_rename_counts(info, dirs_removed,
1038 one->path, two->path);
1041 * Found a rename so don't need text anymore; if we
1042 * didn't find a rename, the filespec_blob would get
1043 * re-used when doing the matrix of comparisons.
1045 diff_free_filespec_blob(one);
1046 diff_free_filespec_blob(two);
1050 strintmap_clear(&sources);
1051 strintmap_clear(&dests);
1053 return renames;
1056 #define NUM_CANDIDATE_PER_DST 4
1057 static void record_if_better(struct diff_score m[], struct diff_score *o)
1059 int i, worst;
1061 /* find the worst one */
1062 worst = 0;
1063 for (i = 1; i < NUM_CANDIDATE_PER_DST; i++)
1064 if (score_compare(&m[i], &m[worst]) > 0)
1065 worst = i;
1067 /* is it better than the worst one? */
1068 if (score_compare(&m[worst], o) > 0)
1069 m[worst] = *o;
1073 * Returns:
1074 * 0 if we are under the limit;
1075 * 1 if we need to disable inexact rename detection;
1076 * 2 if we would be under the limit if we were given -C instead of -C -C.
1078 static int too_many_rename_candidates(int num_destinations, int num_sources,
1079 struct diff_options *options)
1081 int rename_limit = options->rename_limit;
1082 int i, limited_sources;
1084 options->needed_rename_limit = 0;
1087 * This basically does a test for the rename matrix not
1088 * growing larger than a "rename_limit" square matrix, ie:
1090 * num_destinations * num_sources > rename_limit * rename_limit
1092 * We use st_mult() to check overflow conditions; in the
1093 * exceptional circumstance that size_t isn't large enough to hold
1094 * the multiplication, the system won't be able to allocate enough
1095 * memory for the matrix anyway.
1097 if (rename_limit <= 0)
1098 return 0; /* treat as unlimited */
1099 if (st_mult(num_destinations, num_sources)
1100 <= st_mult(rename_limit, rename_limit))
1101 return 0;
1103 options->needed_rename_limit =
1104 num_sources > num_destinations ? num_sources : num_destinations;
1106 /* Are we running under -C -C? */
1107 if (!options->flags.find_copies_harder)
1108 return 1;
1110 /* Would we bust the limit if we were running under -C? */
1111 for (limited_sources = i = 0; i < num_sources; i++) {
1112 if (diff_unmodified_pair(rename_src[i].p))
1113 continue;
1114 limited_sources++;
1116 if (st_mult(num_destinations, limited_sources)
1117 <= st_mult(rename_limit, rename_limit))
1118 return 2;
1119 return 1;
1122 static int find_renames(struct diff_score *mx,
1123 int dst_cnt,
1124 int minimum_score,
1125 int copies,
1126 struct dir_rename_info *info,
1127 struct strintmap *dirs_removed)
1129 int count = 0, i;
1131 for (i = 0; i < dst_cnt * NUM_CANDIDATE_PER_DST; i++) {
1132 struct diff_rename_dst *dst;
1134 if ((mx[i].dst < 0) ||
1135 (mx[i].score < minimum_score))
1136 break; /* there is no more usable pair. */
1137 dst = &rename_dst[mx[i].dst];
1138 if (dst->is_rename)
1139 continue; /* already done, either exact or fuzzy. */
1140 if (!copies && rename_src[mx[i].src].p->one->rename_used)
1141 continue;
1142 record_rename_pair(mx[i].dst, mx[i].src, mx[i].score);
1143 count++;
1144 update_dir_rename_counts(info, dirs_removed,
1145 rename_src[mx[i].src].p->one->path,
1146 rename_dst[mx[i].dst].p->two->path);
1148 return count;
1151 static void remove_unneeded_paths_from_src(int detecting_copies,
1152 struct strintmap *interesting)
1154 int i, new_num_src;
1156 if (detecting_copies && !interesting)
1157 return; /* nothing to remove */
1158 if (break_idx)
1159 return; /* culling incompatible with break detection */
1162 * Note on reasons why we cull unneeded sources but not destinations:
1163 * 1) Pairings are stored in rename_dst (not rename_src), which we
1164 * need to keep around. So, we just can't cull rename_dst even
1165 * if we wanted to. But doing so wouldn't help because...
1167 * 2) There is a matrix pairwise comparison that follows the
1168 * "Performing inexact rename detection" progress message.
1169 * Iterating over the destinations is done in the outer loop,
1170 * hence we only iterate over each of those once and we can
1171 * easily skip the outer loop early if the destination isn't
1172 * relevant. That's only one check per destination path to
1173 * skip.
1175 * By contrast, the sources are iterated in the inner loop; if
1176 * we check whether a source can be skipped, then we'll be
1177 * checking it N separate times, once for each destination.
1178 * We don't want to have to iterate over known-not-needed
1179 * sources N times each, so avoid that by removing the sources
1180 * from rename_src here.
1182 for (i = 0, new_num_src = 0; i < rename_src_nr; i++) {
1183 struct diff_filespec *one = rename_src[i].p->one;
1186 * renames are stored in rename_dst, so if a rename has
1187 * already been detected using this source, we can just
1188 * remove the source knowing rename_dst has its info.
1190 if (!detecting_copies && one->rename_used)
1191 continue;
1193 /* If we don't care about the source path, skip it */
1194 if (interesting && !strintmap_contains(interesting, one->path))
1195 continue;
1197 if (new_num_src < i)
1198 memcpy(&rename_src[new_num_src], &rename_src[i],
1199 sizeof(struct diff_rename_src));
1200 new_num_src++;
1203 rename_src_nr = new_num_src;
1206 static void handle_early_known_dir_renames(struct dir_rename_info *info,
1207 struct strintmap *relevant_sources,
1208 struct strintmap *dirs_removed)
1211 * Directory renames are determined via an aggregate of all renames
1212 * under them and using a "majority wins" rule. The fact that
1213 * "majority wins", though, means we don't need all the renames
1214 * under the given directory, we only need enough to ensure we have
1215 * a majority.
1218 int i, new_num_src;
1219 struct hashmap_iter iter;
1220 struct strmap_entry *entry;
1222 if (!dirs_removed || !relevant_sources)
1223 return; /* nothing to cull */
1224 if (break_idx)
1225 return; /* culling incompatbile with break detection */
1228 * Supplement dir_rename_count with number of potential renames,
1229 * marking all potential rename sources as mapping to UNKNOWN_DIR.
1231 for (i = 0; i < rename_src_nr; i++) {
1232 char *old_dir;
1233 struct diff_filespec *one = rename_src[i].p->one;
1236 * sources that are part of a rename will have already been
1237 * removed by a prior call to remove_unneeded_paths_from_src()
1239 assert(!one->rename_used);
1241 old_dir = get_dirname(one->path);
1242 while (*old_dir != '\0' &&
1243 NOT_RELEVANT != strintmap_get(dirs_removed, old_dir)) {
1244 char *freeme = old_dir;
1246 increment_count(info, old_dir, UNKNOWN_DIR);
1247 old_dir = get_dirname(old_dir);
1249 /* Free resources we don't need anymore */
1250 free(freeme);
1253 * old_dir and new_dir free'd in increment_count, but
1254 * get_dirname() gives us a new pointer we need to free for
1255 * old_dir. Also, if the loop runs 0 times we need old_dir
1256 * to be freed.
1258 free(old_dir);
1262 * For any directory which we need a potential rename detected for
1263 * (i.e. those marked as RELEVANT_FOR_SELF in dirs_removed), check
1264 * whether we have enough renames to satisfy the "majority rules"
1265 * requirement such that detecting any more renames of files under
1266 * it won't change the result. For any such directory, mark that
1267 * we no longer need to detect a rename for it. However, since we
1268 * might need to still detect renames for an ancestor of that
1269 * directory, use RELEVANT_FOR_ANCESTOR.
1271 strmap_for_each_entry(info->dir_rename_count, &iter, entry) {
1272 /* entry->key is source_dir */
1273 struct strintmap *counts = entry->value;
1275 if (strintmap_get(dirs_removed, entry->key) ==
1276 RELEVANT_FOR_SELF &&
1277 dir_rename_already_determinable(counts)) {
1278 strintmap_set(dirs_removed, entry->key,
1279 RELEVANT_FOR_ANCESTOR);
1283 for (i = 0, new_num_src = 0; i < rename_src_nr; i++) {
1284 struct diff_filespec *one = rename_src[i].p->one;
1285 int val;
1287 val = strintmap_get(relevant_sources, one->path);
1290 * sources that were not found in relevant_sources should
1291 * have already been removed by a prior call to
1292 * remove_unneeded_paths_from_src()
1294 assert(val != -1);
1296 if (val == RELEVANT_LOCATION) {
1297 int removable = 1;
1298 char *dir = get_dirname(one->path);
1299 while (1) {
1300 char *freeme = dir;
1301 int res = strintmap_get(dirs_removed, dir);
1303 /* Quit if not found or irrelevant */
1304 if (res == NOT_RELEVANT)
1305 break;
1306 /* If RELEVANT_FOR_SELF, can't remove */
1307 if (res == RELEVANT_FOR_SELF) {
1308 removable = 0;
1309 break;
1311 /* Else continue searching upwards */
1312 assert(res == RELEVANT_FOR_ANCESTOR);
1313 dir = get_dirname(dir);
1314 free(freeme);
1316 free(dir);
1317 if (removable) {
1318 strintmap_set(relevant_sources, one->path,
1319 RELEVANT_NO_MORE);
1320 continue;
1324 if (new_num_src < i)
1325 memcpy(&rename_src[new_num_src], &rename_src[i],
1326 sizeof(struct diff_rename_src));
1327 new_num_src++;
1330 rename_src_nr = new_num_src;
1333 void diffcore_rename_extended(struct diff_options *options,
1334 struct strintmap *relevant_sources,
1335 struct strintmap *dirs_removed,
1336 struct strmap *dir_rename_count,
1337 struct strmap *cached_pairs)
1339 int detect_rename = options->detect_rename;
1340 int minimum_score = options->rename_score;
1341 struct diff_queue_struct *q = &diff_queued_diff;
1342 struct diff_queue_struct outq;
1343 struct diff_score *mx;
1344 int i, j, rename_count, skip_unmodified = 0;
1345 int num_destinations, dst_cnt;
1346 int num_sources, want_copies;
1347 struct progress *progress = NULL;
1348 struct dir_rename_info info;
1349 struct diff_populate_filespec_options dpf_options = {
1350 .check_binary = 0,
1351 .missing_object_cb = NULL,
1352 .missing_object_data = NULL
1354 struct inexact_prefetch_options prefetch_options = {
1355 .repo = options->repo
1358 trace2_region_enter("diff", "setup", options->repo);
1359 info.setup = 0;
1360 assert(!dir_rename_count || strmap_empty(dir_rename_count));
1361 want_copies = (detect_rename == DIFF_DETECT_COPY);
1362 if (dirs_removed && (break_idx || want_copies))
1363 BUG("dirs_removed incompatible with break/copy detection");
1364 if (break_idx && relevant_sources)
1365 BUG("break detection incompatible with source specification");
1366 if (!minimum_score)
1367 minimum_score = DEFAULT_RENAME_SCORE;
1369 for (i = 0; i < q->nr; i++) {
1370 struct diff_filepair *p = q->queue[i];
1371 if (!DIFF_FILE_VALID(p->one)) {
1372 if (!DIFF_FILE_VALID(p->two))
1373 continue; /* unmerged */
1374 else if (options->single_follow &&
1375 strcmp(options->single_follow, p->two->path))
1376 continue; /* not interested */
1377 else if (!options->flags.rename_empty &&
1378 is_empty_blob_oid(&p->two->oid))
1379 continue;
1380 else if (add_rename_dst(p) < 0) {
1381 warning("skipping rename detection, detected"
1382 " duplicate destination '%s'",
1383 p->two->path);
1384 goto cleanup;
1387 else if (!options->flags.rename_empty &&
1388 is_empty_blob_oid(&p->one->oid))
1389 continue;
1390 else if (!DIFF_PAIR_UNMERGED(p) && !DIFF_FILE_VALID(p->two)) {
1392 * If the source is a broken "delete", and
1393 * they did not really want to get broken,
1394 * that means the source actually stays.
1395 * So we increment the "rename_used" score
1396 * by one, to indicate ourselves as a user
1398 if (p->broken_pair && !p->score)
1399 p->one->rename_used++;
1400 register_rename_src(p);
1402 else if (want_copies) {
1404 * Increment the "rename_used" score by
1405 * one, to indicate ourselves as a user.
1407 p->one->rename_used++;
1408 register_rename_src(p);
1411 trace2_region_leave("diff", "setup", options->repo);
1412 if (rename_dst_nr == 0 || rename_src_nr == 0)
1413 goto cleanup; /* nothing to do */
1415 trace2_region_enter("diff", "exact renames", options->repo);
1417 * We really want to cull the candidates list early
1418 * with cheap tests in order to avoid doing deltas.
1420 rename_count = find_exact_renames(options);
1421 trace2_region_leave("diff", "exact renames", options->repo);
1423 /* Did we only want exact renames? */
1424 if (minimum_score == MAX_SCORE)
1425 goto cleanup;
1427 num_sources = rename_src_nr;
1429 if (want_copies || break_idx) {
1431 * Cull sources:
1432 * - remove ones corresponding to exact renames
1433 * - remove ones not found in relevant_sources
1435 trace2_region_enter("diff", "cull after exact", options->repo);
1436 remove_unneeded_paths_from_src(want_copies, relevant_sources);
1437 trace2_region_leave("diff", "cull after exact", options->repo);
1438 } else {
1439 /* Determine minimum score to match basenames */
1440 double factor = 0.5;
1441 char *basename_factor = getenv("GIT_BASENAME_FACTOR");
1442 int min_basename_score;
1444 if (basename_factor)
1445 factor = strtol(basename_factor, NULL, 10)/100.0;
1446 assert(factor >= 0.0 && factor <= 1.0);
1447 min_basename_score = minimum_score +
1448 (int)(factor * (MAX_SCORE - minimum_score));
1451 * Cull sources:
1452 * - remove ones involved in renames (found via exact match)
1454 trace2_region_enter("diff", "cull after exact", options->repo);
1455 remove_unneeded_paths_from_src(want_copies, NULL);
1456 trace2_region_leave("diff", "cull after exact", options->repo);
1458 /* Preparation for basename-driven matching. */
1459 trace2_region_enter("diff", "dir rename setup", options->repo);
1460 initialize_dir_rename_info(&info, relevant_sources,
1461 dirs_removed, dir_rename_count,
1462 cached_pairs);
1463 trace2_region_leave("diff", "dir rename setup", options->repo);
1465 /* Utilize file basenames to quickly find renames. */
1466 trace2_region_enter("diff", "basename matches", options->repo);
1467 rename_count += find_basename_matches(options,
1468 min_basename_score,
1469 &info,
1470 relevant_sources,
1471 dirs_removed);
1472 trace2_region_leave("diff", "basename matches", options->repo);
1475 * Cull sources, again:
1476 * - remove ones involved in renames (found via basenames)
1477 * - remove ones not found in relevant_sources
1478 * and
1479 * - remove ones in relevant_sources which are needed only
1480 * for directory renames IF no ancestory directory
1481 * actually needs to know any more individual path
1482 * renames under them
1484 trace2_region_enter("diff", "cull basename", options->repo);
1485 remove_unneeded_paths_from_src(want_copies, relevant_sources);
1486 handle_early_known_dir_renames(&info, relevant_sources,
1487 dirs_removed);
1488 trace2_region_leave("diff", "cull basename", options->repo);
1491 /* Calculate how many rename destinations are left */
1492 num_destinations = (rename_dst_nr - rename_count);
1493 num_sources = rename_src_nr; /* rename_src_nr reflects lower number */
1495 /* All done? */
1496 if (!num_destinations || !num_sources)
1497 goto cleanup;
1499 switch (too_many_rename_candidates(num_destinations, num_sources,
1500 options)) {
1501 case 1:
1502 goto cleanup;
1503 case 2:
1504 options->degraded_cc_to_c = 1;
1505 skip_unmodified = 1;
1506 break;
1507 default:
1508 break;
1511 trace2_region_enter("diff", "inexact renames", options->repo);
1512 if (options->show_rename_progress) {
1513 progress = start_delayed_progress(
1514 _("Performing inexact rename detection"),
1515 (uint64_t)num_destinations * (uint64_t)num_sources);
1518 /* Finish setting up dpf_options */
1519 prefetch_options.skip_unmodified = skip_unmodified;
1520 if (options->repo == the_repository && has_promisor_remote()) {
1521 dpf_options.missing_object_cb = inexact_prefetch;
1522 dpf_options.missing_object_data = &prefetch_options;
1525 CALLOC_ARRAY(mx, st_mult(NUM_CANDIDATE_PER_DST, num_destinations));
1526 for (dst_cnt = i = 0; i < rename_dst_nr; i++) {
1527 struct diff_filespec *two = rename_dst[i].p->two;
1528 struct diff_score *m;
1530 if (rename_dst[i].is_rename)
1531 continue; /* exact or basename match already handled */
1533 m = &mx[dst_cnt * NUM_CANDIDATE_PER_DST];
1534 for (j = 0; j < NUM_CANDIDATE_PER_DST; j++)
1535 m[j].dst = -1;
1537 for (j = 0; j < rename_src_nr; j++) {
1538 struct diff_filespec *one = rename_src[j].p->one;
1539 struct diff_score this_src;
1541 assert(!one->rename_used || want_copies || break_idx);
1543 if (skip_unmodified &&
1544 diff_unmodified_pair(rename_src[j].p))
1545 continue;
1547 this_src.score = estimate_similarity(options->repo,
1548 one, two,
1549 minimum_score,
1550 &dpf_options);
1551 this_src.name_score = basename_same(one, two);
1552 this_src.dst = i;
1553 this_src.src = j;
1554 record_if_better(m, &this_src);
1556 * Once we run estimate_similarity,
1557 * We do not need the text anymore.
1559 diff_free_filespec_blob(one);
1560 diff_free_filespec_blob(two);
1562 dst_cnt++;
1563 display_progress(progress,
1564 (uint64_t)dst_cnt * (uint64_t)num_sources);
1566 stop_progress(&progress);
1568 /* cost matrix sorted by most to least similar pair */
1569 STABLE_QSORT(mx, dst_cnt * NUM_CANDIDATE_PER_DST, score_compare);
1571 rename_count += find_renames(mx, dst_cnt, minimum_score, 0,
1572 &info, dirs_removed);
1573 if (want_copies)
1574 rename_count += find_renames(mx, dst_cnt, minimum_score, 1,
1575 &info, dirs_removed);
1576 free(mx);
1577 trace2_region_leave("diff", "inexact renames", options->repo);
1579 cleanup:
1580 /* At this point, we have found some renames and copies and they
1581 * are recorded in rename_dst. The original list is still in *q.
1583 trace2_region_enter("diff", "write back to queue", options->repo);
1584 DIFF_QUEUE_CLEAR(&outq);
1585 for (i = 0; i < q->nr; i++) {
1586 struct diff_filepair *p = q->queue[i];
1587 struct diff_filepair *pair_to_free = NULL;
1589 if (DIFF_PAIR_UNMERGED(p)) {
1590 diff_q(&outq, p);
1592 else if (!DIFF_FILE_VALID(p->one) && DIFF_FILE_VALID(p->two)) {
1593 /* Creation */
1594 diff_q(&outq, p);
1596 else if (DIFF_FILE_VALID(p->one) && !DIFF_FILE_VALID(p->two)) {
1598 * Deletion
1600 * We would output this delete record if:
1602 * (1) this is a broken delete and the counterpart
1603 * broken create remains in the output; or
1604 * (2) this is not a broken delete, and rename_dst
1605 * does not have a rename/copy to move p->one->path
1606 * out of existence.
1608 * Otherwise, the counterpart broken create
1609 * has been turned into a rename-edit; or
1610 * delete did not have a matching create to
1611 * begin with.
1613 if (DIFF_PAIR_BROKEN(p)) {
1614 /* broken delete */
1615 struct diff_rename_dst *dst = locate_rename_dst(p);
1616 if (!dst)
1617 BUG("tracking failed somehow; failed to find associated dst for broken pair");
1618 if (dst->is_rename)
1619 /* counterpart is now rename/copy */
1620 pair_to_free = p;
1622 else {
1623 if (p->one->rename_used)
1624 /* this path remains */
1625 pair_to_free = p;
1628 if (!pair_to_free)
1629 diff_q(&outq, p);
1631 else if (!diff_unmodified_pair(p))
1632 /* all the usual ones need to be kept */
1633 diff_q(&outq, p);
1634 else
1635 /* no need to keep unmodified pairs */
1636 pair_to_free = p;
1638 if (pair_to_free)
1639 diff_free_filepair(pair_to_free);
1641 diff_debug_queue("done copying original", &outq);
1643 free(q->queue);
1644 *q = outq;
1645 diff_debug_queue("done collapsing", q);
1647 for (i = 0; i < rename_dst_nr; i++)
1648 if (rename_dst[i].filespec_to_free)
1649 free_filespec(rename_dst[i].filespec_to_free);
1651 cleanup_dir_rename_info(&info, dirs_removed, dir_rename_count != NULL);
1652 FREE_AND_NULL(rename_dst);
1653 rename_dst_nr = rename_dst_alloc = 0;
1654 FREE_AND_NULL(rename_src);
1655 rename_src_nr = rename_src_alloc = 0;
1656 if (break_idx) {
1657 strintmap_clear(break_idx);
1658 FREE_AND_NULL(break_idx);
1660 trace2_region_leave("diff", "write back to queue", options->repo);
1661 return;
1664 void diffcore_rename(struct diff_options *options)
1666 diffcore_rename_extended(options, NULL, NULL, NULL, NULL);