Code

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