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"
9
10/* Table of rename/copy destinations */
11
12static struct diff_rename_dst {
13 struct diff_filespec *two;
14 struct diff_filepair *pair;
15} *rename_dst;
16static int rename_dst_nr, rename_dst_alloc;
17
18static struct diff_rename_dst *locate_rename_dst(struct diff_filespec *two,
19 int insert_ok)
20{
21 int first, last;
22
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;
34 }
35 first = next+1;
36 }
37 /* not found */
38 if (!insert_ok)
39 return NULL;
40 /* insert to make it at "first" */
41 if (rename_dst_alloc <= rename_dst_nr) {
42 rename_dst_alloc = alloc_nr(rename_dst_alloc);
43 rename_dst = xrealloc(rename_dst,
44 rename_dst_alloc * sizeof(*rename_dst));
45 }
46 rename_dst_nr++;
47 if (first < rename_dst_nr)
48 memmove(rename_dst + first + 1, rename_dst + first,
49 (rename_dst_nr - first - 1) * sizeof(*rename_dst));
50 rename_dst[first].two = alloc_filespec(two->path);
51 fill_filespec(rename_dst[first].two, two->sha1, two->mode);
52 rename_dst[first].pair = NULL;
53 return &(rename_dst[first]);
54}
55
56/* Table of rename/copy src files */
57static struct diff_rename_src {
58 struct diff_filepair *p;
59 unsigned short score; /* to remember the break score */
60} *rename_src;
61static int rename_src_nr, rename_src_alloc;
62
63static struct diff_rename_src *register_rename_src(struct diff_filepair *p)
64{
65 int first, last;
66 struct diff_filespec *one = p->one;
67 unsigned short score = p->score;
68
69 first = 0;
70 last = rename_src_nr;
71 while (last > first) {
72 int next = (last + first) >> 1;
73 struct diff_rename_src *src = &(rename_src[next]);
74 int cmp = strcmp(one->path, src->p->one->path);
75 if (!cmp)
76 return src;
77 if (cmp < 0) {
78 last = next;
79 continue;
80 }
81 first = next+1;
82 }
83
84 /* insert to make it at "first" */
85 if (rename_src_alloc <= rename_src_nr) {
86 rename_src_alloc = alloc_nr(rename_src_alloc);
87 rename_src = xrealloc(rename_src,
88 rename_src_alloc * sizeof(*rename_src));
89 }
90 rename_src_nr++;
91 if (first < rename_src_nr)
92 memmove(rename_src + first + 1, rename_src + first,
93 (rename_src_nr - first - 1) * sizeof(*rename_src));
94 rename_src[first].p = p;
95 rename_src[first].score = score;
96 return &(rename_src[first]);
97}
98
99static int basename_same(struct diff_filespec *src, struct diff_filespec *dst)
100{
101 int src_len = strlen(src->path), dst_len = strlen(dst->path);
102 while (src_len && dst_len) {
103 char c1 = src->path[--src_len];
104 char c2 = dst->path[--dst_len];
105 if (c1 != c2)
106 return 0;
107 if (c1 == '/')
108 return 1;
109 }
110 return (!src_len || src->path[src_len - 1] == '/') &&
111 (!dst_len || dst->path[dst_len - 1] == '/');
112}
113
114struct diff_score {
115 int src; /* index in rename_src */
116 int dst; /* index in rename_dst */
117 unsigned short score;
118 short name_score;
119};
120
121static int estimate_similarity(struct diff_filespec *src,
122 struct diff_filespec *dst,
123 int minimum_score)
124{
125 /* src points at a file that existed in the original tree (or
126 * optionally a file in the destination tree) and dst points
127 * at a newly created file. They may be quite similar, in which
128 * case we want to say src is renamed to dst or src is copied into
129 * dst, and then some edit has been applied to dst.
130 *
131 * Compare them and return how similar they are, representing
132 * the score as an integer between 0 and MAX_SCORE.
133 *
134 * When there is an exact match, it is considered a better
135 * match than anything else; the destination does not even
136 * call into this function in that case.
137 */
138 unsigned long max_size, delta_size, base_size, src_copied, literal_added;
139 unsigned long delta_limit;
140 int score;
141
142 /* We deal only with regular files. Symlink renames are handled
143 * only when they are exact matches --- in other words, no edits
144 * after renaming.
145 */
146 if (!S_ISREG(src->mode) || !S_ISREG(dst->mode))
147 return 0;
148
149 /*
150 * Need to check that source and destination sizes are
151 * filled in before comparing them.
152 *
153 * If we already have "cnt_data" filled in, we know it's
154 * all good (avoid checking the size for zero, as that
155 * is a possible size - we really should have a flag to
156 * say whether the size is valid or not!)
157 */
158 if (!src->cnt_data && diff_populate_filespec(src, 1))
159 return 0;
160 if (!dst->cnt_data && diff_populate_filespec(dst, 1))
161 return 0;
162
163 max_size = ((src->size > dst->size) ? src->size : dst->size);
164 base_size = ((src->size < dst->size) ? src->size : dst->size);
165 delta_size = max_size - base_size;
166
167 /* We would not consider edits that change the file size so
168 * drastically. delta_size must be smaller than
169 * (MAX_SCORE-minimum_score)/MAX_SCORE * min(src->size, dst->size).
170 *
171 * Note that base_size == 0 case is handled here already
172 * and the final score computation below would not have a
173 * divide-by-zero issue.
174 */
175 if (max_size * (MAX_SCORE-minimum_score) < delta_size * MAX_SCORE)
176 return 0;
177
178 if (!src->cnt_data && diff_populate_filespec(src, 0))
179 return 0;
180 if (!dst->cnt_data && diff_populate_filespec(dst, 0))
181 return 0;
182
183 delta_limit = (unsigned long)
184 (base_size * (MAX_SCORE-minimum_score) / MAX_SCORE);
185 if (diffcore_count_changes(src, dst,
186 &src->cnt_data, &dst->cnt_data,
187 delta_limit,
188 &src_copied, &literal_added))
189 return 0;
190
191 /* How similar are they?
192 * what percentage of material in dst are from source?
193 */
194 if (!dst->size)
195 score = 0; /* should not happen */
196 else
197 score = (int)(src_copied * MAX_SCORE / max_size);
198 return score;
199}
200
201static void record_rename_pair(int dst_index, int src_index, int score)
202{
203 struct diff_filespec *src, *dst;
204 struct diff_filepair *dp;
205
206 if (rename_dst[dst_index].pair)
207 die("internal error: dst already matched.");
208
209 src = rename_src[src_index].p->one;
210 src->rename_used++;
211 src->count++;
212
213 dst = rename_dst[dst_index].two;
214 dst->count++;
215
216 dp = diff_queue(NULL, src, dst);
217 dp->renamed_pair = 1;
218 if (!strcmp(src->path, dst->path))
219 dp->score = rename_src[src_index].score;
220 else
221 dp->score = score;
222 rename_dst[dst_index].pair = dp;
223}
224
225/*
226 * We sort the rename similarity matrix with the score, in descending
227 * order (the most similar first).
228 */
229static int score_compare(const void *a_, const void *b_)
230{
231 const struct diff_score *a = a_, *b = b_;
232
233 /* sink the unused ones to the bottom */
234 if (a->dst < 0)
235 return (0 <= b->dst);
236 else if (b->dst < 0)
237 return -1;
238
239 if (a->score == b->score)
240 return b->name_score - a->name_score;
241
242 return b->score - a->score;
243}
244
245struct file_similarity {
246 int src_dst, index;
247 struct diff_filespec *filespec;
248 struct file_similarity *next;
249};
250
251static int find_identical_files(struct file_similarity *src,
252 struct file_similarity *dst,
253 struct diff_options *options)
254{
255 int renames = 0;
256
257 /*
258 * Walk over all the destinations ...
259 */
260 do {
261 struct diff_filespec *target = dst->filespec;
262 struct file_similarity *p, *best;
263 int i = 100, best_score = -1;
264
265 /*
266 * .. to find the best source match
267 */
268 best = NULL;
269 for (p = src; p; p = p->next) {
270 int score;
271 struct diff_filespec *source = p->filespec;
272
273 /* False hash collision? */
274 if (hashcmp(source->sha1, target->sha1))
275 continue;
276 /* Non-regular files? If so, the modes must match! */
277 if (!S_ISREG(source->mode) || !S_ISREG(target->mode)) {
278 if (source->mode != target->mode)
279 continue;
280 }
281 /* Give higher scores to sources that haven't been used already */
282 score = !source->rename_used;
283 if (source->rename_used && options->detect_rename != DIFF_DETECT_COPY)
284 continue;
285 score += basename_same(source, target);
286 if (score > best_score) {
287 best = p;
288 best_score = score;
289 if (score == 2)
290 break;
291 }
292
293 /* Too many identical alternatives? Pick one */
294 if (!--i)
295 break;
296 }
297 if (best) {
298 record_rename_pair(dst->index, best->index, MAX_SCORE);
299 renames++;
300 }
301 } while ((dst = dst->next) != NULL);
302 return renames;
303}
304
305static void free_similarity_list(struct file_similarity *p)
306{
307 while (p) {
308 struct file_similarity *entry = p;
309 p = p->next;
310 free(entry);
311 }
312}
313
314static int find_same_files(void *ptr, void *data)
315{
316 int ret;
317 struct file_similarity *p = ptr;
318 struct file_similarity *src = NULL, *dst = NULL;
319 struct diff_options *options = data;
320
321 /* Split the hash list up into sources and destinations */
322 do {
323 struct file_similarity *entry = p;
324 p = p->next;
325 if (entry->src_dst < 0) {
326 entry->next = src;
327 src = entry;
328 } else {
329 entry->next = dst;
330 dst = entry;
331 }
332 } while (p);
333
334 /*
335 * If we have both sources *and* destinations, see if
336 * we can match them up
337 */
338 ret = (src && dst) ? find_identical_files(src, dst, options) : 0;
339
340 /* Free the hashes and return the number of renames found */
341 free_similarity_list(src);
342 free_similarity_list(dst);
343 return ret;
344}
345
346static unsigned int hash_filespec(struct diff_filespec *filespec)
347{
348 unsigned int hash;
349 if (!filespec->sha1_valid) {
350 if (diff_populate_filespec(filespec, 0))
351 return 0;
352 hash_sha1_file(filespec->data, filespec->size, "blob", filespec->sha1);
353 }
354 memcpy(&hash, filespec->sha1, sizeof(hash));
355 return hash;
356}
357
358static void insert_file_table(struct hash_table *table, int src_dst, int index, struct diff_filespec *filespec)
359{
360 void **pos;
361 unsigned int hash;
362 struct file_similarity *entry = xmalloc(sizeof(*entry));
363
364 entry->src_dst = src_dst;
365 entry->index = index;
366 entry->filespec = filespec;
367 entry->next = NULL;
368
369 hash = hash_filespec(filespec);
370 pos = insert_hash(hash, entry, table);
371
372 /* We already had an entry there? */
373 if (pos) {
374 entry->next = *pos;
375 *pos = entry;
376 }
377}
378
379/*
380 * Find exact renames first.
381 *
382 * The first round matches up the up-to-date entries,
383 * and then during the second round we try to match
384 * cache-dirty entries as well.
385 */
386static int find_exact_renames(struct diff_options *options)
387{
388 int i;
389 struct hash_table file_table;
390
391 init_hash(&file_table);
392 for (i = 0; i < rename_src_nr; i++)
393 insert_file_table(&file_table, -1, i, rename_src[i].p->one);
394
395 for (i = 0; i < rename_dst_nr; i++)
396 insert_file_table(&file_table, 1, i, rename_dst[i].two);
397
398 /* Find the renames */
399 i = for_each_hash(&file_table, find_same_files, options);
400
401 /* .. and free the hash data structure */
402 free_hash(&file_table);
403
404 return i;
405}
406
407#define NUM_CANDIDATE_PER_DST 4
408static void record_if_better(struct diff_score m[], struct diff_score *o)
409{
410 int i, worst;
411
412 /* find the worst one */
413 worst = 0;
414 for (i = 1; i < NUM_CANDIDATE_PER_DST; i++)
415 if (score_compare(&m[i], &m[worst]) > 0)
416 worst = i;
417
418 /* is it better than the worst one? */
419 if (score_compare(&m[worst], o) > 0)
420 m[worst] = *o;
421}
422
423static int too_many_rename_candidates(int num_create,
424 struct diff_options *options)
425{
426 int rename_limit = options->rename_limit;
427 int num_src = rename_src_nr;
428
429 options->needed_rename_limit = 0;
430
431 /*
432 * This basically does a test for the rename matrix not
433 * growing larger than a "rename_limit" square matrix, ie:
434 *
435 * num_create * num_src > rename_limit * rename_limit
436 *
437 * but handles the potential overflow case specially (and we
438 * assume at least 32-bit integers)
439 */
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;
445
446 options->needed_rename_limit =
447 num_src > num_create ? num_src : num_create;
448 return 1;
449}
450
451static int find_renames(struct diff_score *mx, int dst_cnt, int minimum_score, int copies)
452{
453 int count = 0, i;
454
455 for (i = 0; i < dst_cnt * NUM_CANDIDATE_PER_DST; i++) {
456 struct diff_rename_dst *dst;
457
458 if ((mx[i].dst < 0) ||
459 (mx[i].score < minimum_score))
460 break; /* there is no more usable pair. */
461 dst = &rename_dst[mx[i].dst];
462 if (dst->pair)
463 continue; /* already done, either exact or fuzzy. */
464 if (!copies && rename_src[mx[i].src].p->one->rename_used)
465 continue;
466 record_rename_pair(mx[i].dst, mx[i].src, mx[i].score);
467 count++;
468 }
469 return count;
470}
471
472void diffcore_rename(struct diff_options *options)
473{
474 int detect_rename = options->detect_rename;
475 int minimum_score = options->rename_score;
476 struct diff_queue_struct *q = &diff_queued_diff;
477 struct diff_queue_struct outq;
478 struct diff_score *mx;
479 int i, j, rename_count;
480 int num_create, num_src, dst_cnt;
481 struct progress *progress = NULL;
482
483 if (!minimum_score)
484 minimum_score = DEFAULT_RENAME_SCORE;
485
486 for (i = 0; i < q->nr; i++) {
487 struct diff_filepair *p = q->queue[i];
488 if (!DIFF_FILE_VALID(p->one)) {
489 if (!DIFF_FILE_VALID(p->two))
490 continue; /* unmerged */
491 else if (options->single_follow &&
492 strcmp(options->single_follow, p->two->path))
493 continue; /* not interested */
494 else
495 locate_rename_dst(p->two, 1);
496 }
497 else if (!DIFF_FILE_VALID(p->two)) {
498 /*
499 * If the source is a broken "delete", and
500 * they did not really want to get broken,
501 * that means the source actually stays.
502 * So we increment the "rename_used" score
503 * by one, to indicate ourselves as a user
504 */
505 if (p->broken_pair && !p->score)
506 p->one->rename_used++;
507 register_rename_src(p);
508 }
509 else if (detect_rename == DIFF_DETECT_COPY) {
510 /*
511 * Increment the "rename_used" score by
512 * one, to indicate ourselves as a user.
513 */
514 p->one->rename_used++;
515 register_rename_src(p);
516 }
517 }
518 if (rename_dst_nr == 0 || rename_src_nr == 0)
519 goto cleanup; /* nothing to do */
520
521 /*
522 * We really want to cull the candidates list early
523 * with cheap tests in order to avoid doing deltas.
524 */
525 rename_count = find_exact_renames(options);
526
527 /* Did we only want exact renames? */
528 if (minimum_score == MAX_SCORE)
529 goto cleanup;
530
531 /*
532 * Calculate how many renames are left (but all the source
533 * files still remain as options for rename/copies!)
534 */
535 num_create = (rename_dst_nr - rename_count);
536 num_src = rename_src_nr;
537
538 /* All done? */
539 if (!num_create)
540 goto cleanup;
541
542 if (too_many_rename_candidates(num_create, options))
543 goto cleanup;
544
545 if (options->show_rename_progress) {
546 progress = start_progress_delay(
547 "Performing inexact rename detection",
548 rename_dst_nr * rename_src_nr, 50, 1);
549 }
550
551 mx = xcalloc(num_create * NUM_CANDIDATE_PER_DST, sizeof(*mx));
552 for (dst_cnt = i = 0; i < rename_dst_nr; i++) {
553 struct diff_filespec *two = rename_dst[i].two;
554 struct diff_score *m;
555
556 if (rename_dst[i].pair)
557 continue; /* dealt with exact match already. */
558
559 m = &mx[dst_cnt * NUM_CANDIDATE_PER_DST];
560 for (j = 0; j < NUM_CANDIDATE_PER_DST; j++)
561 m[j].dst = -1;
562
563 for (j = 0; j < rename_src_nr; j++) {
564 struct diff_filespec *one = rename_src[j].p->one;
565 struct diff_score this_src;
566 this_src.score = estimate_similarity(one, two,
567 minimum_score);
568 this_src.name_score = basename_same(one, two);
569 this_src.dst = i;
570 this_src.src = j;
571 record_if_better(m, &this_src);
572 /*
573 * Once we run estimate_similarity,
574 * We do not need the text anymore.
575 */
576 diff_free_filespec_blob(one);
577 diff_free_filespec_blob(two);
578 }
579 dst_cnt++;
580 display_progress(progress, (i+1)*rename_src_nr);
581 }
582 stop_progress(&progress);
583
584 /* cost matrix sorted by most to least similar pair */
585 qsort(mx, dst_cnt * NUM_CANDIDATE_PER_DST, sizeof(*mx), score_compare);
586
587 rename_count += find_renames(mx, dst_cnt, minimum_score, 0);
588 if (detect_rename == DIFF_DETECT_COPY)
589 rename_count += find_renames(mx, dst_cnt, minimum_score, 1);
590 free(mx);
591
592 cleanup:
593 /* At this point, we have found some renames and copies and they
594 * are recorded in rename_dst. The original list is still in *q.
595 */
596 DIFF_QUEUE_CLEAR(&outq);
597 for (i = 0; i < q->nr; i++) {
598 struct diff_filepair *p = q->queue[i];
599 struct diff_filepair *pair_to_free = NULL;
600
601 if (!DIFF_FILE_VALID(p->one) && DIFF_FILE_VALID(p->two)) {
602 /*
603 * Creation
604 *
605 * We would output this create record if it has
606 * not been turned into a rename/copy already.
607 */
608 struct diff_rename_dst *dst =
609 locate_rename_dst(p->two, 0);
610 if (dst && dst->pair) {
611 diff_q(&outq, dst->pair);
612 pair_to_free = p;
613 }
614 else
615 /* no matching rename/copy source, so
616 * record this as a creation.
617 */
618 diff_q(&outq, p);
619 }
620 else if (DIFF_FILE_VALID(p->one) && !DIFF_FILE_VALID(p->two)) {
621 /*
622 * Deletion
623 *
624 * We would output this delete record if:
625 *
626 * (1) this is a broken delete and the counterpart
627 * broken create remains in the output; or
628 * (2) this is not a broken delete, and rename_dst
629 * does not have a rename/copy to move p->one->path
630 * out of existence.
631 *
632 * Otherwise, the counterpart broken create
633 * has been turned into a rename-edit; or
634 * delete did not have a matching create to
635 * begin with.
636 */
637 if (DIFF_PAIR_BROKEN(p)) {
638 /* broken delete */
639 struct diff_rename_dst *dst =
640 locate_rename_dst(p->one, 0);
641 if (dst && dst->pair)
642 /* counterpart is now rename/copy */
643 pair_to_free = p;
644 }
645 else {
646 if (p->one->rename_used)
647 /* this path remains */
648 pair_to_free = p;
649 }
650
651 if (pair_to_free)
652 ;
653 else
654 diff_q(&outq, p);
655 }
656 else if (!diff_unmodified_pair(p))
657 /* all the usual ones need to be kept */
658 diff_q(&outq, p);
659 else
660 /* no need to keep unmodified pairs */
661 pair_to_free = p;
662
663 if (pair_to_free)
664 diff_free_filepair(pair_to_free);
665 }
666 diff_debug_queue("done copying original", &outq);
667
668 free(q->queue);
669 *q = outq;
670 diff_debug_queue("done collapsing", q);
671
672 for (i = 0; i < rename_dst_nr; i++)
673 free_filespec(rename_dst[i].two);
674
675 free(rename_dst);
676 rename_dst = NULL;
677 rename_dst_nr = rename_dst_alloc = 0;
678 free(rename_src);
679 rename_src = NULL;
680 rename_src_nr = rename_src_alloc = 0;
681 return;
682}