replace_object.c: use ALLOC_GROW() in register_replace_object()
[git.git] / diffcore-rename.c
blobf54d5bf479f40752a1e65a5c5fdadc81a37facee
1 /*
2 * Copyright (C) 2005 Junio C Hamano
3 */
4 #include "cache.h"
5 #include "diff.h"
6 #include "diffcore.h"
7 #include "hash.h"
8 #include "progress.h"
10 /* Table of rename/copy destinations */
12 static struct diff_rename_dst {
13 struct diff_filespec *two;
14 struct diff_filepair *pair;
15 } *rename_dst;
16 static int rename_dst_nr, rename_dst_alloc;
18 static struct diff_rename_dst *locate_rename_dst(struct diff_filespec *two,
19 int insert_ok)
21 int first, last;
23 first = 0;
24 last = rename_dst_nr;
25 while (last > first) {
26 int next = (last + first) >> 1;
27 struct diff_rename_dst *dst = &(rename_dst[next]);
28 int cmp = strcmp(two->path, dst->two->path);
29 if (!cmp)
30 return dst;
31 if (cmp < 0) {
32 last = next;
33 continue;
35 first = next+1;
37 /* not found */
38 if (!insert_ok)
39 return NULL;
40 /* insert to make it at "first" */
41 ALLOC_GROW(rename_dst, rename_dst_nr + 1, rename_dst_alloc);
42 rename_dst_nr++;
43 if (first < rename_dst_nr)
44 memmove(rename_dst + first + 1, rename_dst + first,
45 (rename_dst_nr - first - 1) * sizeof(*rename_dst));
46 rename_dst[first].two = alloc_filespec(two->path);
47 fill_filespec(rename_dst[first].two, two->sha1, two->sha1_valid, two->mode);
48 rename_dst[first].pair = NULL;
49 return &(rename_dst[first]);
52 /* Table of rename/copy src files */
53 static struct diff_rename_src {
54 struct diff_filepair *p;
55 unsigned short score; /* to remember the break score */
56 } *rename_src;
57 static int rename_src_nr, rename_src_alloc;
59 static struct diff_rename_src *register_rename_src(struct diff_filepair *p)
61 int first, last;
62 struct diff_filespec *one = p->one;
63 unsigned short score = p->score;
65 first = 0;
66 last = rename_src_nr;
67 while (last > first) {
68 int next = (last + first) >> 1;
69 struct diff_rename_src *src = &(rename_src[next]);
70 int cmp = strcmp(one->path, src->p->one->path);
71 if (!cmp)
72 return src;
73 if (cmp < 0) {
74 last = next;
75 continue;
77 first = next+1;
80 /* insert to make it at "first" */
81 ALLOC_GROW(rename_src, rename_src_nr + 1, rename_src_alloc);
82 rename_src_nr++;
83 if (first < rename_src_nr)
84 memmove(rename_src + first + 1, rename_src + first,
85 (rename_src_nr - first - 1) * sizeof(*rename_src));
86 rename_src[first].p = p;
87 rename_src[first].score = score;
88 return &(rename_src[first]);
91 static int basename_same(struct diff_filespec *src, struct diff_filespec *dst)
93 int src_len = strlen(src->path), dst_len = strlen(dst->path);
94 while (src_len && dst_len) {
95 char c1 = src->path[--src_len];
96 char c2 = dst->path[--dst_len];
97 if (c1 != c2)
98 return 0;
99 if (c1 == '/')
100 return 1;
102 return (!src_len || src->path[src_len - 1] == '/') &&
103 (!dst_len || dst->path[dst_len - 1] == '/');
106 struct diff_score {
107 int src; /* index in rename_src */
108 int dst; /* index in rename_dst */
109 unsigned short score;
110 short name_score;
113 static int estimate_similarity(struct diff_filespec *src,
114 struct diff_filespec *dst,
115 int minimum_score)
117 /* src points at a file that existed in the original tree (or
118 * optionally a file in the destination tree) and dst points
119 * at a newly created file. They may be quite similar, in which
120 * case we want to say src is renamed to dst or src is copied into
121 * dst, and then some edit has been applied to dst.
123 * Compare them and return how similar they are, representing
124 * the score as an integer between 0 and MAX_SCORE.
126 * When there is an exact match, it is considered a better
127 * match than anything else; the destination does not even
128 * call into this function in that case.
130 unsigned long max_size, delta_size, base_size, src_copied, literal_added;
131 unsigned long delta_limit;
132 int score;
134 /* We deal only with regular files. Symlink renames are handled
135 * only when they are exact matches --- in other words, no edits
136 * after renaming.
138 if (!S_ISREG(src->mode) || !S_ISREG(dst->mode))
139 return 0;
142 * Need to check that source and destination sizes are
143 * filled in before comparing them.
145 * If we already have "cnt_data" filled in, we know it's
146 * all good (avoid checking the size for zero, as that
147 * is a possible size - we really should have a flag to
148 * say whether the size is valid or not!)
150 if (!src->cnt_data && diff_populate_filespec(src, 1))
151 return 0;
152 if (!dst->cnt_data && diff_populate_filespec(dst, 1))
153 return 0;
155 max_size = ((src->size > dst->size) ? src->size : dst->size);
156 base_size = ((src->size < dst->size) ? src->size : dst->size);
157 delta_size = max_size - base_size;
159 /* We would not consider edits that change the file size so
160 * drastically. delta_size must be smaller than
161 * (MAX_SCORE-minimum_score)/MAX_SCORE * min(src->size, dst->size).
163 * Note that base_size == 0 case is handled here already
164 * and the final score computation below would not have a
165 * divide-by-zero issue.
167 if (max_size * (MAX_SCORE-minimum_score) < delta_size * MAX_SCORE)
168 return 0;
170 if (!src->cnt_data && diff_populate_filespec(src, 0))
171 return 0;
172 if (!dst->cnt_data && diff_populate_filespec(dst, 0))
173 return 0;
175 delta_limit = (unsigned long)
176 (base_size * (MAX_SCORE-minimum_score) / MAX_SCORE);
177 if (diffcore_count_changes(src, dst,
178 &src->cnt_data, &dst->cnt_data,
179 delta_limit,
180 &src_copied, &literal_added))
181 return 0;
183 /* How similar are they?
184 * what percentage of material in dst are from source?
186 if (!dst->size)
187 score = 0; /* should not happen */
188 else
189 score = (int)(src_copied * MAX_SCORE / max_size);
190 return score;
193 static void record_rename_pair(int dst_index, int src_index, int score)
195 struct diff_filespec *src, *dst;
196 struct diff_filepair *dp;
198 if (rename_dst[dst_index].pair)
199 die("internal error: dst already matched.");
201 src = rename_src[src_index].p->one;
202 src->rename_used++;
203 src->count++;
205 dst = rename_dst[dst_index].two;
206 dst->count++;
208 dp = diff_queue(NULL, src, dst);
209 dp->renamed_pair = 1;
210 if (!strcmp(src->path, dst->path))
211 dp->score = rename_src[src_index].score;
212 else
213 dp->score = score;
214 rename_dst[dst_index].pair = dp;
218 * We sort the rename similarity matrix with the score, in descending
219 * order (the most similar first).
221 static int score_compare(const void *a_, const void *b_)
223 const struct diff_score *a = a_, *b = b_;
225 /* sink the unused ones to the bottom */
226 if (a->dst < 0)
227 return (0 <= b->dst);
228 else if (b->dst < 0)
229 return -1;
231 if (a->score == b->score)
232 return b->name_score - a->name_score;
234 return b->score - a->score;
237 struct file_similarity {
238 int src_dst, index;
239 struct diff_filespec *filespec;
240 struct file_similarity *next;
243 static int find_identical_files(struct file_similarity *src,
244 struct file_similarity *dst,
245 struct diff_options *options)
247 int renames = 0;
250 * Walk over all the destinations ...
252 do {
253 struct diff_filespec *target = dst->filespec;
254 struct file_similarity *p, *best;
255 int i = 100, best_score = -1;
258 * .. to find the best source match
260 best = NULL;
261 for (p = src; p; p = p->next) {
262 int score;
263 struct diff_filespec *source = p->filespec;
265 /* False hash collision? */
266 if (hashcmp(source->sha1, target->sha1))
267 continue;
268 /* Non-regular files? If so, the modes must match! */
269 if (!S_ISREG(source->mode) || !S_ISREG(target->mode)) {
270 if (source->mode != target->mode)
271 continue;
273 /* Give higher scores to sources that haven't been used already */
274 score = !source->rename_used;
275 if (source->rename_used && options->detect_rename != DIFF_DETECT_COPY)
276 continue;
277 score += basename_same(source, target);
278 if (score > best_score) {
279 best = p;
280 best_score = score;
281 if (score == 2)
282 break;
285 /* Too many identical alternatives? Pick one */
286 if (!--i)
287 break;
289 if (best) {
290 record_rename_pair(dst->index, best->index, MAX_SCORE);
291 renames++;
293 } while ((dst = dst->next) != NULL);
294 return renames;
297 static void free_similarity_list(struct file_similarity *p)
299 while (p) {
300 struct file_similarity *entry = p;
301 p = p->next;
302 free(entry);
306 static int find_same_files(void *ptr, void *data)
308 int ret;
309 struct file_similarity *p = ptr;
310 struct file_similarity *src = NULL, *dst = NULL;
311 struct diff_options *options = data;
313 /* Split the hash list up into sources and destinations */
314 do {
315 struct file_similarity *entry = p;
316 p = p->next;
317 if (entry->src_dst < 0) {
318 entry->next = src;
319 src = entry;
320 } else {
321 entry->next = dst;
322 dst = entry;
324 } while (p);
327 * If we have both sources *and* destinations, see if
328 * we can match them up
330 ret = (src && dst) ? find_identical_files(src, dst, options) : 0;
332 /* Free the hashes and return the number of renames found */
333 free_similarity_list(src);
334 free_similarity_list(dst);
335 return ret;
338 static unsigned int hash_filespec(struct diff_filespec *filespec)
340 unsigned int hash;
341 if (!filespec->sha1_valid) {
342 if (diff_populate_filespec(filespec, 0))
343 return 0;
344 hash_sha1_file(filespec->data, filespec->size, "blob", filespec->sha1);
346 memcpy(&hash, filespec->sha1, sizeof(hash));
347 return hash;
350 static void insert_file_table(struct hash_table *table, int src_dst, int index, struct diff_filespec *filespec)
352 void **pos;
353 unsigned int hash;
354 struct file_similarity *entry = xmalloc(sizeof(*entry));
356 entry->src_dst = src_dst;
357 entry->index = index;
358 entry->filespec = filespec;
359 entry->next = NULL;
361 hash = hash_filespec(filespec);
362 pos = insert_hash(hash, entry, table);
364 /* We already had an entry there? */
365 if (pos) {
366 entry->next = *pos;
367 *pos = entry;
372 * Find exact renames first.
374 * The first round matches up the up-to-date entries,
375 * and then during the second round we try to match
376 * cache-dirty entries as well.
378 static int find_exact_renames(struct diff_options *options)
380 int i;
381 struct hash_table file_table;
383 init_hash(&file_table);
384 preallocate_hash(&file_table, rename_src_nr + rename_dst_nr);
385 for (i = 0; i < rename_src_nr; i++)
386 insert_file_table(&file_table, -1, i, rename_src[i].p->one);
388 for (i = 0; i < rename_dst_nr; i++)
389 insert_file_table(&file_table, 1, i, rename_dst[i].two);
391 /* Find the renames */
392 i = for_each_hash(&file_table, find_same_files, options);
394 /* .. and free the hash data structure */
395 free_hash(&file_table);
397 return i;
400 #define NUM_CANDIDATE_PER_DST 4
401 static void record_if_better(struct diff_score m[], struct diff_score *o)
403 int i, worst;
405 /* find the worst one */
406 worst = 0;
407 for (i = 1; i < NUM_CANDIDATE_PER_DST; i++)
408 if (score_compare(&m[i], &m[worst]) > 0)
409 worst = i;
411 /* is it better than the worst one? */
412 if (score_compare(&m[worst], o) > 0)
413 m[worst] = *o;
417 * Returns:
418 * 0 if we are under the limit;
419 * 1 if we need to disable inexact rename detection;
420 * 2 if we would be under the limit if we were given -C instead of -C -C.
422 static int too_many_rename_candidates(int num_create,
423 struct diff_options *options)
425 int rename_limit = options->rename_limit;
426 int num_src = rename_src_nr;
427 int i;
429 options->needed_rename_limit = 0;
432 * This basically does a test for the rename matrix not
433 * growing larger than a "rename_limit" square matrix, ie:
435 * num_create * num_src > rename_limit * rename_limit
437 * but handles the potential overflow case specially (and we
438 * assume at least 32-bit integers)
440 if (rename_limit <= 0 || rename_limit > 32767)
441 rename_limit = 32767;
442 if ((num_create <= rename_limit || num_src <= rename_limit) &&
443 (num_create * num_src <= rename_limit * rename_limit))
444 return 0;
446 options->needed_rename_limit =
447 num_src > num_create ? num_src : num_create;
449 /* Are we running under -C -C? */
450 if (!DIFF_OPT_TST(options, FIND_COPIES_HARDER))
451 return 1;
453 /* Would we bust the limit if we were running under -C? */
454 for (num_src = i = 0; i < rename_src_nr; i++) {
455 if (diff_unmodified_pair(rename_src[i].p))
456 continue;
457 num_src++;
459 if ((num_create <= rename_limit || num_src <= rename_limit) &&
460 (num_create * num_src <= rename_limit * rename_limit))
461 return 2;
462 return 1;
465 static int find_renames(struct diff_score *mx, int dst_cnt, int minimum_score, int copies)
467 int count = 0, i;
469 for (i = 0; i < dst_cnt * NUM_CANDIDATE_PER_DST; i++) {
470 struct diff_rename_dst *dst;
472 if ((mx[i].dst < 0) ||
473 (mx[i].score < minimum_score))
474 break; /* there is no more usable pair. */
475 dst = &rename_dst[mx[i].dst];
476 if (dst->pair)
477 continue; /* already done, either exact or fuzzy. */
478 if (!copies && rename_src[mx[i].src].p->one->rename_used)
479 continue;
480 record_rename_pair(mx[i].dst, mx[i].src, mx[i].score);
481 count++;
483 return count;
486 void diffcore_rename(struct diff_options *options)
488 int detect_rename = options->detect_rename;
489 int minimum_score = options->rename_score;
490 struct diff_queue_struct *q = &diff_queued_diff;
491 struct diff_queue_struct outq;
492 struct diff_score *mx;
493 int i, j, rename_count, skip_unmodified = 0;
494 int num_create, dst_cnt;
495 struct progress *progress = NULL;
497 if (!minimum_score)
498 minimum_score = DEFAULT_RENAME_SCORE;
500 for (i = 0; i < q->nr; i++) {
501 struct diff_filepair *p = q->queue[i];
502 if (!DIFF_FILE_VALID(p->one)) {
503 if (!DIFF_FILE_VALID(p->two))
504 continue; /* unmerged */
505 else if (options->single_follow &&
506 strcmp(options->single_follow, p->two->path))
507 continue; /* not interested */
508 else if (!DIFF_OPT_TST(options, RENAME_EMPTY) &&
509 is_empty_blob_sha1(p->two->sha1))
510 continue;
511 else
512 locate_rename_dst(p->two, 1);
514 else if (!DIFF_OPT_TST(options, RENAME_EMPTY) &&
515 is_empty_blob_sha1(p->one->sha1))
516 continue;
517 else if (!DIFF_PAIR_UNMERGED(p) && !DIFF_FILE_VALID(p->two)) {
519 * If the source is a broken "delete", and
520 * they did not really want to get broken,
521 * that means the source actually stays.
522 * So we increment the "rename_used" score
523 * by one, to indicate ourselves as a user
525 if (p->broken_pair && !p->score)
526 p->one->rename_used++;
527 register_rename_src(p);
529 else if (detect_rename == DIFF_DETECT_COPY) {
531 * Increment the "rename_used" score by
532 * one, to indicate ourselves as a user.
534 p->one->rename_used++;
535 register_rename_src(p);
538 if (rename_dst_nr == 0 || rename_src_nr == 0)
539 goto cleanup; /* nothing to do */
542 * We really want to cull the candidates list early
543 * with cheap tests in order to avoid doing deltas.
545 rename_count = find_exact_renames(options);
547 /* Did we only want exact renames? */
548 if (minimum_score == MAX_SCORE)
549 goto cleanup;
552 * Calculate how many renames are left (but all the source
553 * files still remain as options for rename/copies!)
555 num_create = (rename_dst_nr - rename_count);
557 /* All done? */
558 if (!num_create)
559 goto cleanup;
561 switch (too_many_rename_candidates(num_create, options)) {
562 case 1:
563 goto cleanup;
564 case 2:
565 options->degraded_cc_to_c = 1;
566 skip_unmodified = 1;
567 break;
568 default:
569 break;
572 if (options->show_rename_progress) {
573 progress = start_progress_delay(
574 "Performing inexact rename detection",
575 rename_dst_nr * rename_src_nr, 50, 1);
578 mx = xcalloc(num_create * NUM_CANDIDATE_PER_DST, sizeof(*mx));
579 for (dst_cnt = i = 0; i < rename_dst_nr; i++) {
580 struct diff_filespec *two = rename_dst[i].two;
581 struct diff_score *m;
583 if (rename_dst[i].pair)
584 continue; /* dealt with exact match already. */
586 m = &mx[dst_cnt * NUM_CANDIDATE_PER_DST];
587 for (j = 0; j < NUM_CANDIDATE_PER_DST; j++)
588 m[j].dst = -1;
590 for (j = 0; j < rename_src_nr; j++) {
591 struct diff_filespec *one = rename_src[j].p->one;
592 struct diff_score this_src;
594 if (skip_unmodified &&
595 diff_unmodified_pair(rename_src[j].p))
596 continue;
598 this_src.score = estimate_similarity(one, two,
599 minimum_score);
600 this_src.name_score = basename_same(one, two);
601 this_src.dst = i;
602 this_src.src = j;
603 record_if_better(m, &this_src);
605 * Once we run estimate_similarity,
606 * We do not need the text anymore.
608 diff_free_filespec_blob(one);
609 diff_free_filespec_blob(two);
611 dst_cnt++;
612 display_progress(progress, (i+1)*rename_src_nr);
614 stop_progress(&progress);
616 /* cost matrix sorted by most to least similar pair */
617 qsort(mx, dst_cnt * NUM_CANDIDATE_PER_DST, sizeof(*mx), score_compare);
619 rename_count += find_renames(mx, dst_cnt, minimum_score, 0);
620 if (detect_rename == DIFF_DETECT_COPY)
621 rename_count += find_renames(mx, dst_cnt, minimum_score, 1);
622 free(mx);
624 cleanup:
625 /* At this point, we have found some renames and copies and they
626 * are recorded in rename_dst. The original list is still in *q.
628 DIFF_QUEUE_CLEAR(&outq);
629 for (i = 0; i < q->nr; i++) {
630 struct diff_filepair *p = q->queue[i];
631 struct diff_filepair *pair_to_free = NULL;
633 if (DIFF_PAIR_UNMERGED(p)) {
634 diff_q(&outq, p);
636 else if (!DIFF_FILE_VALID(p->one) && DIFF_FILE_VALID(p->two)) {
638 * Creation
640 * We would output this create record if it has
641 * not been turned into a rename/copy already.
643 struct diff_rename_dst *dst =
644 locate_rename_dst(p->two, 0);
645 if (dst && dst->pair) {
646 diff_q(&outq, dst->pair);
647 pair_to_free = p;
649 else
650 /* no matching rename/copy source, so
651 * record this as a creation.
653 diff_q(&outq, p);
655 else if (DIFF_FILE_VALID(p->one) && !DIFF_FILE_VALID(p->two)) {
657 * Deletion
659 * We would output this delete record if:
661 * (1) this is a broken delete and the counterpart
662 * broken create remains in the output; or
663 * (2) this is not a broken delete, and rename_dst
664 * does not have a rename/copy to move p->one->path
665 * out of existence.
667 * Otherwise, the counterpart broken create
668 * has been turned into a rename-edit; or
669 * delete did not have a matching create to
670 * begin with.
672 if (DIFF_PAIR_BROKEN(p)) {
673 /* broken delete */
674 struct diff_rename_dst *dst =
675 locate_rename_dst(p->one, 0);
676 if (dst && dst->pair)
677 /* counterpart is now rename/copy */
678 pair_to_free = p;
680 else {
681 if (p->one->rename_used)
682 /* this path remains */
683 pair_to_free = p;
686 if (pair_to_free)
688 else
689 diff_q(&outq, p);
691 else if (!diff_unmodified_pair(p))
692 /* all the usual ones need to be kept */
693 diff_q(&outq, p);
694 else
695 /* no need to keep unmodified pairs */
696 pair_to_free = p;
698 if (pair_to_free)
699 diff_free_filepair(pair_to_free);
701 diff_debug_queue("done copying original", &outq);
703 free(q->queue);
704 *q = outq;
705 diff_debug_queue("done collapsing", q);
707 for (i = 0; i < rename_dst_nr; i++)
708 free_filespec(rename_dst[i].two);
710 free(rename_dst);
711 rename_dst = NULL;
712 rename_dst_nr = rename_dst_alloc = 0;
713 free(rename_src);
714 rename_src = NULL;
715 rename_src_nr = rename_src_alloc = 0;
716 return;