Ref-count the filespecs used by diffcore
[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
8 /* Table of rename/copy destinations */
9
10 static struct diff_rename_dst {
11         struct diff_filespec *two;
12         struct diff_filepair *pair;
13 } *rename_dst;
14 static int rename_dst_nr, rename_dst_alloc;
15
16 static struct diff_rename_dst *locate_rename_dst(struct diff_filespec *two,
17                                                  int insert_ok)
18 {
19         int first, last;
20
21         first = 0;
22         last = rename_dst_nr;
23         while (last > first) {
24                 int next = (last + first) >> 1;
25                 struct diff_rename_dst *dst = &(rename_dst[next]);
26                 int cmp = strcmp(two->path, dst->two->path);
27                 if (!cmp)
28                         return dst;
29                 if (cmp < 0) {
30                         last = next;
31                         continue;
32                 }
33                 first = next+1;
34         }
35         /* not found */
36         if (!insert_ok)
37                 return NULL;
38         /* insert to make it at "first" */
39         if (rename_dst_alloc <= rename_dst_nr) {
40                 rename_dst_alloc = alloc_nr(rename_dst_alloc);
41                 rename_dst = xrealloc(rename_dst,
42                                       rename_dst_alloc * sizeof(*rename_dst));
43         }
44         rename_dst_nr++;
45         if (first < rename_dst_nr)
46                 memmove(rename_dst + first + 1, rename_dst + first,
47                         (rename_dst_nr - first - 1) * sizeof(*rename_dst));
48         rename_dst[first].two = alloc_filespec(two->path);
49         fill_filespec(rename_dst[first].two, two->sha1, two->mode);
50         rename_dst[first].pair = NULL;
51         return &(rename_dst[first]);
52 }
53
54 /* Table of rename/copy src files */
55 static struct diff_rename_src {
56         struct diff_filespec *one;
57         unsigned short score; /* to remember the break score */
58         unsigned src_path_left : 1;
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                                                    int src_path_left,
64                                                    unsigned short score)
65 {
66         int first, last;
67
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->one->path);
74                 if (!cmp)
75                         return src;
76                 if (cmp < 0) {
77                         last = next;
78                         continue;
79                 }
80                 first = next+1;
81         }
82
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].one = one;
94         rename_src[first].score = score;
95         rename_src[first].src_path_left = src_path_left;
96         return &(rename_src[first]);
97 }
98
99 static int is_exact_match(struct diff_filespec *src,
100                           struct diff_filespec *dst,
101                           int contents_too)
102 {
103         if (src->sha1_valid && dst->sha1_valid &&
104             !hashcmp(src->sha1, dst->sha1))
105                 return 1;
106         if (!contents_too)
107                 return 0;
108         if (diff_populate_filespec(src, 1) || diff_populate_filespec(dst, 1))
109                 return 0;
110         if (src->size != dst->size)
111                 return 0;
112         if (src->sha1_valid && dst->sha1_valid)
113             return !hashcmp(src->sha1, dst->sha1);
114         if (diff_populate_filespec(src, 0) || diff_populate_filespec(dst, 0))
115                 return 0;
116         if (src->size == dst->size &&
117             !memcmp(src->data, dst->data, src->size))
118                 return 1;
119         return 0;
120 }
121
122 static int basename_same(struct diff_filespec *src, struct diff_filespec *dst)
123 {
124         int src_len = strlen(src->path), dst_len = strlen(dst->path);
125         while (src_len && dst_len) {
126                 char c1 = src->path[--src_len];
127                 char c2 = dst->path[--dst_len];
128                 if (c1 != c2)
129                         return 0;
130                 if (c1 == '/')
131                         return 1;
132         }
133         return (!src_len || src->path[src_len - 1] == '/') &&
134                 (!dst_len || dst->path[dst_len - 1] == '/');
135 }
136
137 struct diff_score {
138         int src; /* index in rename_src */
139         int dst; /* index in rename_dst */
140         int score;
141         int name_score;
142 };
143
144 static int estimate_similarity(struct diff_filespec *src,
145                                struct diff_filespec *dst,
146                                int minimum_score)
147 {
148         /* src points at a file that existed in the original tree (or
149          * optionally a file in the destination tree) and dst points
150          * at a newly created file.  They may be quite similar, in which
151          * case we want to say src is renamed to dst or src is copied into
152          * dst, and then some edit has been applied to dst.
153          *
154          * Compare them and return how similar they are, representing
155          * the score as an integer between 0 and MAX_SCORE.
156          *
157          * When there is an exact match, it is considered a better
158          * match than anything else; the destination does not even
159          * call into this function in that case.
160          */
161         unsigned long max_size, delta_size, base_size, src_copied, literal_added;
162         unsigned long delta_limit;
163         int score;
164
165         /* We deal only with regular files.  Symlink renames are handled
166          * only when they are exact matches --- in other words, no edits
167          * after renaming.
168          */
169         if (!S_ISREG(src->mode) || !S_ISREG(dst->mode))
170                 return 0;
171
172         max_size = ((src->size > dst->size) ? src->size : dst->size);
173         base_size = ((src->size < dst->size) ? src->size : dst->size);
174         delta_size = max_size - base_size;
175
176         /* We would not consider edits that change the file size so
177          * drastically.  delta_size must be smaller than
178          * (MAX_SCORE-minimum_score)/MAX_SCORE * min(src->size, dst->size).
179          *
180          * Note that base_size == 0 case is handled here already
181          * and the final score computation below would not have a
182          * divide-by-zero issue.
183          */
184         if (base_size * (MAX_SCORE-minimum_score) < delta_size * MAX_SCORE)
185                 return 0;
186
187         if ((!src->cnt_data && diff_populate_filespec(src, 0))
188                 || (!dst->cnt_data && diff_populate_filespec(dst, 0)))
189                 return 0; /* error but caught downstream */
190
191
192         delta_limit = (unsigned long)
193                 (base_size * (MAX_SCORE-minimum_score) / MAX_SCORE);
194         if (diffcore_count_changes(src, dst,
195                                    &src->cnt_data, &dst->cnt_data,
196                                    delta_limit,
197                                    &src_copied, &literal_added))
198                 return 0;
199
200         /* How similar are they?
201          * what percentage of material in dst are from source?
202          */
203         if (!dst->size)
204                 score = 0; /* should not happen */
205         else
206                 score = (int)(src_copied * MAX_SCORE / max_size);
207         return score;
208 }
209
210 static void record_rename_pair(int dst_index, int src_index, int score)
211 {
212         struct diff_filespec *src, *dst;
213         struct diff_filepair *dp;
214
215         if (rename_dst[dst_index].pair)
216                 die("internal error: dst already matched.");
217
218         src = rename_src[src_index].one;
219         src->count++;
220
221         dst = rename_dst[dst_index].two;
222         dst->count++;
223
224         dp = diff_queue(NULL, src, dst);
225         dp->renamed_pair = 1;
226         if (!strcmp(src->path, dst->path))
227                 dp->score = rename_src[src_index].score;
228         else
229                 dp->score = score;
230         dp->source_stays = rename_src[src_index].src_path_left;
231         rename_dst[dst_index].pair = dp;
232 }
233
234 /*
235  * We sort the rename similarity matrix with the score, in descending
236  * order (the most similar first).
237  */
238 static int score_compare(const void *a_, const void *b_)
239 {
240         const struct diff_score *a = a_, *b = b_;
241
242         if (a->score == b->score)
243                 return b->name_score - a->name_score;
244
245         return b->score - a->score;
246 }
247
248 static int compute_stays(struct diff_queue_struct *q,
249                          struct diff_filespec *one)
250 {
251         int i;
252         for (i = 0; i < q->nr; i++) {
253                 struct diff_filepair *p = q->queue[i];
254                 if (strcmp(one->path, p->two->path))
255                         continue;
256                 if (DIFF_PAIR_RENAME(p)) {
257                         return 0; /* something else is renamed into this */
258                 }
259         }
260         return 1;
261 }
262
263 /*
264  * Find exact renames first.
265  *
266  * The first round matches up the up-to-date entries,
267  * and then during the second round we try to match
268  * cache-dirty entries as well.
269  *
270  * Note: the rest of the rename logic depends on this
271  * phase also populating all the filespecs for any
272  * entry that isn't matched up with an exact rename,
273  * see "is_exact_match()".
274  */
275 static int find_exact_renames(void)
276 {
277         int rename_count = 0;
278         int contents_too;
279
280         for (contents_too = 0; contents_too < 2; contents_too++) {
281                 int i;
282
283                 for (i = 0; i < rename_dst_nr; i++) {
284                         struct diff_filespec *two = rename_dst[i].two;
285                         int j;
286
287                         if (rename_dst[i].pair)
288                                 continue; /* dealt with an earlier round */
289                         for (j = 0; j < rename_src_nr; j++) {
290                                 int k;
291                                 struct diff_filespec *one = rename_src[j].one;
292                                 if (!is_exact_match(one, two, contents_too))
293                                         continue;
294
295                                 /* see if there is a basename match, too */
296                                 for (k = j; k < rename_src_nr; k++) {
297                                         one = rename_src[k].one;
298                                         if (basename_same(one, two) &&
299                                                 is_exact_match(one, two,
300                                                         contents_too)) {
301                                                 j = k;
302                                                 break;
303                                         }
304                                 }
305
306                                 record_rename_pair(i, j, (int)MAX_SCORE);
307                                 rename_count++;
308                                 break; /* we are done with this entry */
309                         }
310                 }
311         }
312         return rename_count;
313 }
314
315 void diffcore_rename(struct diff_options *options)
316 {
317         int detect_rename = options->detect_rename;
318         int minimum_score = options->rename_score;
319         int rename_limit = options->rename_limit;
320         struct diff_queue_struct *q = &diff_queued_diff;
321         struct diff_queue_struct outq;
322         struct diff_score *mx;
323         int i, j, rename_count;
324         int num_create, num_src, dst_cnt;
325
326         if (!minimum_score)
327                 minimum_score = DEFAULT_RENAME_SCORE;
328
329         for (i = 0; i < q->nr; i++) {
330                 struct diff_filepair *p = q->queue[i];
331                 if (!DIFF_FILE_VALID(p->one)) {
332                         if (!DIFF_FILE_VALID(p->two))
333                                 continue; /* unmerged */
334                         else if (options->single_follow &&
335                                  strcmp(options->single_follow, p->two->path))
336                                 continue; /* not interested */
337                         else
338                                 locate_rename_dst(p->two, 1);
339                 }
340                 else if (!DIFF_FILE_VALID(p->two)) {
341                         /* If the source is a broken "delete", and
342                          * they did not really want to get broken,
343                          * that means the source actually stays.
344                          */
345                         int stays = (p->broken_pair && !p->score);
346                         register_rename_src(p->one, stays, p->score);
347                 }
348                 else if (detect_rename == DIFF_DETECT_COPY)
349                         register_rename_src(p->one, 1, p->score);
350         }
351         if (rename_dst_nr == 0 || rename_src_nr == 0)
352                 goto cleanup; /* nothing to do */
353
354         /*
355          * This basically does a test for the rename matrix not
356          * growing larger than a "rename_limit" square matrix, ie:
357          *
358          *    rename_dst_nr * rename_src_nr > rename_limit * rename_limit
359          *
360          * but handles the potential overflow case specially (and we
361          * assume at least 32-bit integers)
362          */
363         if (rename_limit <= 0 || rename_limit > 32767)
364                 rename_limit = 32767;
365         if (rename_dst_nr > rename_limit && rename_src_nr > rename_limit)
366                 goto cleanup;
367         if (rename_dst_nr * rename_src_nr > rename_limit * rename_limit)
368                 goto cleanup;
369
370         /*
371          * We really want to cull the candidates list early
372          * with cheap tests in order to avoid doing deltas.
373          */
374         rename_count = find_exact_renames();
375
376         /* Have we run out the created file pool?  If so we can avoid
377          * doing the delta matrix altogether.
378          */
379         if (rename_count == rename_dst_nr)
380                 goto cleanup;
381
382         if (minimum_score == MAX_SCORE)
383                 goto cleanup;
384
385         num_create = (rename_dst_nr - rename_count);
386         num_src = rename_src_nr;
387         mx = xmalloc(sizeof(*mx) * num_create * num_src);
388         for (dst_cnt = i = 0; i < rename_dst_nr; i++) {
389                 int base = dst_cnt * num_src;
390                 struct diff_filespec *two = rename_dst[i].two;
391                 if (rename_dst[i].pair)
392                         continue; /* dealt with exact match already. */
393                 for (j = 0; j < rename_src_nr; j++) {
394                         struct diff_filespec *one = rename_src[j].one;
395                         struct diff_score *m = &mx[base+j];
396                         m->src = j;
397                         m->dst = i;
398                         m->score = estimate_similarity(one, two,
399                                                        minimum_score);
400                         m->name_score = basename_same(one, two);
401                         diff_free_filespec_blob(one);
402                 }
403                 /* We do not need the text anymore */
404                 diff_free_filespec_blob(two);
405                 dst_cnt++;
406         }
407         /* cost matrix sorted by most to least similar pair */
408         qsort(mx, num_create * num_src, sizeof(*mx), score_compare);
409         for (i = 0; i < num_create * num_src; i++) {
410                 struct diff_rename_dst *dst = &rename_dst[mx[i].dst];
411                 if (dst->pair)
412                         continue; /* already done, either exact or fuzzy. */
413                 if (mx[i].score < minimum_score)
414                         break; /* there is no more usable pair. */
415                 record_rename_pair(mx[i].dst, mx[i].src, mx[i].score);
416                 rename_count++;
417         }
418         free(mx);
419
420  cleanup:
421         /* At this point, we have found some renames and copies and they
422          * are recorded in rename_dst.  The original list is still in *q.
423          */
424         outq.queue = NULL;
425         outq.nr = outq.alloc = 0;
426         for (i = 0; i < q->nr; i++) {
427                 struct diff_filepair *p = q->queue[i];
428                 struct diff_filepair *pair_to_free = NULL;
429
430                 if (!DIFF_FILE_VALID(p->one) && DIFF_FILE_VALID(p->two)) {
431                         /*
432                          * Creation
433                          *
434                          * We would output this create record if it has
435                          * not been turned into a rename/copy already.
436                          */
437                         struct diff_rename_dst *dst =
438                                 locate_rename_dst(p->two, 0);
439                         if (dst && dst->pair) {
440                                 diff_q(&outq, dst->pair);
441                                 pair_to_free = p;
442                         }
443                         else
444                                 /* no matching rename/copy source, so
445                                  * record this as a creation.
446                                  */
447                                 diff_q(&outq, p);
448                 }
449                 else if (DIFF_FILE_VALID(p->one) && !DIFF_FILE_VALID(p->two)) {
450                         /*
451                          * Deletion
452                          *
453                          * We would output this delete record if:
454                          *
455                          * (1) this is a broken delete and the counterpart
456                          *     broken create remains in the output; or
457                          * (2) this is not a broken delete, and rename_dst
458                          *     does not have a rename/copy to move p->one->path
459                          *     out of existence.
460                          *
461                          * Otherwise, the counterpart broken create
462                          * has been turned into a rename-edit; or
463                          * delete did not have a matching create to
464                          * begin with.
465                          */
466                         if (DIFF_PAIR_BROKEN(p)) {
467                                 /* broken delete */
468                                 struct diff_rename_dst *dst =
469                                         locate_rename_dst(p->one, 0);
470                                 if (dst && dst->pair)
471                                         /* counterpart is now rename/copy */
472                                         pair_to_free = p;
473                         }
474                         else {
475                                 for (j = 0; j < rename_dst_nr; j++) {
476                                         if (!rename_dst[j].pair)
477                                                 continue;
478                                         if (strcmp(rename_dst[j].pair->
479                                                    one->path,
480                                                    p->one->path))
481                                                 continue;
482                                         break;
483                                 }
484                                 if (j < rename_dst_nr)
485                                         /* this path remains */
486                                         pair_to_free = p;
487                         }
488
489                         if (pair_to_free)
490                                 ;
491                         else
492                                 diff_q(&outq, p);
493                 }
494                 else if (!diff_unmodified_pair(p))
495                         /* all the usual ones need to be kept */
496                         diff_q(&outq, p);
497                 else
498                         /* no need to keep unmodified pairs */
499                         pair_to_free = p;
500
501                 if (pair_to_free)
502                         diff_free_filepair(pair_to_free);
503         }
504         diff_debug_queue("done copying original", &outq);
505
506         free(q->queue);
507         *q = outq;
508         diff_debug_queue("done collapsing", q);
509
510         /* We need to see which rename source really stays here;
511          * earlier we only checked if the path is left in the result,
512          * but even if a path remains in the result, if that is coming
513          * from copying something else on top of it, then the original
514          * source is lost and does not stay.
515          */
516         for (i = 0; i < q->nr; i++) {
517                 struct diff_filepair *p = q->queue[i];
518                 if (DIFF_PAIR_RENAME(p) && p->source_stays) {
519                         /* If one appears as the target of a rename-copy,
520                          * then mark p->source_stays = 0; otherwise
521                          * leave it as is.
522                          */
523                         p->source_stays = compute_stays(q, p->one);
524                 }
525         }
526
527         for (i = 0; i < rename_dst_nr; i++)
528                 free_filespec(rename_dst[i].two);
529
530         free(rename_dst);
531         rename_dst = NULL;
532         rename_dst_nr = rename_dst_alloc = 0;
533         free(rename_src);
534         rename_src = NULL;
535         rename_src_nr = rename_src_alloc = 0;
536         return;
537 }