3 * Copyright (C) 2005 Junio C Hamano
8 #include "object-store.h"
11 #include "promisor-remote.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 */
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;
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 */
50 static int rename_src_nr, rename_src_alloc;
52 static void register_rename_src(struct diff_filepair *p)
56 break_idx = xmalloc(sizeof(*break_idx));
57 strintmap_init(break_idx, -1);
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;
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];
79 return (!src_len || src->path[src_len - 1] == '/') &&
80 (!dst_len || dst->path[dst_len - 1] == '/');
84 int src; /* index in rename_src */
85 int dst; /* index in rename_dst */
90 struct prefetch_options {
91 struct repository *repo;
94 static void prefetch(void *prefetch_options)
96 struct prefetch_options *options = prefetch_options;
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.
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,
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;
146 struct diff_populate_filespec_options dpf_options = {
149 struct prefetch_options prefetch_options = {r, skip_unmodified};
151 if (r == the_repository && has_promisor_remote()) {
152 dpf_options.missing_object_cb = prefetch;
153 dpf_options.missing_object_data = &prefetch_options;
156 /* We deal only with regular files. Symlink renames are handled
157 * only when they are exact matches --- in other words, no edits
160 if (!S_ISREG(src->mode) || !S_ISREG(dst->mode))
164 * Need to check that source and destination sizes are
165 * filled in before comparing them.
167 * If we already have "cnt_data" filled in, we know it's
168 * all good (avoid checking the size for zero, as that
169 * is a possible size - we really should have a flag to
170 * say whether the size is valid or not!)
172 if (!src->cnt_data &&
173 diff_populate_filespec(r, src, &dpf_options))
175 if (!dst->cnt_data &&
176 diff_populate_filespec(r, dst, &dpf_options))
179 max_size = ((src->size > dst->size) ? src->size : dst->size);
180 base_size = ((src->size < dst->size) ? src->size : dst->size);
181 delta_size = max_size - base_size;
183 /* We would not consider edits that change the file size so
184 * drastically. delta_size must be smaller than
185 * (MAX_SCORE-minimum_score)/MAX_SCORE * min(src->size, dst->size).
187 * Note that base_size == 0 case is handled here already
188 * and the final score computation below would not have a
189 * divide-by-zero issue.
191 if (max_size * (MAX_SCORE-minimum_score) < delta_size * MAX_SCORE)
194 dpf_options.check_size_only = 0;
196 if (!src->cnt_data && diff_populate_filespec(r, src, &dpf_options))
198 if (!dst->cnt_data && diff_populate_filespec(r, dst, &dpf_options))
201 if (diffcore_count_changes(r, src, dst,
202 &src->cnt_data, &dst->cnt_data,
203 &src_copied, &literal_added))
206 /* How similar are they?
207 * what percentage of material in dst are from source?
210 score = 0; /* should not happen */
212 score = (int)(src_copied * MAX_SCORE / max_size);
216 static void record_rename_pair(int dst_index, int src_index, int score)
218 struct diff_filepair *src = rename_src[src_index].p;
219 struct diff_filepair *dst = rename_dst[dst_index].p;
221 if (dst->renamed_pair)
222 die("internal error: dst already matched.");
224 src->one->rename_used++;
227 rename_dst[dst_index].filespec_to_free = dst->one;
228 rename_dst[dst_index].is_rename = 1;
231 dst->renamed_pair = 1;
232 if (!strcmp(dst->one->path, dst->two->path))
233 dst->score = rename_src[src_index].score;
239 * We sort the rename similarity matrix with the score, in descending
240 * order (the most similar first).
242 static int score_compare(const void *a_, const void *b_)
244 const struct diff_score *a = a_, *b = b_;
246 /* sink the unused ones to the bottom */
248 return (0 <= b->dst);
252 if (a->score == b->score)
253 return b->name_score - a->name_score;
255 return b->score - a->score;
258 struct file_similarity {
259 struct hashmap_entry entry;
261 struct diff_filespec *filespec;
264 static unsigned int hash_filespec(struct repository *r,
265 struct diff_filespec *filespec)
267 if (!filespec->oid_valid) {
268 if (diff_populate_filespec(r, filespec, NULL))
270 hash_object_file(r->hash_algo, filespec->data, filespec->size,
271 "blob", &filespec->oid);
273 return oidhash(&filespec->oid);
276 static int find_identical_files(struct hashmap *srcs,
278 struct diff_options *options)
281 struct diff_filespec *target = rename_dst[dst_index].p->two;
282 struct file_similarity *p, *best = NULL;
283 int i = 100, best_score = -1;
284 unsigned int hash = hash_filespec(options->repo, target);
287 * Find the best source match for specified destination.
289 p = hashmap_get_entry_from_hash(srcs, hash, NULL,
290 struct file_similarity, entry);
291 hashmap_for_each_entry_from(srcs, p, entry) {
293 struct diff_filespec *source = p->filespec;
295 /* False hash collision? */
296 if (!oideq(&source->oid, &target->oid))
298 /* Non-regular files? If so, the modes must match! */
299 if (!S_ISREG(source->mode) || !S_ISREG(target->mode)) {
300 if (source->mode != target->mode)
303 /* Give higher scores to sources that haven't been used already */
304 score = !source->rename_used;
305 if (source->rename_used && options->detect_rename != DIFF_DETECT_COPY)
307 score += basename_same(source, target);
308 if (score > best_score) {
315 /* Too many identical alternatives? Pick one */
320 record_rename_pair(dst_index, best->index, MAX_SCORE);
326 static void insert_file_table(struct repository *r,
327 struct hashmap *table, int index,
328 struct diff_filespec *filespec)
330 struct file_similarity *entry = xmalloc(sizeof(*entry));
332 entry->index = index;
333 entry->filespec = filespec;
335 hashmap_entry_init(&entry->entry, hash_filespec(r, filespec));
336 hashmap_add(table, &entry->entry);
340 * Find exact renames first.
342 * The first round matches up the up-to-date entries,
343 * and then during the second round we try to match
344 * cache-dirty entries as well.
346 static int find_exact_renames(struct diff_options *options)
349 struct hashmap file_table;
351 /* Add all sources to the hash table in reverse order, because
352 * later on they will be retrieved in LIFO order.
354 hashmap_init(&file_table, NULL, NULL, rename_src_nr);
355 for (i = rename_src_nr-1; i >= 0; i--)
356 insert_file_table(options->repo,
358 rename_src[i].p->one);
360 /* Walk the destinations and find best source match */
361 for (i = 0; i < rename_dst_nr; i++)
362 renames += find_identical_files(&file_table, i, options);
364 /* Free the hash data structure and entries */
365 hashmap_clear_and_free(&file_table, struct file_similarity, entry);
370 struct dir_rename_info {
371 struct strintmap idx_map;
372 struct strmap dir_rename_guess;
373 struct strmap *dir_rename_count;
374 struct strintmap *relevant_source_dirs;
378 static char *get_dirname(const char *filename)
380 char *slash = strrchr(filename, '/');
381 return slash ? xstrndup(filename, slash - filename) : xstrdup("");
384 static void dirname_munge(char *filename)
386 char *slash = strrchr(filename, '/');
392 static const char *get_highest_rename_path(struct strintmap *counts)
394 int highest_count = 0;
395 const char *highest_destination_dir = NULL;
396 struct hashmap_iter iter;
397 struct strmap_entry *entry;
399 strintmap_for_each_entry(counts, &iter, entry) {
400 const char *destination_dir = entry->key;
401 intptr_t count = (intptr_t)entry->value;
402 if (count > highest_count) {
403 highest_count = count;
404 highest_destination_dir = destination_dir;
407 return highest_destination_dir;
410 static void increment_count(struct dir_rename_info *info,
414 struct strintmap *counts;
415 struct strmap_entry *e;
417 /* Get the {new_dirs -> counts} mapping using old_dir */
418 e = strmap_get_entry(info->dir_rename_count, old_dir);
422 counts = xmalloc(sizeof(*counts));
423 strintmap_init_with_options(counts, 0, NULL, 1);
424 strmap_put(info->dir_rename_count, old_dir, counts);
427 /* Increment the count for new_dir */
428 strintmap_incr(counts, new_dir, 1);
431 static void update_dir_rename_counts(struct dir_rename_info *info,
432 struct strintmap *dirs_removed,
436 char *old_dir = xstrdup(oldname);
437 char *new_dir = xstrdup(newname);
438 char new_dir_first_char = new_dir[0];
439 int first_time_in_loop = 1;
443 * info->setup is 0 here in two cases: (1) all auxiliary
444 * vars (like dirs_removed) were NULL so
445 * initialize_dir_rename_info() returned early, or (2)
446 * either break detection or copy detection are active so
447 * that we never called initialize_dir_rename_info(). In
448 * the former case, we don't have enough info to know if
449 * directories were renamed (because dirs_removed lets us
450 * know about a necessary prerequisite, namely if they were
451 * removed), and in the latter, we don't care about
452 * directory renames or find_basename_matches.
454 * This matters because both basename and inexact matching
455 * will also call update_dir_rename_counts(). In either of
456 * the above two cases info->dir_rename_counts will not
457 * have been properly initialized which prevents us from
458 * updating it, but in these two cases we don't care about
459 * dir_rename_counts anyway, so we can just exit early.
464 /* Get old_dir, skip if its directory isn't relevant. */
465 dirname_munge(old_dir);
466 if (info->relevant_source_dirs &&
467 !strintmap_contains(info->relevant_source_dirs, old_dir))
471 dirname_munge(new_dir);
475 * "a/b/c/d/e/foo.c" -> "a/b/some/thing/else/e/foo.c"
476 * then this suggests that both
477 * a/b/c/d/e/ => a/b/some/thing/else/e/
478 * a/b/c/d/ => a/b/some/thing/else/
479 * so we want to increment counters for both. We do NOT,
480 * however, also want to suggest that there was the following
482 * a/b/c/ => a/b/some/thing/
483 * so we need to quit at that point.
485 * Note the when first_time_in_loop, we only strip off the
486 * basename, and we don't care if that's different.
488 if (!first_time_in_loop) {
489 char *old_sub_dir = strchr(old_dir, '\0')+1;
490 char *new_sub_dir = strchr(new_dir, '\0')+1;
493 * Special case when renaming to root directory,
494 * i.e. when new_dir == "". In this case, we had
496 * a/b/subdir => subdir
497 * and so dirname_munge() sets things up so that
498 * old_dir = "a/b\0subdir\0"
499 * new_dir = "\0ubdir\0"
500 * We didn't have a '/' to overwrite a '\0' onto
501 * in new_dir, so we have to compare differently.
503 if (new_dir_first_char != old_sub_dir[0] ||
504 strcmp(old_sub_dir+1, new_sub_dir))
507 if (strcmp(old_sub_dir, new_sub_dir))
512 if (strintmap_contains(dirs_removed, old_dir))
513 increment_count(info, old_dir, new_dir);
517 /* If we hit toplevel directory ("") for old or new dir, quit */
518 if (!*old_dir || !*new_dir)
521 first_time_in_loop = 0;
524 /* Free resources we don't need anymore */
529 static void initialize_dir_rename_info(struct dir_rename_info *info,
530 struct strintmap *relevant_sources,
531 struct strintmap *dirs_removed,
532 struct strmap *dir_rename_count)
534 struct hashmap_iter iter;
535 struct strmap_entry *entry;
538 if (!dirs_removed && !relevant_sources) {
544 info->dir_rename_count = dir_rename_count;
545 if (!info->dir_rename_count) {
546 info->dir_rename_count = xmalloc(sizeof(*dir_rename_count));
547 strmap_init(info->dir_rename_count);
549 strintmap_init_with_options(&info->idx_map, -1, NULL, 0);
550 strmap_init_with_options(&info->dir_rename_guess, NULL, 0);
552 /* Setup info->relevant_source_dirs */
553 info->relevant_source_dirs = NULL;
554 if (dirs_removed || !relevant_sources) {
555 info->relevant_source_dirs = dirs_removed; /* might be NULL */
557 info->relevant_source_dirs = xmalloc(sizeof(struct strintmap));
558 strintmap_init(info->relevant_source_dirs, 0 /* unused */);
559 strintmap_for_each_entry(relevant_sources, &iter, entry) {
560 char *dirname = get_dirname(entry->key);
562 strintmap_contains(dirs_removed, dirname))
563 strintmap_set(info->relevant_source_dirs,
564 dirname, 0 /* value irrelevant */);
570 * Loop setting up both info->idx_map, and doing setup of
571 * info->dir_rename_count.
573 for (i = 0; i < rename_dst_nr; ++i) {
575 * For non-renamed files, make idx_map contain mapping of
576 * filename -> index (index within rename_dst, that is)
578 if (!rename_dst[i].is_rename) {
579 char *filename = rename_dst[i].p->two->path;
580 strintmap_set(&info->idx_map, filename, i);
585 * For everything else (i.e. renamed files), make
586 * dir_rename_count contain a map of a map:
587 * old_directory -> {new_directory -> count}
588 * In other words, for every pair look at the directories for
589 * the old filename and the new filename and count how many
590 * times that pairing occurs.
592 update_dir_rename_counts(info, dirs_removed,
593 rename_dst[i].p->one->path,
594 rename_dst[i].p->two->path);
599 * dir_rename_count: old_directory -> {new_directory -> count}
601 * dir_rename_guess: old_directory -> best_new_directory
602 * where best_new_directory is the one with the highest count.
604 strmap_for_each_entry(info->dir_rename_count, &iter, entry) {
605 /* entry->key is source_dir */
606 struct strintmap *counts = entry->value;
609 best_newdir = xstrdup(get_highest_rename_path(counts));
610 strmap_put(&info->dir_rename_guess, entry->key,
615 void partial_clear_dir_rename_count(struct strmap *dir_rename_count)
617 struct hashmap_iter iter;
618 struct strmap_entry *entry;
620 strmap_for_each_entry(dir_rename_count, &iter, entry) {
621 struct strintmap *counts = entry->value;
622 strintmap_clear(counts);
624 strmap_partial_clear(dir_rename_count, 1);
627 static void cleanup_dir_rename_info(struct dir_rename_info *info,
628 struct strintmap *dirs_removed,
629 int keep_dir_rename_count)
631 struct hashmap_iter iter;
632 struct strmap_entry *entry;
633 struct string_list to_remove = STRING_LIST_INIT_NODUP;
640 strintmap_clear(&info->idx_map);
642 /* dir_rename_guess */
643 strmap_clear(&info->dir_rename_guess, 1);
645 /* relevant_source_dirs */
646 if (info->relevant_source_dirs &&
647 info->relevant_source_dirs != dirs_removed) {
648 strintmap_clear(info->relevant_source_dirs);
649 FREE_AND_NULL(info->relevant_source_dirs);
652 /* dir_rename_count */
653 if (!keep_dir_rename_count) {
654 partial_clear_dir_rename_count(info->dir_rename_count);
655 strmap_clear(info->dir_rename_count, 1);
656 FREE_AND_NULL(info->dir_rename_count);
661 * Although dir_rename_count was passed in
662 * diffcore_rename_extended() and we want to keep it around and
663 * return it to that caller, we first want to remove any data
664 * associated with directories that weren't renamed.
666 strmap_for_each_entry(info->dir_rename_count, &iter, entry) {
667 const char *source_dir = entry->key;
668 struct strintmap *counts = entry->value;
670 if (!strintmap_get(dirs_removed, source_dir)) {
671 string_list_append(&to_remove, source_dir);
672 strintmap_clear(counts);
676 for (i = 0; i < to_remove.nr; ++i)
677 strmap_remove(info->dir_rename_count,
678 to_remove.items[i].string, 1);
679 string_list_clear(&to_remove, 0);
682 static const char *get_basename(const char *filename)
685 * gitbasename() has to worry about special drives, multiple
686 * directory separator characters, trailing slashes, NULL or
687 * empty strings, etc. We only work on filenames as stored in
688 * git, and thus get to ignore all those complications.
690 const char *base = strrchr(filename, '/');
691 return base ? base + 1 : filename;
694 static int idx_possible_rename(char *filename, struct dir_rename_info *info)
697 * Our comparison of files with the same basename (see
698 * find_basename_matches() below), is only helpful when after exact
699 * rename detection we have exactly one file with a given basename
700 * among the rename sources and also only exactly one file with
701 * that basename among the rename destinations. When we have
702 * multiple files with the same basename in either set, we do not
703 * know which to compare against. However, there are some
704 * filenames that occur in large numbers (particularly
705 * build-related filenames such as 'Makefile', '.gitignore', or
706 * 'build.gradle' that potentially exist within every single
707 * subdirectory), and for performance we want to be able to quickly
708 * find renames for these files too.
710 * The reason basename comparisons are a useful heuristic was that it
711 * is common for people to move files across directories while keeping
712 * their filename the same. If we had a way of determining or even
713 * making a good educated guess about which directory these non-unique
714 * basename files had moved the file to, we could check it.
717 * When an entire directory is in fact renamed, we have two factors
719 * (a) the original directory disappeared giving us a hint
720 * about when we can apply an extra heuristic.
721 * (a) we often have several files within that directory and
722 * subdirectories that are renamed without changes
723 * So, rules for a heuristic:
724 * (0) If there basename matches are non-unique (the condition under
725 * which this function is called) AND
726 * (1) the directory in which the file was found has disappeared
727 * (i.e. dirs_removed is non-NULL and has a relevant entry) THEN
728 * (2) use exact renames of files within the directory to determine
729 * where the directory is likely to have been renamed to. IF
730 * there is at least one exact rename from within that
731 * directory, we can proceed.
732 * (3) If there are multiple places the directory could have been
733 * renamed to based on exact renames, ignore all but one of them.
734 * Just use the destination with the most renames going to it.
735 * (4) Check if applying that directory rename to the original file
736 * would result in a destination filename that is in the
737 * potential rename set. If so, return the index of the
738 * destination file (the index within rename_dst).
739 * (5) Compare the original file and returned destination for
740 * similarity, and if they are sufficiently similar, record the
743 * This function, idx_possible_rename(), is only responsible for (4).
744 * The conditions/steps in (1)-(3) are handled via setting up
745 * dir_rename_count and dir_rename_guess in
746 * initialize_dir_rename_info(). Steps (0) and (5) are handled by
747 * the caller of this function.
749 char *old_dir, *new_dir;
750 struct strbuf new_path = STRBUF_INIT;
756 old_dir = get_dirname(filename);
757 new_dir = strmap_get(&info->dir_rename_guess, old_dir);
762 strbuf_addstr(&new_path, new_dir);
763 strbuf_addch(&new_path, '/');
764 strbuf_addstr(&new_path, get_basename(filename));
766 idx = strintmap_get(&info->idx_map, new_path.buf);
767 strbuf_release(&new_path);
771 static int find_basename_matches(struct diff_options *options,
773 struct dir_rename_info *info,
774 struct strintmap *relevant_sources,
775 struct strintmap *dirs_removed)
778 * When I checked in early 2020, over 76% of file renames in linux
779 * just moved files to a different directory but kept the same
780 * basename. gcc did that with over 64% of renames, gecko did it
781 * with over 79%, and WebKit did it with over 89%.
783 * Therefore we can bypass the normal exhaustive NxM matrix
784 * comparison of similarities between all potential rename sources
785 * and destinations by instead using file basename as a hint (i.e.
786 * the portion of the filename after the last '/'), checking for
787 * similarity between files with the same basename, and if we find
788 * a pair that are sufficiently similar, record the rename pair and
789 * exclude those two from the NxM matrix.
791 * This *might* cause us to find a less than optimal pairing (if
792 * there is another file that we are even more similar to but has a
793 * different basename). Given the huge performance advantage
794 * basename matching provides, and given the frequency with which
795 * people use the same basename in real world projects, that's a
796 * trade-off we are willing to accept when doing just rename
799 * If someone wants copy detection that implies they are willing to
800 * spend more cycles to find similarities between files, so it may
801 * be less likely that this heuristic is wanted. If someone is
802 * doing break detection, that means they do not want filename
803 * similarity to imply any form of content similiarity, and thus
804 * this heuristic would definitely be incompatible.
808 struct strintmap sources;
809 struct strintmap dests;
812 * The prefeteching stuff wants to know if it can skip prefetching
813 * blobs that are unmodified...and will then do a little extra work
814 * to verify that the oids are indeed different before prefetching.
815 * Unmodified blobs are only relevant when doing copy detection;
816 * when limiting to rename detection, diffcore_rename[_extended]()
817 * will never be called with unmodified source paths fed to us, so
818 * the extra work necessary to check if rename_src entries are
819 * unmodified would be a small waste.
821 int skip_unmodified = 0;
824 * Create maps of basename -> fullname(s) for remaining sources and
827 strintmap_init_with_options(&sources, -1, NULL, 0);
828 strintmap_init_with_options(&dests, -1, NULL, 0);
829 for (i = 0; i < rename_src_nr; ++i) {
830 char *filename = rename_src[i].p->one->path;
833 /* exact renames removed in remove_unneeded_paths_from_src() */
834 assert(!rename_src[i].p->one->rename_used);
836 /* Record index within rename_src (i) if basename is unique */
837 base = get_basename(filename);
838 if (strintmap_contains(&sources, base))
839 strintmap_set(&sources, base, -1);
841 strintmap_set(&sources, base, i);
843 for (i = 0; i < rename_dst_nr; ++i) {
844 char *filename = rename_dst[i].p->two->path;
847 if (rename_dst[i].is_rename)
848 continue; /* involved in exact match already. */
850 /* Record index within rename_dst (i) if basename is unique */
851 base = get_basename(filename);
852 if (strintmap_contains(&dests, base))
853 strintmap_set(&dests, base, -1);
855 strintmap_set(&dests, base, i);
858 /* Now look for basename matchups and do similarity estimation */
859 for (i = 0; i < rename_src_nr; ++i) {
860 char *filename = rename_src[i].p->one->path;
861 const char *base = NULL;
865 /* Skip irrelevant sources */
866 if (relevant_sources &&
867 !strintmap_contains(relevant_sources, filename))
871 * If the basename is unique among remaining sources, then
872 * src_index will equal 'i' and we can attempt to match it
873 * to a unique basename in the destinations. Otherwise,
874 * use directory rename heuristics, if possible.
876 base = get_basename(filename);
877 src_index = strintmap_get(&sources, base);
878 assert(src_index == -1 || src_index == i);
880 if (strintmap_contains(&dests, base)) {
881 struct diff_filespec *one, *two;
884 /* Find a matching destination, if possible */
885 dst_index = strintmap_get(&dests, base);
886 if (src_index == -1 || dst_index == -1) {
888 dst_index = idx_possible_rename(filename, info);
893 /* Ignore this dest if already used in a rename */
894 if (rename_dst[dst_index].is_rename)
895 continue; /* already used previously */
897 /* Estimate the similarity */
898 one = rename_src[src_index].p->one;
899 two = rename_dst[dst_index].p->two;
900 score = estimate_similarity(options->repo, one, two,
901 minimum_score, skip_unmodified);
903 /* If sufficiently similar, record as rename pair */
904 if (score < minimum_score)
906 record_rename_pair(dst_index, src_index, score);
908 update_dir_rename_counts(info, dirs_removed,
909 one->path, two->path);
912 * Found a rename so don't need text anymore; if we
913 * didn't find a rename, the filespec_blob would get
914 * re-used when doing the matrix of comparisons.
916 diff_free_filespec_blob(one);
917 diff_free_filespec_blob(two);
921 strintmap_clear(&sources);
922 strintmap_clear(&dests);
927 #define NUM_CANDIDATE_PER_DST 4
928 static void record_if_better(struct diff_score m[], struct diff_score *o)
932 /* find the worst one */
934 for (i = 1; i < NUM_CANDIDATE_PER_DST; i++)
935 if (score_compare(&m[i], &m[worst]) > 0)
938 /* is it better than the worst one? */
939 if (score_compare(&m[worst], o) > 0)
945 * 0 if we are under the limit;
946 * 1 if we need to disable inexact rename detection;
947 * 2 if we would be under the limit if we were given -C instead of -C -C.
949 static int too_many_rename_candidates(int num_destinations, int num_sources,
950 struct diff_options *options)
952 int rename_limit = options->rename_limit;
953 int i, limited_sources;
955 options->needed_rename_limit = 0;
958 * This basically does a test for the rename matrix not
959 * growing larger than a "rename_limit" square matrix, ie:
961 * num_destinations * num_sources > rename_limit * rename_limit
963 * We use st_mult() to check overflow conditions; in the
964 * exceptional circumstance that size_t isn't large enough to hold
965 * the multiplication, the system won't be able to allocate enough
966 * memory for the matrix anyway.
968 if (rename_limit <= 0)
969 rename_limit = 32767;
970 if (st_mult(num_destinations, num_sources)
971 <= st_mult(rename_limit, rename_limit))
974 options->needed_rename_limit =
975 num_sources > num_destinations ? num_sources : num_destinations;
977 /* Are we running under -C -C? */
978 if (!options->flags.find_copies_harder)
981 /* Would we bust the limit if we were running under -C? */
982 for (limited_sources = i = 0; i < num_sources; i++) {
983 if (diff_unmodified_pair(rename_src[i].p))
987 if (st_mult(num_destinations, limited_sources)
988 <= st_mult(rename_limit, rename_limit))
993 static int find_renames(struct diff_score *mx,
997 struct dir_rename_info *info,
998 struct strintmap *dirs_removed)
1002 for (i = 0; i < dst_cnt * NUM_CANDIDATE_PER_DST; i++) {
1003 struct diff_rename_dst *dst;
1005 if ((mx[i].dst < 0) ||
1006 (mx[i].score < minimum_score))
1007 break; /* there is no more usable pair. */
1008 dst = &rename_dst[mx[i].dst];
1010 continue; /* already done, either exact or fuzzy. */
1011 if (!copies && rename_src[mx[i].src].p->one->rename_used)
1013 record_rename_pair(mx[i].dst, mx[i].src, mx[i].score);
1015 update_dir_rename_counts(info, dirs_removed,
1016 rename_src[mx[i].src].p->one->path,
1017 rename_dst[mx[i].dst].p->two->path);
1022 static void remove_unneeded_paths_from_src(int detecting_copies,
1023 struct strintmap *interesting)
1027 if (detecting_copies && !interesting)
1028 return; /* nothing to remove */
1030 return; /* culling incompatible with break detection */
1033 * Note on reasons why we cull unneeded sources but not destinations:
1034 * 1) Pairings are stored in rename_dst (not rename_src), which we
1035 * need to keep around. So, we just can't cull rename_dst even
1036 * if we wanted to. But doing so wouldn't help because...
1038 * 2) There is a matrix pairwise comparison that follows the
1039 * "Performing inexact rename detection" progress message.
1040 * Iterating over the destinations is done in the outer loop,
1041 * hence we only iterate over each of those once and we can
1042 * easily skip the outer loop early if the destination isn't
1043 * relevant. That's only one check per destination path to
1046 * By contrast, the sources are iterated in the inner loop; if
1047 * we check whether a source can be skipped, then we'll be
1048 * checking it N separate times, once for each destination.
1049 * We don't want to have to iterate over known-not-needed
1050 * sources N times each, so avoid that by removing the sources
1051 * from rename_src here.
1053 for (i = 0, new_num_src = 0; i < rename_src_nr; i++) {
1054 struct diff_filespec *one = rename_src[i].p->one;
1057 * renames are stored in rename_dst, so if a rename has
1058 * already been detected using this source, we can just
1059 * remove the source knowing rename_dst has its info.
1061 if (!detecting_copies && one->rename_used)
1064 /* If we don't care about the source path, skip it */
1065 if (interesting && !strintmap_contains(interesting, one->path))
1068 if (new_num_src < i)
1069 memcpy(&rename_src[new_num_src], &rename_src[i],
1070 sizeof(struct diff_rename_src));
1074 rename_src_nr = new_num_src;
1077 static void handle_early_known_dir_renames(struct dir_rename_info *info,
1078 struct strintmap *relevant_sources,
1079 struct strintmap *dirs_removed)
1082 * Not yet implemented; directory renames are determined via an
1083 * aggregate of all renames under them and using a "majority wins"
1084 * rule. The fact that "majority wins", though, means we don't need
1085 * all the renames under the given directory, we only need enough to
1086 * ensure we have a majority.
1088 * For now, we don't have enough information to know if we have a
1089 * majority after exact renames and basename-guided rename detection,
1090 * so just return early without doing any extra filtering.
1095 void diffcore_rename_extended(struct diff_options *options,
1096 struct strintmap *relevant_sources,
1097 struct strintmap *dirs_removed,
1098 struct strmap *dir_rename_count)
1100 int detect_rename = options->detect_rename;
1101 int minimum_score = options->rename_score;
1102 struct diff_queue_struct *q = &diff_queued_diff;
1103 struct diff_queue_struct outq;
1104 struct diff_score *mx;
1105 int i, j, rename_count, skip_unmodified = 0;
1106 int num_destinations, dst_cnt;
1107 int num_sources, want_copies;
1108 struct progress *progress = NULL;
1109 struct dir_rename_info info;
1111 trace2_region_enter("diff", "setup", options->repo);
1113 assert(!dir_rename_count || strmap_empty(dir_rename_count));
1114 want_copies = (detect_rename == DIFF_DETECT_COPY);
1115 if (dirs_removed && (break_idx || want_copies))
1116 BUG("dirs_removed incompatible with break/copy detection");
1117 if (break_idx && relevant_sources)
1118 BUG("break detection incompatible with source specification");
1120 minimum_score = DEFAULT_RENAME_SCORE;
1122 for (i = 0; i < q->nr; i++) {
1123 struct diff_filepair *p = q->queue[i];
1124 if (!DIFF_FILE_VALID(p->one)) {
1125 if (!DIFF_FILE_VALID(p->two))
1126 continue; /* unmerged */
1127 else if (options->single_follow &&
1128 strcmp(options->single_follow, p->two->path))
1129 continue; /* not interested */
1130 else if (!options->flags.rename_empty &&
1131 is_empty_blob_oid(&p->two->oid))
1133 else if (add_rename_dst(p) < 0) {
1134 warning("skipping rename detection, detected"
1135 " duplicate destination '%s'",
1140 else if (!options->flags.rename_empty &&
1141 is_empty_blob_oid(&p->one->oid))
1143 else if (!DIFF_PAIR_UNMERGED(p) && !DIFF_FILE_VALID(p->two)) {
1145 * If the source is a broken "delete", and
1146 * they did not really want to get broken,
1147 * that means the source actually stays.
1148 * So we increment the "rename_used" score
1149 * by one, to indicate ourselves as a user
1151 if (p->broken_pair && !p->score)
1152 p->one->rename_used++;
1153 register_rename_src(p);
1155 else if (want_copies) {
1157 * Increment the "rename_used" score by
1158 * one, to indicate ourselves as a user.
1160 p->one->rename_used++;
1161 register_rename_src(p);
1164 trace2_region_leave("diff", "setup", options->repo);
1165 if (rename_dst_nr == 0 || rename_src_nr == 0)
1166 goto cleanup; /* nothing to do */
1168 trace2_region_enter("diff", "exact renames", options->repo);
1170 * We really want to cull the candidates list early
1171 * with cheap tests in order to avoid doing deltas.
1173 rename_count = find_exact_renames(options);
1174 trace2_region_leave("diff", "exact renames", options->repo);
1176 /* Did we only want exact renames? */
1177 if (minimum_score == MAX_SCORE)
1180 num_sources = rename_src_nr;
1182 if (want_copies || break_idx) {
1185 * - remove ones corresponding to exact renames
1186 * - remove ones not found in relevant_sources
1188 trace2_region_enter("diff", "cull after exact", options->repo);
1189 remove_unneeded_paths_from_src(want_copies, relevant_sources);
1190 trace2_region_leave("diff", "cull after exact", options->repo);
1192 /* Determine minimum score to match basenames */
1193 double factor = 0.5;
1194 char *basename_factor = getenv("GIT_BASENAME_FACTOR");
1195 int min_basename_score;
1197 if (basename_factor)
1198 factor = strtol(basename_factor, NULL, 10)/100.0;
1199 assert(factor >= 0.0 && factor <= 1.0);
1200 min_basename_score = minimum_score +
1201 (int)(factor * (MAX_SCORE - minimum_score));
1205 * - remove ones involved in renames (found via exact match)
1207 trace2_region_enter("diff", "cull after exact", options->repo);
1208 remove_unneeded_paths_from_src(want_copies, NULL);
1209 trace2_region_leave("diff", "cull after exact", options->repo);
1211 /* Preparation for basename-driven matching. */
1212 trace2_region_enter("diff", "dir rename setup", options->repo);
1213 initialize_dir_rename_info(&info, relevant_sources,
1214 dirs_removed, dir_rename_count);
1215 trace2_region_leave("diff", "dir rename setup", options->repo);
1217 /* Utilize file basenames to quickly find renames. */
1218 trace2_region_enter("diff", "basename matches", options->repo);
1219 rename_count += find_basename_matches(options,
1224 trace2_region_leave("diff", "basename matches", options->repo);
1227 * Cull sources, again:
1228 * - remove ones involved in renames (found via basenames)
1229 * - remove ones not found in relevant_sources
1231 * - remove ones in relevant_sources which are needed only
1232 * for directory renames IF no ancestory directory
1233 * actually needs to know any more individual path
1234 * renames under them
1236 trace2_region_enter("diff", "cull basename", options->repo);
1237 remove_unneeded_paths_from_src(want_copies, relevant_sources);
1238 handle_early_known_dir_renames(&info, relevant_sources,
1240 trace2_region_leave("diff", "cull basename", options->repo);
1243 /* Calculate how many rename destinations are left */
1244 num_destinations = (rename_dst_nr - rename_count);
1245 num_sources = rename_src_nr; /* rename_src_nr reflects lower number */
1248 if (!num_destinations || !num_sources)
1251 switch (too_many_rename_candidates(num_destinations, num_sources,
1256 options->degraded_cc_to_c = 1;
1257 skip_unmodified = 1;
1263 trace2_region_enter("diff", "inexact renames", options->repo);
1264 if (options->show_rename_progress) {
1265 progress = start_delayed_progress(
1266 _("Performing inexact rename detection"),
1267 (uint64_t)num_destinations * (uint64_t)num_sources);
1270 mx = xcalloc(st_mult(NUM_CANDIDATE_PER_DST, num_destinations),
1272 for (dst_cnt = i = 0; i < rename_dst_nr; i++) {
1273 struct diff_filespec *two = rename_dst[i].p->two;
1274 struct diff_score *m;
1276 if (rename_dst[i].is_rename)
1277 continue; /* exact or basename match already handled */
1279 m = &mx[dst_cnt * NUM_CANDIDATE_PER_DST];
1280 for (j = 0; j < NUM_CANDIDATE_PER_DST; j++)
1283 for (j = 0; j < rename_src_nr; j++) {
1284 struct diff_filespec *one = rename_src[j].p->one;
1285 struct diff_score this_src;
1287 assert(!one->rename_used || want_copies || break_idx);
1289 if (skip_unmodified &&
1290 diff_unmodified_pair(rename_src[j].p))
1293 this_src.score = estimate_similarity(options->repo,
1297 this_src.name_score = basename_same(one, two);
1300 record_if_better(m, &this_src);
1302 * Once we run estimate_similarity,
1303 * We do not need the text anymore.
1305 diff_free_filespec_blob(one);
1306 diff_free_filespec_blob(two);
1309 display_progress(progress,
1310 (uint64_t)dst_cnt * (uint64_t)num_sources);
1312 stop_progress(&progress);
1314 /* cost matrix sorted by most to least similar pair */
1315 STABLE_QSORT(mx, dst_cnt * NUM_CANDIDATE_PER_DST, score_compare);
1317 rename_count += find_renames(mx, dst_cnt, minimum_score, 0,
1318 &info, dirs_removed);
1320 rename_count += find_renames(mx, dst_cnt, minimum_score, 1,
1321 &info, dirs_removed);
1323 trace2_region_leave("diff", "inexact renames", options->repo);
1326 /* At this point, we have found some renames and copies and they
1327 * are recorded in rename_dst. The original list is still in *q.
1329 trace2_region_enter("diff", "write back to queue", options->repo);
1330 DIFF_QUEUE_CLEAR(&outq);
1331 for (i = 0; i < q->nr; i++) {
1332 struct diff_filepair *p = q->queue[i];
1333 struct diff_filepair *pair_to_free = NULL;
1335 if (DIFF_PAIR_UNMERGED(p)) {
1338 else if (!DIFF_FILE_VALID(p->one) && DIFF_FILE_VALID(p->two)) {
1342 else if (DIFF_FILE_VALID(p->one) && !DIFF_FILE_VALID(p->two)) {
1346 * We would output this delete record if:
1348 * (1) this is a broken delete and the counterpart
1349 * broken create remains in the output; or
1350 * (2) this is not a broken delete, and rename_dst
1351 * does not have a rename/copy to move p->one->path
1354 * Otherwise, the counterpart broken create
1355 * has been turned into a rename-edit; or
1356 * delete did not have a matching create to
1359 if (DIFF_PAIR_BROKEN(p)) {
1361 struct diff_rename_dst *dst = locate_rename_dst(p);
1363 BUG("tracking failed somehow; failed to find associated dst for broken pair");
1365 /* counterpart is now rename/copy */
1369 if (p->one->rename_used)
1370 /* this path remains */
1377 else if (!diff_unmodified_pair(p))
1378 /* all the usual ones need to be kept */
1381 /* no need to keep unmodified pairs; FIXME: remove earlier? */
1385 diff_free_filepair(pair_to_free);
1387 diff_debug_queue("done copying original", &outq);
1391 diff_debug_queue("done collapsing", q);
1393 for (i = 0; i < rename_dst_nr; i++)
1394 if (rename_dst[i].filespec_to_free)
1395 free_filespec(rename_dst[i].filespec_to_free);
1397 cleanup_dir_rename_info(&info, dirs_removed, dir_rename_count != NULL);
1398 FREE_AND_NULL(rename_dst);
1399 rename_dst_nr = rename_dst_alloc = 0;
1400 FREE_AND_NULL(rename_src);
1401 rename_src_nr = rename_src_alloc = 0;
1403 strintmap_clear(break_idx);
1404 FREE_AND_NULL(break_idx);
1406 trace2_region_leave("diff", "write back to queue", options->repo);
1410 void diffcore_rename(struct diff_options *options)
1412 diffcore_rename_extended(options, NULL, NULL, NULL);