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