e7e370b2cc1e66f7724755c1b33f2a815b7223bf
   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
  11static struct diff_rename_dst {
  12        struct diff_filespec *two;
  13        struct diff_filepair *pair;
  14} *rename_dst;
  15static int rename_dst_nr, rename_dst_alloc;
  16
  17static 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 */
  56static struct diff_rename_src {
  57        struct diff_filespec *one;
  58        unsigned short score; /* to remember the break score */
  59} *rename_src;
  60static int rename_src_nr, rename_src_alloc;
  61
  62static 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
  97static 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
 112struct diff_score {
 113        int src; /* index in rename_src */
 114        int dst; /* index in rename_dst */
 115        int score;
 116        int name_score;
 117};
 118
 119static 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        max_size = ((src->size > dst->size) ? src->size : dst->size);
 148        base_size = ((src->size < dst->size) ? src->size : dst->size);
 149        delta_size = max_size - base_size;
 150
 151        /* We would not consider edits that change the file size so
 152         * drastically.  delta_size must be smaller than
 153         * (MAX_SCORE-minimum_score)/MAX_SCORE * min(src->size, dst->size).
 154         *
 155         * Note that base_size == 0 case is handled here already
 156         * and the final score computation below would not have a
 157         * divide-by-zero issue.
 158         */
 159        if (base_size * (MAX_SCORE-minimum_score) < delta_size * MAX_SCORE)
 160                return 0;
 161
 162        if ((!src->cnt_data && diff_populate_filespec(src, 0))
 163                || (!dst->cnt_data && diff_populate_filespec(dst, 0)))
 164                return 0; /* error but caught downstream */
 165
 166
 167        delta_limit = (unsigned long)
 168                (base_size * (MAX_SCORE-minimum_score) / MAX_SCORE);
 169        if (diffcore_count_changes(src, dst,
 170                                   &src->cnt_data, &dst->cnt_data,
 171                                   delta_limit,
 172                                   &src_copied, &literal_added))
 173                return 0;
 174
 175        /* How similar are they?
 176         * what percentage of material in dst are from source?
 177         */
 178        if (!dst->size)
 179                score = 0; /* should not happen */
 180        else
 181                score = (int)(src_copied * MAX_SCORE / max_size);
 182        return score;
 183}
 184
 185static void record_rename_pair(int dst_index, int src_index, int score)
 186{
 187        struct diff_filespec *src, *dst;
 188        struct diff_filepair *dp;
 189
 190        if (rename_dst[dst_index].pair)
 191                die("internal error: dst already matched.");
 192
 193        src = rename_src[src_index].one;
 194        src->rename_used++;
 195        src->count++;
 196
 197        dst = rename_dst[dst_index].two;
 198        dst->count++;
 199
 200        dp = diff_queue(NULL, src, dst);
 201        dp->renamed_pair = 1;
 202        if (!strcmp(src->path, dst->path))
 203                dp->score = rename_src[src_index].score;
 204        else
 205                dp->score = score;
 206        rename_dst[dst_index].pair = dp;
 207}
 208
 209/*
 210 * We sort the rename similarity matrix with the score, in descending
 211 * order (the most similar first).
 212 */
 213static int score_compare(const void *a_, const void *b_)
 214{
 215        const struct diff_score *a = a_, *b = b_;
 216
 217        if (a->score == b->score)
 218                return b->name_score - a->name_score;
 219
 220        return b->score - a->score;
 221}
 222
 223struct file_similarity {
 224        int src_dst, index;
 225        struct diff_filespec *filespec;
 226        struct file_similarity *next;
 227};
 228
 229static int find_identical_files(struct file_similarity *src,
 230                                struct file_similarity *dst)
 231{
 232        int renames = 0;
 233
 234        /*
 235         * Walk over all the destinations ...
 236         */
 237        do {
 238                struct diff_filespec *one = dst->filespec;
 239                struct file_similarity *p, *best;
 240                int i = 100;
 241
 242                /*
 243                 * .. to find the best source match
 244                 */
 245                best = NULL;
 246                for (p = src; p; p = p->next) {
 247                        struct diff_filespec *two = p->filespec;
 248
 249                        /* False hash collission? */
 250                        if (hashcmp(one->sha1, two->sha1))
 251                                continue;
 252                        /* Non-regular files? If so, the modes must match! */
 253                        if (!S_ISREG(one->mode) || !S_ISREG(two->mode)) {
 254                                if (one->mode != two->mode)
 255                                        continue;
 256                        }
 257                        best = p;
 258                        if (basename_same(one, two))
 259                                break;
 260
 261                        /* Too many identical alternatives? Pick one */
 262                        if (!--i)
 263                                break;
 264                }
 265                if (best) {
 266                        record_rename_pair(dst->index, best->index, MAX_SCORE);
 267                        renames++;
 268                }
 269        } while ((dst = dst->next) != NULL);
 270        return renames;
 271}
 272
 273/*
 274 * Note: the rest of the rename logic depends on this
 275 * phase also populating all the filespecs for any
 276 * entry that isn't matched up with an exact rename.
 277 */
 278static void free_similarity_list(struct file_similarity *p)
 279{
 280        while (p) {
 281                struct file_similarity *entry = p;
 282                p = p->next;
 283
 284                /* Stupid special case, see note above! */
 285                diff_populate_filespec(entry->filespec, 0);
 286                free(entry);
 287        }
 288}
 289
 290static int find_same_files(void *ptr)
 291{
 292        int ret;
 293        struct file_similarity *p = ptr;
 294        struct file_similarity *src = NULL, *dst = NULL;
 295
 296        /* Split the hash list up into sources and destinations */
 297        do {
 298                struct file_similarity *entry = p;
 299                p = p->next;
 300                if (entry->src_dst < 0) {
 301                        entry->next = src;
 302                        src = entry;
 303                } else {
 304                        entry->next = dst;
 305                        dst = entry;
 306                }
 307        } while (p);
 308
 309        /*
 310         * If we have both sources *and* destinations, see if
 311         * we can match them up
 312         */
 313        ret = (src && dst) ? find_identical_files(src, dst) : 0;
 314
 315        /* Free the hashes and return the number of renames found */
 316        free_similarity_list(src);
 317        free_similarity_list(dst);
 318        return ret;
 319}
 320
 321static unsigned int hash_filespec(struct diff_filespec *filespec)
 322{
 323        unsigned int hash;
 324        if (!filespec->sha1_valid) {
 325                if (diff_populate_filespec(filespec, 0))
 326                        return 0;
 327                hash_sha1_file(filespec->data, filespec->size, "blob", filespec->sha1);
 328        }
 329        memcpy(&hash, filespec->sha1, sizeof(hash));
 330        return hash;
 331}
 332
 333static void insert_file_table(struct hash_table *table, int src_dst, int index, struct diff_filespec *filespec)
 334{
 335        void **pos;
 336        unsigned int hash;
 337        struct file_similarity *entry = xmalloc(sizeof(*entry));
 338
 339        entry->src_dst = src_dst;
 340        entry->index = index;
 341        entry->filespec = filespec;
 342        entry->next = NULL;
 343
 344        hash = hash_filespec(filespec);
 345        pos = insert_hash(hash, entry, table);
 346
 347        /* We already had an entry there? */
 348        if (pos) {
 349                entry->next = *pos;
 350                *pos = entry;
 351        }
 352}
 353
 354/*
 355 * Find exact renames first.
 356 *
 357 * The first round matches up the up-to-date entries,
 358 * and then during the second round we try to match
 359 * cache-dirty entries as well.
 360 */
 361static int find_exact_renames(void)
 362{
 363        int i;
 364        struct hash_table file_table;
 365
 366        init_hash(&file_table);
 367        for (i = 0; i < rename_src_nr; i++)
 368                insert_file_table(&file_table, -1, i, rename_src[i].one);
 369
 370        for (i = 0; i < rename_dst_nr; i++)
 371                insert_file_table(&file_table, 1, i, rename_dst[i].two);
 372
 373        /* Find the renames */
 374        i = for_each_hash(&file_table, find_same_files);
 375
 376        /* .. and free the hash data structure */
 377        free_hash(&file_table);
 378
 379        return i;
 380}
 381
 382void diffcore_rename(struct diff_options *options)
 383{
 384        int detect_rename = options->detect_rename;
 385        int minimum_score = options->rename_score;
 386        int rename_limit = options->rename_limit;
 387        struct diff_queue_struct *q = &diff_queued_diff;
 388        struct diff_queue_struct outq;
 389        struct diff_score *mx;
 390        int i, j, rename_count;
 391        int num_create, num_src, dst_cnt;
 392
 393        if (!minimum_score)
 394                minimum_score = DEFAULT_RENAME_SCORE;
 395
 396        for (i = 0; i < q->nr; i++) {
 397                struct diff_filepair *p = q->queue[i];
 398                if (!DIFF_FILE_VALID(p->one)) {
 399                        if (!DIFF_FILE_VALID(p->two))
 400                                continue; /* unmerged */
 401                        else if (options->single_follow &&
 402                                 strcmp(options->single_follow, p->two->path))
 403                                continue; /* not interested */
 404                        else
 405                                locate_rename_dst(p->two, 1);
 406                }
 407                else if (!DIFF_FILE_VALID(p->two)) {
 408                        /*
 409                         * If the source is a broken "delete", and
 410                         * they did not really want to get broken,
 411                         * that means the source actually stays.
 412                         * So we increment the "rename_used" score
 413                         * by one, to indicate ourselves as a user
 414                         */
 415                        if (p->broken_pair && !p->score)
 416                                p->one->rename_used++;
 417                        register_rename_src(p->one, p->score);
 418                }
 419                else if (detect_rename == DIFF_DETECT_COPY) {
 420                        /*
 421                         * Increment the "rename_used" score by
 422                         * one, to indicate ourselves as a user.
 423                         */
 424                        p->one->rename_used++;
 425                        register_rename_src(p->one, p->score);
 426                }
 427        }
 428        if (rename_dst_nr == 0 || rename_src_nr == 0)
 429                goto cleanup; /* nothing to do */
 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         *    rename_dst_nr * rename_src_nr > 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 (rename_dst_nr > rename_limit && rename_src_nr > rename_limit)
 443                goto cleanup;
 444        if (rename_dst_nr * rename_src_nr > rename_limit * rename_limit)
 445                goto cleanup;
 446
 447        /*
 448         * We really want to cull the candidates list early
 449         * with cheap tests in order to avoid doing deltas.
 450         */
 451        rename_count = find_exact_renames();
 452
 453        /* Have we run out the created file pool?  If so we can avoid
 454         * doing the delta matrix altogether.
 455         */
 456        if (rename_count == rename_dst_nr)
 457                goto cleanup;
 458
 459        if (minimum_score == MAX_SCORE)
 460                goto cleanup;
 461
 462        num_create = (rename_dst_nr - rename_count);
 463        num_src = rename_src_nr;
 464        mx = xmalloc(sizeof(*mx) * num_create * num_src);
 465        for (dst_cnt = i = 0; i < rename_dst_nr; i++) {
 466                int base = dst_cnt * num_src;
 467                struct diff_filespec *two = rename_dst[i].two;
 468                if (rename_dst[i].pair)
 469                        continue; /* dealt with exact match already. */
 470                for (j = 0; j < rename_src_nr; j++) {
 471                        struct diff_filespec *one = rename_src[j].one;
 472                        struct diff_score *m = &mx[base+j];
 473                        m->src = j;
 474                        m->dst = i;
 475                        m->score = estimate_similarity(one, two,
 476                                                       minimum_score);
 477                        m->name_score = basename_same(one, two);
 478                        diff_free_filespec_blob(one);
 479                }
 480                /* We do not need the text anymore */
 481                diff_free_filespec_blob(two);
 482                dst_cnt++;
 483        }
 484        /* cost matrix sorted by most to least similar pair */
 485        qsort(mx, num_create * num_src, sizeof(*mx), score_compare);
 486        for (i = 0; i < num_create * num_src; i++) {
 487                struct diff_rename_dst *dst = &rename_dst[mx[i].dst];
 488                if (dst->pair)
 489                        continue; /* already done, either exact or fuzzy. */
 490                if (mx[i].score < minimum_score)
 491                        break; /* there is no more usable pair. */
 492                record_rename_pair(mx[i].dst, mx[i].src, mx[i].score);
 493                rename_count++;
 494        }
 495        free(mx);
 496
 497 cleanup:
 498        /* At this point, we have found some renames and copies and they
 499         * are recorded in rename_dst.  The original list is still in *q.
 500         */
 501        outq.queue = NULL;
 502        outq.nr = outq.alloc = 0;
 503        for (i = 0; i < q->nr; i++) {
 504                struct diff_filepair *p = q->queue[i];
 505                struct diff_filepair *pair_to_free = NULL;
 506
 507                if (!DIFF_FILE_VALID(p->one) && DIFF_FILE_VALID(p->two)) {
 508                        /*
 509                         * Creation
 510                         *
 511                         * We would output this create record if it has
 512                         * not been turned into a rename/copy already.
 513                         */
 514                        struct diff_rename_dst *dst =
 515                                locate_rename_dst(p->two, 0);
 516                        if (dst && dst->pair) {
 517                                diff_q(&outq, dst->pair);
 518                                pair_to_free = p;
 519                        }
 520                        else
 521                                /* no matching rename/copy source, so
 522                                 * record this as a creation.
 523                                 */
 524                                diff_q(&outq, p);
 525                }
 526                else if (DIFF_FILE_VALID(p->one) && !DIFF_FILE_VALID(p->two)) {
 527                        /*
 528                         * Deletion
 529                         *
 530                         * We would output this delete record if:
 531                         *
 532                         * (1) this is a broken delete and the counterpart
 533                         *     broken create remains in the output; or
 534                         * (2) this is not a broken delete, and rename_dst
 535                         *     does not have a rename/copy to move p->one->path
 536                         *     out of existence.
 537                         *
 538                         * Otherwise, the counterpart broken create
 539                         * has been turned into a rename-edit; or
 540                         * delete did not have a matching create to
 541                         * begin with.
 542                         */
 543                        if (DIFF_PAIR_BROKEN(p)) {
 544                                /* broken delete */
 545                                struct diff_rename_dst *dst =
 546                                        locate_rename_dst(p->one, 0);
 547                                if (dst && dst->pair)
 548                                        /* counterpart is now rename/copy */
 549                                        pair_to_free = p;
 550                        }
 551                        else {
 552                                if (p->one->rename_used)
 553                                        /* this path remains */
 554                                        pair_to_free = p;
 555                        }
 556
 557                        if (pair_to_free)
 558                                ;
 559                        else
 560                                diff_q(&outq, p);
 561                }
 562                else if (!diff_unmodified_pair(p))
 563                        /* all the usual ones need to be kept */
 564                        diff_q(&outq, p);
 565                else
 566                        /* no need to keep unmodified pairs */
 567                        pair_to_free = p;
 568
 569                if (pair_to_free)
 570                        diff_free_filepair(pair_to_free);
 571        }
 572        diff_debug_queue("done copying original", &outq);
 573
 574        free(q->queue);
 575        *q = outq;
 576        diff_debug_queue("done collapsing", q);
 577
 578        for (i = 0; i < rename_dst_nr; i++)
 579                free_filespec(rename_dst[i].two);
 580
 581        free(rename_dst);
 582        rename_dst = NULL;
 583        rename_dst_nr = rename_dst_alloc = 0;
 584        free(rename_src);
 585        rename_src = NULL;
 586        rename_src_nr = rename_src_alloc = 0;
 587        return;
 588}