pull: trivial cleanup
[git.git] / diffcore-rename.c
blob3375e24659ea1a34eca48af6109fa534861c8c7c
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(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;
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 prefetch_options {
91 struct repository *repo;
92 int skip_unmodified;
94 static void prefetch(void *prefetch_options)
96 struct 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 int skip_unmodified)
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;
146 struct diff_populate_filespec_options dpf_options = {
147 .check_size_only = 1
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
158 * after renaming.
160 if (!S_ISREG(src->mode) || !S_ISREG(dst->mode))
161 return 0;
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))
174 return 0;
175 if (!dst->cnt_data &&
176 diff_populate_filespec(r, dst, &dpf_options))
177 return 0;
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)
192 return 0;
194 dpf_options.check_size_only = 0;
196 if (!src->cnt_data && diff_populate_filespec(r, src, &dpf_options))
197 return 0;
198 if (!dst->cnt_data && diff_populate_filespec(r, dst, &dpf_options))
199 return 0;
201 if (diffcore_count_changes(r, src, dst,
202 &src->cnt_data, &dst->cnt_data,
203 &src_copied, &literal_added))
204 return 0;
206 /* How similar are they?
207 * what percentage of material in dst are from source?
209 if (!dst->size)
210 score = 0; /* should not happen */
211 else
212 score = (int)(src_copied * MAX_SCORE / max_size);
213 return score;
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++;
225 src->one->count++;
227 rename_dst[dst_index].filespec_to_free = dst->one;
228 rename_dst[dst_index].is_rename = 1;
230 dst->one = src->one;
231 dst->renamed_pair = 1;
232 if (!strcmp(dst->one->path, dst->two->path))
233 dst->score = rename_src[src_index].score;
234 else
235 dst->score = score;
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 */
247 if (a->dst < 0)
248 return (0 <= b->dst);
249 else if (b->dst < 0)
250 return -1;
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;
260 int index;
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))
269 return 0;
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,
277 int dst_index,
278 struct diff_options *options)
280 int renames = 0;
281 struct diff_filespec *target = rename_dst[dst_index].p->two;
282 struct file_similarity *p, *best = NULL;
283 int i = 100, best_score = -1;
284 unsigned int hash = hash_filespec(options->repo, target);
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) {
292 int score;
293 struct diff_filespec *source = p->filespec;
295 /* False hash collision? */
296 if (!oideq(&source->oid, &target->oid))
297 continue;
298 /* Non-regular files? If so, the modes must match! */
299 if (!S_ISREG(source->mode) || !S_ISREG(target->mode)) {
300 if (source->mode != target->mode)
301 continue;
303 /* Give higher scores to sources that haven't been used already */
304 score = !source->rename_used;
305 if (source->rename_used && options->detect_rename != DIFF_DETECT_COPY)
306 continue;
307 score += basename_same(source, target);
308 if (score > best_score) {
309 best = p;
310 best_score = score;
311 if (score == 2)
312 break;
315 /* Too many identical alternatives? Pick one */
316 if (!--i)
317 break;
319 if (best) {
320 record_rename_pair(dst_index, best->index, MAX_SCORE);
321 renames++;
323 return renames;
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)
348 int i, renames = 0;
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,
357 &file_table, i,
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);
367 return renames;
370 struct dir_rename_info {
371 struct strintmap idx_map;
372 struct strmap dir_rename_guess;
373 struct strmap *dir_rename_count;
374 struct strintmap *relevant_source_dirs;
375 unsigned setup;
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, '/');
387 if (!slash)
388 slash = filename;
389 *slash = '\0';
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 char *UNKNOWN_DIR = "/"; /* placeholder -- short, illegal directory */
412 static int dir_rename_already_determinable(struct strintmap *counts)
414 struct hashmap_iter iter;
415 struct strmap_entry *entry;
416 int first = 0, second = 0, unknown = 0;
417 strintmap_for_each_entry(counts, &iter, entry) {
418 const char *destination_dir = entry->key;
419 intptr_t count = (intptr_t)entry->value;
420 if (!strcmp(destination_dir, UNKNOWN_DIR)) {
421 unknown = count;
422 } else if (count >= first) {
423 second = first;
424 first = count;
425 } else if (count >= second) {
426 second = count;
429 return first > second + unknown;
432 static void increment_count(struct dir_rename_info *info,
433 char *old_dir,
434 char *new_dir)
436 struct strintmap *counts;
437 struct strmap_entry *e;
439 /* Get the {new_dirs -> counts} mapping using old_dir */
440 e = strmap_get_entry(info->dir_rename_count, old_dir);
441 if (e) {
442 counts = e->value;
443 } else {
444 counts = xmalloc(sizeof(*counts));
445 strintmap_init_with_options(counts, 0, NULL, 1);
446 strmap_put(info->dir_rename_count, old_dir, counts);
449 /* Increment the count for new_dir */
450 strintmap_incr(counts, new_dir, 1);
453 static void update_dir_rename_counts(struct dir_rename_info *info,
454 struct strintmap *dirs_removed,
455 const char *oldname,
456 const char *newname)
458 char *old_dir = xstrdup(oldname);
459 char *new_dir = xstrdup(newname);
460 char new_dir_first_char = new_dir[0];
461 int first_time_in_loop = 1;
463 if (!info->setup)
465 * info->setup is 0 here in two cases: (1) all auxiliary
466 * vars (like dirs_removed) were NULL so
467 * initialize_dir_rename_info() returned early, or (2)
468 * either break detection or copy detection are active so
469 * that we never called initialize_dir_rename_info(). In
470 * the former case, we don't have enough info to know if
471 * directories were renamed (because dirs_removed lets us
472 * know about a necessary prerequisite, namely if they were
473 * removed), and in the latter, we don't care about
474 * directory renames or find_basename_matches.
476 * This matters because both basename and inexact matching
477 * will also call update_dir_rename_counts(). In either of
478 * the above two cases info->dir_rename_counts will not
479 * have been properly initialized which prevents us from
480 * updating it, but in these two cases we don't care about
481 * dir_rename_counts anyway, so we can just exit early.
483 return;
485 while (1) {
486 int drd_flag = NOT_RELEVANT;
488 /* Get old_dir, skip if its directory isn't relevant. */
489 dirname_munge(old_dir);
490 if (info->relevant_source_dirs &&
491 !strintmap_contains(info->relevant_source_dirs, old_dir))
492 break;
494 /* Get new_dir */
495 dirname_munge(new_dir);
498 * When renaming
499 * "a/b/c/d/e/foo.c" -> "a/b/some/thing/else/e/foo.c"
500 * then this suggests that both
501 * a/b/c/d/e/ => a/b/some/thing/else/e/
502 * a/b/c/d/ => a/b/some/thing/else/
503 * so we want to increment counters for both. We do NOT,
504 * however, also want to suggest that there was the following
505 * rename:
506 * a/b/c/ => a/b/some/thing/
507 * so we need to quit at that point.
509 * Note the when first_time_in_loop, we only strip off the
510 * basename, and we don't care if that's different.
512 if (!first_time_in_loop) {
513 char *old_sub_dir = strchr(old_dir, '\0')+1;
514 char *new_sub_dir = strchr(new_dir, '\0')+1;
515 if (!*new_dir) {
517 * Special case when renaming to root directory,
518 * i.e. when new_dir == "". In this case, we had
519 * something like
520 * a/b/subdir => subdir
521 * and so dirname_munge() sets things up so that
522 * old_dir = "a/b\0subdir\0"
523 * new_dir = "\0ubdir\0"
524 * We didn't have a '/' to overwrite a '\0' onto
525 * in new_dir, so we have to compare differently.
527 if (new_dir_first_char != old_sub_dir[0] ||
528 strcmp(old_sub_dir+1, new_sub_dir))
529 break;
530 } else {
531 if (strcmp(old_sub_dir, new_sub_dir))
532 break;
537 * Above we suggested that we'd keep recording renames for
538 * all ancestor directories where the trailing directories
539 * matched, i.e. for
540 * "a/b/c/d/e/foo.c" -> "a/b/some/thing/else/e/foo.c"
541 * we'd increment rename counts for each of
542 * a/b/c/d/e/ => a/b/some/thing/else/e/
543 * a/b/c/d/ => a/b/some/thing/else/
544 * However, we only need the rename counts for directories
545 * in dirs_removed whose value is RELEVANT_FOR_SELF.
546 * However, we add one special case of also recording it for
547 * first_time_in_loop because find_basename_matches() can
548 * use that as a hint to find a good pairing.
550 if (dirs_removed)
551 drd_flag = strintmap_get(dirs_removed, old_dir);
552 if (drd_flag == RELEVANT_FOR_SELF || first_time_in_loop)
553 increment_count(info, old_dir, new_dir);
555 first_time_in_loop = 0;
556 if (drd_flag == NOT_RELEVANT)
557 break;
558 /* If we hit toplevel directory ("") for old or new dir, quit */
559 if (!*old_dir || !*new_dir)
560 break;
563 /* Free resources we don't need anymore */
564 free(old_dir);
565 free(new_dir);
568 static void initialize_dir_rename_info(struct dir_rename_info *info,
569 struct strintmap *relevant_sources,
570 struct strintmap *dirs_removed,
571 struct strmap *dir_rename_count,
572 struct strmap *cached_pairs)
574 struct hashmap_iter iter;
575 struct strmap_entry *entry;
576 int i;
578 if (!dirs_removed && !relevant_sources) {
579 info->setup = 0;
580 return;
582 info->setup = 1;
584 info->dir_rename_count = dir_rename_count;
585 if (!info->dir_rename_count) {
586 info->dir_rename_count = xmalloc(sizeof(*dir_rename_count));
587 strmap_init(info->dir_rename_count);
589 strintmap_init_with_options(&info->idx_map, -1, NULL, 0);
590 strmap_init_with_options(&info->dir_rename_guess, NULL, 0);
592 /* Setup info->relevant_source_dirs */
593 info->relevant_source_dirs = NULL;
594 if (dirs_removed || !relevant_sources) {
595 info->relevant_source_dirs = dirs_removed; /* might be NULL */
596 } else {
597 info->relevant_source_dirs = xmalloc(sizeof(struct strintmap));
598 strintmap_init(info->relevant_source_dirs, 0 /* unused */);
599 strintmap_for_each_entry(relevant_sources, &iter, entry) {
600 char *dirname = get_dirname(entry->key);
601 if (!dirs_removed ||
602 strintmap_contains(dirs_removed, dirname))
603 strintmap_set(info->relevant_source_dirs,
604 dirname, 0 /* value irrelevant */);
605 free(dirname);
610 * Loop setting up both info->idx_map, and doing setup of
611 * info->dir_rename_count.
613 for (i = 0; i < rename_dst_nr; ++i) {
615 * For non-renamed files, make idx_map contain mapping of
616 * filename -> index (index within rename_dst, that is)
618 if (!rename_dst[i].is_rename) {
619 char *filename = rename_dst[i].p->two->path;
620 strintmap_set(&info->idx_map, filename, i);
621 continue;
625 * For everything else (i.e. renamed files), make
626 * dir_rename_count contain a map of a map:
627 * old_directory -> {new_directory -> count}
628 * In other words, for every pair look at the directories for
629 * the old filename and the new filename and count how many
630 * times that pairing occurs.
632 update_dir_rename_counts(info, dirs_removed,
633 rename_dst[i].p->one->path,
634 rename_dst[i].p->two->path);
637 /* Add cached_pairs to counts */
638 strmap_for_each_entry(cached_pairs, &iter, entry) {
639 const char *old_name = entry->key;
640 const char *new_name = entry->value;
641 if (!new_name)
642 /* known delete; ignore it */
643 continue;
645 update_dir_rename_counts(info, dirs_removed, old_name, new_name);
649 * Now we collapse
650 * dir_rename_count: old_directory -> {new_directory -> count}
651 * down to
652 * dir_rename_guess: old_directory -> best_new_directory
653 * where best_new_directory is the one with the highest count.
655 strmap_for_each_entry(info->dir_rename_count, &iter, entry) {
656 /* entry->key is source_dir */
657 struct strintmap *counts = entry->value;
658 char *best_newdir;
660 best_newdir = xstrdup(get_highest_rename_path(counts));
661 strmap_put(&info->dir_rename_guess, entry->key,
662 best_newdir);
666 void partial_clear_dir_rename_count(struct strmap *dir_rename_count)
668 struct hashmap_iter iter;
669 struct strmap_entry *entry;
671 strmap_for_each_entry(dir_rename_count, &iter, entry) {
672 struct strintmap *counts = entry->value;
673 strintmap_clear(counts);
675 strmap_partial_clear(dir_rename_count, 1);
678 static void cleanup_dir_rename_info(struct dir_rename_info *info,
679 struct strintmap *dirs_removed,
680 int keep_dir_rename_count)
682 struct hashmap_iter iter;
683 struct strmap_entry *entry;
684 struct string_list to_remove = STRING_LIST_INIT_NODUP;
685 int i;
687 if (!info->setup)
688 return;
690 /* idx_map */
691 strintmap_clear(&info->idx_map);
693 /* dir_rename_guess */
694 strmap_clear(&info->dir_rename_guess, 1);
696 /* relevant_source_dirs */
697 if (info->relevant_source_dirs &&
698 info->relevant_source_dirs != dirs_removed) {
699 strintmap_clear(info->relevant_source_dirs);
700 FREE_AND_NULL(info->relevant_source_dirs);
703 /* dir_rename_count */
704 if (!keep_dir_rename_count) {
705 partial_clear_dir_rename_count(info->dir_rename_count);
706 strmap_clear(info->dir_rename_count, 1);
707 FREE_AND_NULL(info->dir_rename_count);
708 return;
712 * Although dir_rename_count was passed in
713 * diffcore_rename_extended() and we want to keep it around and
714 * return it to that caller, we first want to remove any counts in
715 * the maps associated with UNKNOWN_DIR entries and any data
716 * associated with directories that weren't renamed.
718 strmap_for_each_entry(info->dir_rename_count, &iter, entry) {
719 const char *source_dir = entry->key;
720 struct strintmap *counts = entry->value;
722 if (!strintmap_get(dirs_removed, source_dir)) {
723 string_list_append(&to_remove, source_dir);
724 strintmap_clear(counts);
725 continue;
728 if (strintmap_contains(counts, UNKNOWN_DIR))
729 strintmap_remove(counts, UNKNOWN_DIR);
731 for (i = 0; i < to_remove.nr; ++i)
732 strmap_remove(info->dir_rename_count,
733 to_remove.items[i].string, 1);
734 string_list_clear(&to_remove, 0);
737 static const char *get_basename(const char *filename)
740 * gitbasename() has to worry about special drives, multiple
741 * directory separator characters, trailing slashes, NULL or
742 * empty strings, etc. We only work on filenames as stored in
743 * git, and thus get to ignore all those complications.
745 const char *base = strrchr(filename, '/');
746 return base ? base + 1 : filename;
749 static int idx_possible_rename(char *filename, struct dir_rename_info *info)
752 * Our comparison of files with the same basename (see
753 * find_basename_matches() below), is only helpful when after exact
754 * rename detection we have exactly one file with a given basename
755 * among the rename sources and also only exactly one file with
756 * that basename among the rename destinations. When we have
757 * multiple files with the same basename in either set, we do not
758 * know which to compare against. However, there are some
759 * filenames that occur in large numbers (particularly
760 * build-related filenames such as 'Makefile', '.gitignore', or
761 * 'build.gradle' that potentially exist within every single
762 * subdirectory), and for performance we want to be able to quickly
763 * find renames for these files too.
765 * The reason basename comparisons are a useful heuristic was that it
766 * is common for people to move files across directories while keeping
767 * their filename the same. If we had a way of determining or even
768 * making a good educated guess about which directory these non-unique
769 * basename files had moved the file to, we could check it.
770 * Luckily...
772 * When an entire directory is in fact renamed, we have two factors
773 * helping us out:
774 * (a) the original directory disappeared giving us a hint
775 * about when we can apply an extra heuristic.
776 * (a) we often have several files within that directory and
777 * subdirectories that are renamed without changes
778 * So, rules for a heuristic:
779 * (0) If there basename matches are non-unique (the condition under
780 * which this function is called) AND
781 * (1) the directory in which the file was found has disappeared
782 * (i.e. dirs_removed is non-NULL and has a relevant entry) THEN
783 * (2) use exact renames of files within the directory to determine
784 * where the directory is likely to have been renamed to. IF
785 * there is at least one exact rename from within that
786 * directory, we can proceed.
787 * (3) If there are multiple places the directory could have been
788 * renamed to based on exact renames, ignore all but one of them.
789 * Just use the destination with the most renames going to it.
790 * (4) Check if applying that directory rename to the original file
791 * would result in a destination filename that is in the
792 * potential rename set. If so, return the index of the
793 * destination file (the index within rename_dst).
794 * (5) Compare the original file and returned destination for
795 * similarity, and if they are sufficiently similar, record the
796 * rename.
798 * This function, idx_possible_rename(), is only responsible for (4).
799 * The conditions/steps in (1)-(3) are handled via setting up
800 * dir_rename_count and dir_rename_guess in
801 * initialize_dir_rename_info(). Steps (0) and (5) are handled by
802 * the caller of this function.
804 char *old_dir, *new_dir;
805 struct strbuf new_path = STRBUF_INIT;
806 int idx;
808 if (!info->setup)
809 return -1;
811 old_dir = get_dirname(filename);
812 new_dir = strmap_get(&info->dir_rename_guess, old_dir);
813 free(old_dir);
814 if (!new_dir)
815 return -1;
817 strbuf_addstr(&new_path, new_dir);
818 strbuf_addch(&new_path, '/');
819 strbuf_addstr(&new_path, get_basename(filename));
821 idx = strintmap_get(&info->idx_map, new_path.buf);
822 strbuf_release(&new_path);
823 return idx;
826 static int find_basename_matches(struct diff_options *options,
827 int minimum_score,
828 struct dir_rename_info *info,
829 struct strintmap *relevant_sources,
830 struct strintmap *dirs_removed)
833 * When I checked in early 2020, over 76% of file renames in linux
834 * just moved files to a different directory but kept the same
835 * basename. gcc did that with over 64% of renames, gecko did it
836 * with over 79%, and WebKit did it with over 89%.
838 * Therefore we can bypass the normal exhaustive NxM matrix
839 * comparison of similarities between all potential rename sources
840 * and destinations by instead using file basename as a hint (i.e.
841 * the portion of the filename after the last '/'), checking for
842 * similarity between files with the same basename, and if we find
843 * a pair that are sufficiently similar, record the rename pair and
844 * exclude those two from the NxM matrix.
846 * This *might* cause us to find a less than optimal pairing (if
847 * there is another file that we are even more similar to but has a
848 * different basename). Given the huge performance advantage
849 * basename matching provides, and given the frequency with which
850 * people use the same basename in real world projects, that's a
851 * trade-off we are willing to accept when doing just rename
852 * detection.
854 * If someone wants copy detection that implies they are willing to
855 * spend more cycles to find similarities between files, so it may
856 * be less likely that this heuristic is wanted. If someone is
857 * doing break detection, that means they do not want filename
858 * similarity to imply any form of content similiarity, and thus
859 * this heuristic would definitely be incompatible.
862 int i, renames = 0;
863 struct strintmap sources;
864 struct strintmap dests;
867 * The prefeteching stuff wants to know if it can skip prefetching
868 * blobs that are unmodified...and will then do a little extra work
869 * to verify that the oids are indeed different before prefetching.
870 * Unmodified blobs are only relevant when doing copy detection;
871 * when limiting to rename detection, diffcore_rename[_extended]()
872 * will never be called with unmodified source paths fed to us, so
873 * the extra work necessary to check if rename_src entries are
874 * unmodified would be a small waste.
876 int skip_unmodified = 0;
879 * Create maps of basename -> fullname(s) for remaining sources and
880 * dests.
882 strintmap_init_with_options(&sources, -1, NULL, 0);
883 strintmap_init_with_options(&dests, -1, NULL, 0);
884 for (i = 0; i < rename_src_nr; ++i) {
885 char *filename = rename_src[i].p->one->path;
886 const char *base;
888 /* exact renames removed in remove_unneeded_paths_from_src() */
889 assert(!rename_src[i].p->one->rename_used);
891 /* Record index within rename_src (i) if basename is unique */
892 base = get_basename(filename);
893 if (strintmap_contains(&sources, base))
894 strintmap_set(&sources, base, -1);
895 else
896 strintmap_set(&sources, base, i);
898 for (i = 0; i < rename_dst_nr; ++i) {
899 char *filename = rename_dst[i].p->two->path;
900 const char *base;
902 if (rename_dst[i].is_rename)
903 continue; /* involved in exact match already. */
905 /* Record index within rename_dst (i) if basename is unique */
906 base = get_basename(filename);
907 if (strintmap_contains(&dests, base))
908 strintmap_set(&dests, base, -1);
909 else
910 strintmap_set(&dests, base, i);
913 /* Now look for basename matchups and do similarity estimation */
914 for (i = 0; i < rename_src_nr; ++i) {
915 char *filename = rename_src[i].p->one->path;
916 const char *base = NULL;
917 intptr_t src_index;
918 intptr_t dst_index;
920 /* Skip irrelevant sources */
921 if (relevant_sources &&
922 !strintmap_contains(relevant_sources, filename))
923 continue;
926 * If the basename is unique among remaining sources, then
927 * src_index will equal 'i' and we can attempt to match it
928 * to a unique basename in the destinations. Otherwise,
929 * use directory rename heuristics, if possible.
931 base = get_basename(filename);
932 src_index = strintmap_get(&sources, base);
933 assert(src_index == -1 || src_index == i);
935 if (strintmap_contains(&dests, base)) {
936 struct diff_filespec *one, *two;
937 int score;
939 /* Find a matching destination, if possible */
940 dst_index = strintmap_get(&dests, base);
941 if (src_index == -1 || dst_index == -1) {
942 src_index = i;
943 dst_index = idx_possible_rename(filename, info);
945 if (dst_index == -1)
946 continue;
948 /* Ignore this dest if already used in a rename */
949 if (rename_dst[dst_index].is_rename)
950 continue; /* already used previously */
952 /* Estimate the similarity */
953 one = rename_src[src_index].p->one;
954 two = rename_dst[dst_index].p->two;
955 score = estimate_similarity(options->repo, one, two,
956 minimum_score, skip_unmodified);
958 /* If sufficiently similar, record as rename pair */
959 if (score < minimum_score)
960 continue;
961 record_rename_pair(dst_index, src_index, score);
962 renames++;
963 update_dir_rename_counts(info, dirs_removed,
964 one->path, two->path);
967 * Found a rename so don't need text anymore; if we
968 * didn't find a rename, the filespec_blob would get
969 * re-used when doing the matrix of comparisons.
971 diff_free_filespec_blob(one);
972 diff_free_filespec_blob(two);
976 strintmap_clear(&sources);
977 strintmap_clear(&dests);
979 return renames;
982 #define NUM_CANDIDATE_PER_DST 4
983 static void record_if_better(struct diff_score m[], struct diff_score *o)
985 int i, worst;
987 /* find the worst one */
988 worst = 0;
989 for (i = 1; i < NUM_CANDIDATE_PER_DST; i++)
990 if (score_compare(&m[i], &m[worst]) > 0)
991 worst = i;
993 /* is it better than the worst one? */
994 if (score_compare(&m[worst], o) > 0)
995 m[worst] = *o;
999 * Returns:
1000 * 0 if we are under the limit;
1001 * 1 if we need to disable inexact rename detection;
1002 * 2 if we would be under the limit if we were given -C instead of -C -C.
1004 static int too_many_rename_candidates(int num_destinations, int num_sources,
1005 struct diff_options *options)
1007 int rename_limit = options->rename_limit;
1008 int i, limited_sources;
1010 options->needed_rename_limit = 0;
1013 * This basically does a test for the rename matrix not
1014 * growing larger than a "rename_limit" square matrix, ie:
1016 * num_destinations * num_sources > rename_limit * rename_limit
1018 * We use st_mult() to check overflow conditions; in the
1019 * exceptional circumstance that size_t isn't large enough to hold
1020 * the multiplication, the system won't be able to allocate enough
1021 * memory for the matrix anyway.
1023 if (rename_limit <= 0)
1024 rename_limit = 32767;
1025 if (st_mult(num_destinations, num_sources)
1026 <= st_mult(rename_limit, rename_limit))
1027 return 0;
1029 options->needed_rename_limit =
1030 num_sources > num_destinations ? num_sources : num_destinations;
1032 /* Are we running under -C -C? */
1033 if (!options->flags.find_copies_harder)
1034 return 1;
1036 /* Would we bust the limit if we were running under -C? */
1037 for (limited_sources = i = 0; i < num_sources; i++) {
1038 if (diff_unmodified_pair(rename_src[i].p))
1039 continue;
1040 limited_sources++;
1042 if (st_mult(num_destinations, limited_sources)
1043 <= st_mult(rename_limit, rename_limit))
1044 return 2;
1045 return 1;
1048 static int find_renames(struct diff_score *mx,
1049 int dst_cnt,
1050 int minimum_score,
1051 int copies,
1052 struct dir_rename_info *info,
1053 struct strintmap *dirs_removed)
1055 int count = 0, i;
1057 for (i = 0; i < dst_cnt * NUM_CANDIDATE_PER_DST; i++) {
1058 struct diff_rename_dst *dst;
1060 if ((mx[i].dst < 0) ||
1061 (mx[i].score < minimum_score))
1062 break; /* there is no more usable pair. */
1063 dst = &rename_dst[mx[i].dst];
1064 if (dst->is_rename)
1065 continue; /* already done, either exact or fuzzy. */
1066 if (!copies && rename_src[mx[i].src].p->one->rename_used)
1067 continue;
1068 record_rename_pair(mx[i].dst, mx[i].src, mx[i].score);
1069 count++;
1070 update_dir_rename_counts(info, dirs_removed,
1071 rename_src[mx[i].src].p->one->path,
1072 rename_dst[mx[i].dst].p->two->path);
1074 return count;
1077 static void remove_unneeded_paths_from_src(int detecting_copies,
1078 struct strintmap *interesting)
1080 int i, new_num_src;
1082 if (detecting_copies && !interesting)
1083 return; /* nothing to remove */
1084 if (break_idx)
1085 return; /* culling incompatible with break detection */
1088 * Note on reasons why we cull unneeded sources but not destinations:
1089 * 1) Pairings are stored in rename_dst (not rename_src), which we
1090 * need to keep around. So, we just can't cull rename_dst even
1091 * if we wanted to. But doing so wouldn't help because...
1093 * 2) There is a matrix pairwise comparison that follows the
1094 * "Performing inexact rename detection" progress message.
1095 * Iterating over the destinations is done in the outer loop,
1096 * hence we only iterate over each of those once and we can
1097 * easily skip the outer loop early if the destination isn't
1098 * relevant. That's only one check per destination path to
1099 * skip.
1101 * By contrast, the sources are iterated in the inner loop; if
1102 * we check whether a source can be skipped, then we'll be
1103 * checking it N separate times, once for each destination.
1104 * We don't want to have to iterate over known-not-needed
1105 * sources N times each, so avoid that by removing the sources
1106 * from rename_src here.
1108 for (i = 0, new_num_src = 0; i < rename_src_nr; i++) {
1109 struct diff_filespec *one = rename_src[i].p->one;
1112 * renames are stored in rename_dst, so if a rename has
1113 * already been detected using this source, we can just
1114 * remove the source knowing rename_dst has its info.
1116 if (!detecting_copies && one->rename_used)
1117 continue;
1119 /* If we don't care about the source path, skip it */
1120 if (interesting && !strintmap_contains(interesting, one->path))
1121 continue;
1123 if (new_num_src < i)
1124 memcpy(&rename_src[new_num_src], &rename_src[i],
1125 sizeof(struct diff_rename_src));
1126 new_num_src++;
1129 rename_src_nr = new_num_src;
1132 static void handle_early_known_dir_renames(struct dir_rename_info *info,
1133 struct strintmap *relevant_sources,
1134 struct strintmap *dirs_removed)
1137 * Directory renames are determined via an aggregate of all renames
1138 * under them and using a "majority wins" rule. The fact that
1139 * "majority wins", though, means we don't need all the renames
1140 * under the given directory, we only need enough to ensure we have
1141 * a majority.
1144 int i, new_num_src;
1145 struct hashmap_iter iter;
1146 struct strmap_entry *entry;
1148 if (!dirs_removed || !relevant_sources)
1149 return; /* nothing to cull */
1150 if (break_idx)
1151 return; /* culling incompatbile with break detection */
1154 * Supplement dir_rename_count with number of potential renames,
1155 * marking all potential rename sources as mapping to UNKNOWN_DIR.
1157 for (i = 0; i < rename_src_nr; i++) {
1158 char *old_dir;
1159 struct diff_filespec *one = rename_src[i].p->one;
1162 * sources that are part of a rename will have already been
1163 * removed by a prior call to remove_unneeded_paths_from_src()
1165 assert(!one->rename_used);
1167 old_dir = get_dirname(one->path);
1168 while (*old_dir != '\0' &&
1169 NOT_RELEVANT != strintmap_get(dirs_removed, old_dir)) {
1170 char *freeme = old_dir;
1172 increment_count(info, old_dir, UNKNOWN_DIR);
1173 old_dir = get_dirname(old_dir);
1175 /* Free resources we don't need anymore */
1176 free(freeme);
1179 * old_dir and new_dir free'd in increment_count, but
1180 * get_dirname() gives us a new pointer we need to free for
1181 * old_dir. Also, if the loop runs 0 times we need old_dir
1182 * to be freed.
1184 free(old_dir);
1188 * For any directory which we need a potential rename detected for
1189 * (i.e. those marked as RELEVANT_FOR_SELF in dirs_removed), check
1190 * whether we have enough renames to satisfy the "majority rules"
1191 * requirement such that detecting any more renames of files under
1192 * it won't change the result. For any such directory, mark that
1193 * we no longer need to detect a rename for it. However, since we
1194 * might need to still detect renames for an ancestor of that
1195 * directory, use RELEVANT_FOR_ANCESTOR.
1197 strmap_for_each_entry(info->dir_rename_count, &iter, entry) {
1198 /* entry->key is source_dir */
1199 struct strintmap *counts = entry->value;
1201 if (strintmap_get(dirs_removed, entry->key) ==
1202 RELEVANT_FOR_SELF &&
1203 dir_rename_already_determinable(counts)) {
1204 strintmap_set(dirs_removed, entry->key,
1205 RELEVANT_FOR_ANCESTOR);
1209 for (i = 0, new_num_src = 0; i < rename_src_nr; i++) {
1210 struct diff_filespec *one = rename_src[i].p->one;
1211 int val;
1213 val = strintmap_get(relevant_sources, one->path);
1216 * sources that were not found in relevant_sources should
1217 * have already been removed by a prior call to
1218 * remove_unneeded_paths_from_src()
1220 assert(val != -1);
1222 if (val == RELEVANT_LOCATION) {
1223 int removable = 1;
1224 char *dir = get_dirname(one->path);
1225 while (1) {
1226 char *freeme = dir;
1227 int res = strintmap_get(dirs_removed, dir);
1229 /* Quit if not found or irrelevant */
1230 if (res == NOT_RELEVANT)
1231 break;
1232 /* If RELEVANT_FOR_SELF, can't remove */
1233 if (res == RELEVANT_FOR_SELF) {
1234 removable = 0;
1235 break;
1237 /* Else continue searching upwards */
1238 assert(res == RELEVANT_FOR_ANCESTOR);
1239 dir = get_dirname(dir);
1240 free(freeme);
1242 free(dir);
1243 if (removable) {
1244 strintmap_set(relevant_sources, one->path,
1245 RELEVANT_NO_MORE);
1246 continue;
1250 if (new_num_src < i)
1251 memcpy(&rename_src[new_num_src], &rename_src[i],
1252 sizeof(struct diff_rename_src));
1253 new_num_src++;
1256 rename_src_nr = new_num_src;
1259 void diffcore_rename_extended(struct diff_options *options,
1260 struct strintmap *relevant_sources,
1261 struct strintmap *dirs_removed,
1262 struct strmap *dir_rename_count,
1263 struct strmap *cached_pairs)
1265 int detect_rename = options->detect_rename;
1266 int minimum_score = options->rename_score;
1267 struct diff_queue_struct *q = &diff_queued_diff;
1268 struct diff_queue_struct outq;
1269 struct diff_score *mx;
1270 int i, j, rename_count, skip_unmodified = 0;
1271 int num_destinations, dst_cnt;
1272 int num_sources, want_copies;
1273 struct progress *progress = NULL;
1274 struct dir_rename_info info;
1276 trace2_region_enter("diff", "setup", options->repo);
1277 info.setup = 0;
1278 assert(!dir_rename_count || strmap_empty(dir_rename_count));
1279 want_copies = (detect_rename == DIFF_DETECT_COPY);
1280 if (dirs_removed && (break_idx || want_copies))
1281 BUG("dirs_removed incompatible with break/copy detection");
1282 if (break_idx && relevant_sources)
1283 BUG("break detection incompatible with source specification");
1284 if (!minimum_score)
1285 minimum_score = DEFAULT_RENAME_SCORE;
1287 for (i = 0; i < q->nr; i++) {
1288 struct diff_filepair *p = q->queue[i];
1289 if (!DIFF_FILE_VALID(p->one)) {
1290 if (!DIFF_FILE_VALID(p->two))
1291 continue; /* unmerged */
1292 else if (options->single_follow &&
1293 strcmp(options->single_follow, p->two->path))
1294 continue; /* not interested */
1295 else if (!options->flags.rename_empty &&
1296 is_empty_blob_oid(&p->two->oid))
1297 continue;
1298 else if (add_rename_dst(p) < 0) {
1299 warning("skipping rename detection, detected"
1300 " duplicate destination '%s'",
1301 p->two->path);
1302 goto cleanup;
1305 else if (!options->flags.rename_empty &&
1306 is_empty_blob_oid(&p->one->oid))
1307 continue;
1308 else if (!DIFF_PAIR_UNMERGED(p) && !DIFF_FILE_VALID(p->two)) {
1310 * If the source is a broken "delete", and
1311 * they did not really want to get broken,
1312 * that means the source actually stays.
1313 * So we increment the "rename_used" score
1314 * by one, to indicate ourselves as a user
1316 if (p->broken_pair && !p->score)
1317 p->one->rename_used++;
1318 register_rename_src(p);
1320 else if (want_copies) {
1322 * Increment the "rename_used" score by
1323 * one, to indicate ourselves as a user.
1325 p->one->rename_used++;
1326 register_rename_src(p);
1329 trace2_region_leave("diff", "setup", options->repo);
1330 if (rename_dst_nr == 0 || rename_src_nr == 0)
1331 goto cleanup; /* nothing to do */
1333 trace2_region_enter("diff", "exact renames", options->repo);
1335 * We really want to cull the candidates list early
1336 * with cheap tests in order to avoid doing deltas.
1338 rename_count = find_exact_renames(options);
1339 trace2_region_leave("diff", "exact renames", options->repo);
1341 /* Did we only want exact renames? */
1342 if (minimum_score == MAX_SCORE)
1343 goto cleanup;
1345 num_sources = rename_src_nr;
1347 if (want_copies || break_idx) {
1349 * Cull sources:
1350 * - remove ones corresponding to exact renames
1351 * - remove ones not found in relevant_sources
1353 trace2_region_enter("diff", "cull after exact", options->repo);
1354 remove_unneeded_paths_from_src(want_copies, relevant_sources);
1355 trace2_region_leave("diff", "cull after exact", options->repo);
1356 } else {
1357 /* Determine minimum score to match basenames */
1358 double factor = 0.5;
1359 char *basename_factor = getenv("GIT_BASENAME_FACTOR");
1360 int min_basename_score;
1362 if (basename_factor)
1363 factor = strtol(basename_factor, NULL, 10)/100.0;
1364 assert(factor >= 0.0 && factor <= 1.0);
1365 min_basename_score = minimum_score +
1366 (int)(factor * (MAX_SCORE - minimum_score));
1369 * Cull sources:
1370 * - remove ones involved in renames (found via exact match)
1372 trace2_region_enter("diff", "cull after exact", options->repo);
1373 remove_unneeded_paths_from_src(want_copies, NULL);
1374 trace2_region_leave("diff", "cull after exact", options->repo);
1376 /* Preparation for basename-driven matching. */
1377 trace2_region_enter("diff", "dir rename setup", options->repo);
1378 initialize_dir_rename_info(&info, relevant_sources,
1379 dirs_removed, dir_rename_count,
1380 cached_pairs);
1381 trace2_region_leave("diff", "dir rename setup", options->repo);
1383 /* Utilize file basenames to quickly find renames. */
1384 trace2_region_enter("diff", "basename matches", options->repo);
1385 rename_count += find_basename_matches(options,
1386 min_basename_score,
1387 &info,
1388 relevant_sources,
1389 dirs_removed);
1390 trace2_region_leave("diff", "basename matches", options->repo);
1393 * Cull sources, again:
1394 * - remove ones involved in renames (found via basenames)
1395 * - remove ones not found in relevant_sources
1396 * and
1397 * - remove ones in relevant_sources which are needed only
1398 * for directory renames IF no ancestory directory
1399 * actually needs to know any more individual path
1400 * renames under them
1402 trace2_region_enter("diff", "cull basename", options->repo);
1403 remove_unneeded_paths_from_src(want_copies, relevant_sources);
1404 handle_early_known_dir_renames(&info, relevant_sources,
1405 dirs_removed);
1406 trace2_region_leave("diff", "cull basename", options->repo);
1409 /* Calculate how many rename destinations are left */
1410 num_destinations = (rename_dst_nr - rename_count);
1411 num_sources = rename_src_nr; /* rename_src_nr reflects lower number */
1413 /* All done? */
1414 if (!num_destinations || !num_sources)
1415 goto cleanup;
1417 switch (too_many_rename_candidates(num_destinations, num_sources,
1418 options)) {
1419 case 1:
1420 goto cleanup;
1421 case 2:
1422 options->degraded_cc_to_c = 1;
1423 skip_unmodified = 1;
1424 break;
1425 default:
1426 break;
1429 trace2_region_enter("diff", "inexact renames", options->repo);
1430 if (options->show_rename_progress) {
1431 progress = start_delayed_progress(
1432 _("Performing inexact rename detection"),
1433 (uint64_t)num_destinations * (uint64_t)num_sources);
1436 CALLOC_ARRAY(mx, st_mult(NUM_CANDIDATE_PER_DST, num_destinations));
1437 for (dst_cnt = i = 0; i < rename_dst_nr; i++) {
1438 struct diff_filespec *two = rename_dst[i].p->two;
1439 struct diff_score *m;
1441 if (rename_dst[i].is_rename)
1442 continue; /* exact or basename match already handled */
1444 m = &mx[dst_cnt * NUM_CANDIDATE_PER_DST];
1445 for (j = 0; j < NUM_CANDIDATE_PER_DST; j++)
1446 m[j].dst = -1;
1448 for (j = 0; j < rename_src_nr; j++) {
1449 struct diff_filespec *one = rename_src[j].p->one;
1450 struct diff_score this_src;
1452 assert(!one->rename_used || want_copies || break_idx);
1454 if (skip_unmodified &&
1455 diff_unmodified_pair(rename_src[j].p))
1456 continue;
1458 this_src.score = estimate_similarity(options->repo,
1459 one, two,
1460 minimum_score,
1461 skip_unmodified);
1462 this_src.name_score = basename_same(one, two);
1463 this_src.dst = i;
1464 this_src.src = j;
1465 record_if_better(m, &this_src);
1467 * Once we run estimate_similarity,
1468 * We do not need the text anymore.
1470 diff_free_filespec_blob(one);
1471 diff_free_filespec_blob(two);
1473 dst_cnt++;
1474 display_progress(progress,
1475 (uint64_t)dst_cnt * (uint64_t)num_sources);
1477 stop_progress(&progress);
1479 /* cost matrix sorted by most to least similar pair */
1480 STABLE_QSORT(mx, dst_cnt * NUM_CANDIDATE_PER_DST, score_compare);
1482 rename_count += find_renames(mx, dst_cnt, minimum_score, 0,
1483 &info, dirs_removed);
1484 if (want_copies)
1485 rename_count += find_renames(mx, dst_cnt, minimum_score, 1,
1486 &info, dirs_removed);
1487 free(mx);
1488 trace2_region_leave("diff", "inexact renames", options->repo);
1490 cleanup:
1491 /* At this point, we have found some renames and copies and they
1492 * are recorded in rename_dst. The original list is still in *q.
1494 trace2_region_enter("diff", "write back to queue", options->repo);
1495 DIFF_QUEUE_CLEAR(&outq);
1496 for (i = 0; i < q->nr; i++) {
1497 struct diff_filepair *p = q->queue[i];
1498 struct diff_filepair *pair_to_free = NULL;
1500 if (DIFF_PAIR_UNMERGED(p)) {
1501 diff_q(&outq, p);
1503 else if (!DIFF_FILE_VALID(p->one) && DIFF_FILE_VALID(p->two)) {
1504 /* Creation */
1505 diff_q(&outq, p);
1507 else if (DIFF_FILE_VALID(p->one) && !DIFF_FILE_VALID(p->two)) {
1509 * Deletion
1511 * We would output this delete record if:
1513 * (1) this is a broken delete and the counterpart
1514 * broken create remains in the output; or
1515 * (2) this is not a broken delete, and rename_dst
1516 * does not have a rename/copy to move p->one->path
1517 * out of existence.
1519 * Otherwise, the counterpart broken create
1520 * has been turned into a rename-edit; or
1521 * delete did not have a matching create to
1522 * begin with.
1524 if (DIFF_PAIR_BROKEN(p)) {
1525 /* broken delete */
1526 struct diff_rename_dst *dst = locate_rename_dst(p);
1527 if (!dst)
1528 BUG("tracking failed somehow; failed to find associated dst for broken pair");
1529 if (dst->is_rename)
1530 /* counterpart is now rename/copy */
1531 pair_to_free = p;
1533 else {
1534 if (p->one->rename_used)
1535 /* this path remains */
1536 pair_to_free = p;
1539 if (!pair_to_free)
1540 diff_q(&outq, p);
1542 else if (!diff_unmodified_pair(p))
1543 /* all the usual ones need to be kept */
1544 diff_q(&outq, p);
1545 else
1546 /* no need to keep unmodified pairs; FIXME: remove earlier? */
1547 pair_to_free = p;
1549 if (pair_to_free)
1550 diff_free_filepair(pair_to_free);
1552 diff_debug_queue("done copying original", &outq);
1554 free(q->queue);
1555 *q = outq;
1556 diff_debug_queue("done collapsing", q);
1558 for (i = 0; i < rename_dst_nr; i++)
1559 if (rename_dst[i].filespec_to_free)
1560 free_filespec(rename_dst[i].filespec_to_free);
1562 cleanup_dir_rename_info(&info, dirs_removed, dir_rename_count != NULL);
1563 FREE_AND_NULL(rename_dst);
1564 rename_dst_nr = rename_dst_alloc = 0;
1565 FREE_AND_NULL(rename_src);
1566 rename_src_nr = rename_src_alloc = 0;
1567 if (break_idx) {
1568 strintmap_clear(break_idx);
1569 FREE_AND_NULL(break_idx);
1571 trace2_region_leave("diff", "write back to queue", options->repo);
1572 return;
1575 void diffcore_rename(struct diff_options *options)
1577 diffcore_rename_extended(options, NULL, NULL, NULL, NULL);