86f6b2bd330f721a22377f0ca053bd413582ef5d
   1#include "cache.h"
   2#include "refs.h"
   3#include "object-store.h"
   4#include "cache-tree.h"
   5#include "mergesort.h"
   6#include "diff.h"
   7#include "diffcore.h"
   8#include "tag.h"
   9#include "blame.h"
  10#include "alloc.h"
  11#include "commit-slab.h"
  12
  13define_commit_slab(blame_suspects, struct blame_origin *);
  14static struct blame_suspects blame_suspects;
  15
  16struct blame_origin *get_blame_suspects(struct commit *commit)
  17{
  18        struct blame_origin **result;
  19
  20        result = blame_suspects_peek(&blame_suspects, commit);
  21
  22        return result ? *result : NULL;
  23}
  24
  25static void set_blame_suspects(struct commit *commit, struct blame_origin *origin)
  26{
  27        *blame_suspects_at(&blame_suspects, commit) = origin;
  28}
  29
  30void blame_origin_decref(struct blame_origin *o)
  31{
  32        if (o && --o->refcnt <= 0) {
  33                struct blame_origin *p, *l = NULL;
  34                if (o->previous)
  35                        blame_origin_decref(o->previous);
  36                free(o->file.ptr);
  37                /* Should be present exactly once in commit chain */
  38                for (p = get_blame_suspects(o->commit); p; l = p, p = p->next) {
  39                        if (p == o) {
  40                                if (l)
  41                                        l->next = p->next;
  42                                else
  43                                        set_blame_suspects(o->commit, p->next);
  44                                free(o);
  45                                return;
  46                        }
  47                }
  48                die("internal error in blame_origin_decref");
  49        }
  50}
  51
  52/*
  53 * Given a commit and a path in it, create a new origin structure.
  54 * The callers that add blame to the scoreboard should use
  55 * get_origin() to obtain shared, refcounted copy instead of calling
  56 * this function directly.
  57 */
  58static struct blame_origin *make_origin(struct commit *commit, const char *path)
  59{
  60        struct blame_origin *o;
  61        FLEX_ALLOC_STR(o, path, path);
  62        o->commit = commit;
  63        o->refcnt = 1;
  64        o->next = get_blame_suspects(commit);
  65        set_blame_suspects(commit, o);
  66        return o;
  67}
  68
  69/*
  70 * Locate an existing origin or create a new one.
  71 * This moves the origin to front position in the commit util list.
  72 */
  73static struct blame_origin *get_origin(struct commit *commit, const char *path)
  74{
  75        struct blame_origin *o, *l;
  76
  77        for (o = get_blame_suspects(commit), l = NULL; o; l = o, o = o->next) {
  78                if (!strcmp(o->path, path)) {
  79                        /* bump to front */
  80                        if (l) {
  81                                l->next = o->next;
  82                                o->next = get_blame_suspects(commit);
  83                                set_blame_suspects(commit, o);
  84                        }
  85                        return blame_origin_incref(o);
  86                }
  87        }
  88        return make_origin(commit, path);
  89}
  90
  91
  92
  93static void verify_working_tree_path(struct repository *r,
  94                                     struct commit *work_tree, const char *path)
  95{
  96        struct commit_list *parents;
  97        int pos;
  98
  99        for (parents = work_tree->parents; parents; parents = parents->next) {
 100                const struct object_id *commit_oid = &parents->item->object.oid;
 101                struct object_id blob_oid;
 102                unsigned mode;
 103
 104                if (!get_tree_entry(commit_oid, path, &blob_oid, &mode) &&
 105                    oid_object_info(r, &blob_oid, NULL) == OBJ_BLOB)
 106                        return;
 107        }
 108
 109        pos = index_name_pos(r->index, path, strlen(path));
 110        if (pos >= 0)
 111                ; /* path is in the index */
 112        else if (-1 - pos < r->index->cache_nr &&
 113                 !strcmp(r->index->cache[-1 - pos]->name, path))
 114                ; /* path is in the index, unmerged */
 115        else
 116                die("no such path '%s' in HEAD", path);
 117}
 118
 119static struct commit_list **append_parent(struct repository *r,
 120                                          struct commit_list **tail,
 121                                          const struct object_id *oid)
 122{
 123        struct commit *parent;
 124
 125        parent = lookup_commit_reference(r, oid);
 126        if (!parent)
 127                die("no such commit %s", oid_to_hex(oid));
 128        return &commit_list_insert(parent, tail)->next;
 129}
 130
 131static void append_merge_parents(struct repository *r,
 132                                 struct commit_list **tail)
 133{
 134        int merge_head;
 135        struct strbuf line = STRBUF_INIT;
 136
 137        merge_head = open(git_path_merge_head(r), O_RDONLY);
 138        if (merge_head < 0) {
 139                if (errno == ENOENT)
 140                        return;
 141                die("cannot open '%s' for reading",
 142                    git_path_merge_head(r));
 143        }
 144
 145        while (!strbuf_getwholeline_fd(&line, merge_head, '\n')) {
 146                struct object_id oid;
 147                if (line.len < GIT_SHA1_HEXSZ || get_oid_hex(line.buf, &oid))
 148                        die("unknown line in '%s': %s",
 149                            git_path_merge_head(r), line.buf);
 150                tail = append_parent(r, tail, &oid);
 151        }
 152        close(merge_head);
 153        strbuf_release(&line);
 154}
 155
 156/*
 157 * This isn't as simple as passing sb->buf and sb->len, because we
 158 * want to transfer ownership of the buffer to the commit (so we
 159 * must use detach).
 160 */
 161static void set_commit_buffer_from_strbuf(struct repository *r,
 162                                          struct commit *c,
 163                                          struct strbuf *sb)
 164{
 165        size_t len;
 166        void *buf = strbuf_detach(sb, &len);
 167        set_commit_buffer(r, c, buf, len);
 168}
 169
 170/*
 171 * Prepare a dummy commit that represents the work tree (or staged) item.
 172 * Note that annotating work tree item never works in the reverse.
 173 */
 174static struct commit *fake_working_tree_commit(struct repository *r,
 175                                               struct diff_options *opt,
 176                                               const char *path,
 177                                               const char *contents_from)
 178{
 179        struct commit *commit;
 180        struct blame_origin *origin;
 181        struct commit_list **parent_tail, *parent;
 182        struct object_id head_oid;
 183        struct strbuf buf = STRBUF_INIT;
 184        const char *ident;
 185        time_t now;
 186        int len;
 187        struct cache_entry *ce;
 188        unsigned mode;
 189        struct strbuf msg = STRBUF_INIT;
 190
 191        read_index(r->index);
 192        time(&now);
 193        commit = alloc_commit_node(r);
 194        commit->object.parsed = 1;
 195        commit->date = now;
 196        parent_tail = &commit->parents;
 197
 198        if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, &head_oid, NULL))
 199                die("no such ref: HEAD");
 200
 201        parent_tail = append_parent(r, parent_tail, &head_oid);
 202        append_merge_parents(r, parent_tail);
 203        verify_working_tree_path(r, commit, path);
 204
 205        origin = make_origin(commit, path);
 206
 207        ident = fmt_ident("Not Committed Yet", "not.committed.yet", NULL, 0);
 208        strbuf_addstr(&msg, "tree 0000000000000000000000000000000000000000\n");
 209        for (parent = commit->parents; parent; parent = parent->next)
 210                strbuf_addf(&msg, "parent %s\n",
 211                            oid_to_hex(&parent->item->object.oid));
 212        strbuf_addf(&msg,
 213                    "author %s\n"
 214                    "committer %s\n\n"
 215                    "Version of %s from %s\n",
 216                    ident, ident, path,
 217                    (!contents_from ? path :
 218                     (!strcmp(contents_from, "-") ? "standard input" : contents_from)));
 219        set_commit_buffer_from_strbuf(r, commit, &msg);
 220
 221        if (!contents_from || strcmp("-", contents_from)) {
 222                struct stat st;
 223                const char *read_from;
 224                char *buf_ptr;
 225                unsigned long buf_len;
 226
 227                if (contents_from) {
 228                        if (stat(contents_from, &st) < 0)
 229                                die_errno("Cannot stat '%s'", contents_from);
 230                        read_from = contents_from;
 231                }
 232                else {
 233                        if (lstat(path, &st) < 0)
 234                                die_errno("Cannot lstat '%s'", path);
 235                        read_from = path;
 236                }
 237                mode = canon_mode(st.st_mode);
 238
 239                switch (st.st_mode & S_IFMT) {
 240                case S_IFREG:
 241                        if (opt->flags.allow_textconv &&
 242                            textconv_object(r, read_from, mode, &null_oid, 0, &buf_ptr, &buf_len))
 243                                strbuf_attach(&buf, buf_ptr, buf_len, buf_len + 1);
 244                        else if (strbuf_read_file(&buf, read_from, st.st_size) != st.st_size)
 245                                die_errno("cannot open or read '%s'", read_from);
 246                        break;
 247                case S_IFLNK:
 248                        if (strbuf_readlink(&buf, read_from, st.st_size) < 0)
 249                                die_errno("cannot readlink '%s'", read_from);
 250                        break;
 251                default:
 252                        die("unsupported file type %s", read_from);
 253                }
 254        }
 255        else {
 256                /* Reading from stdin */
 257                mode = 0;
 258                if (strbuf_read(&buf, 0, 0) < 0)
 259                        die_errno("failed to read from stdin");
 260        }
 261        convert_to_git(r->index, path, buf.buf, buf.len, &buf, 0);
 262        origin->file.ptr = buf.buf;
 263        origin->file.size = buf.len;
 264        pretend_object_file(buf.buf, buf.len, OBJ_BLOB, &origin->blob_oid);
 265
 266        /*
 267         * Read the current index, replace the path entry with
 268         * origin->blob_sha1 without mucking with its mode or type
 269         * bits; we are not going to write this index out -- we just
 270         * want to run "diff-index --cached".
 271         */
 272        discard_index(r->index);
 273        read_index(r->index);
 274
 275        len = strlen(path);
 276        if (!mode) {
 277                int pos = index_name_pos(r->index, path, len);
 278                if (0 <= pos)
 279                        mode = r->index->cache[pos]->ce_mode;
 280                else
 281                        /* Let's not bother reading from HEAD tree */
 282                        mode = S_IFREG | 0644;
 283        }
 284        ce = make_empty_cache_entry(r->index, len);
 285        oidcpy(&ce->oid, &origin->blob_oid);
 286        memcpy(ce->name, path, len);
 287        ce->ce_flags = create_ce_flags(0);
 288        ce->ce_namelen = len;
 289        ce->ce_mode = create_ce_mode(mode);
 290        add_index_entry(r->index, ce,
 291                        ADD_CACHE_OK_TO_ADD | ADD_CACHE_OK_TO_REPLACE);
 292
 293        cache_tree_invalidate_path(r->index, path);
 294
 295        return commit;
 296}
 297
 298
 299
 300static int diff_hunks(mmfile_t *file_a, mmfile_t *file_b,
 301                      xdl_emit_hunk_consume_func_t hunk_func, void *cb_data, int xdl_opts)
 302{
 303        xpparam_t xpp = {0};
 304        xdemitconf_t xecfg = {0};
 305        xdemitcb_t ecb = {NULL};
 306
 307        xpp.flags = xdl_opts;
 308        xecfg.hunk_func = hunk_func;
 309        ecb.priv = cb_data;
 310        return xdi_diff(file_a, file_b, &xpp, &xecfg, &ecb);
 311}
 312
 313static const char *get_next_line(const char *start, const char *end)
 314{
 315        const char *nl = memchr(start, '\n', end - start);
 316
 317        return nl ? nl + 1 : end;
 318}
 319
 320static int find_line_starts(int **line_starts, const char *buf,
 321                            unsigned long len)
 322{
 323        const char *end = buf + len;
 324        const char *p;
 325        int *lineno;
 326        int num = 0;
 327
 328        for (p = buf; p < end; p = get_next_line(p, end))
 329                num++;
 330
 331        ALLOC_ARRAY(*line_starts, num + 1);
 332        lineno = *line_starts;
 333
 334        for (p = buf; p < end; p = get_next_line(p, end))
 335                *lineno++ = p - buf;
 336
 337        *lineno = len;
 338
 339        return num;
 340}
 341
 342struct fingerprint_entry;
 343
 344/* A fingerprint is intended to loosely represent a string, such that two
 345 * fingerprints can be quickly compared to give an indication of the similarity
 346 * of the strings that they represent.
 347 *
 348 * A fingerprint is represented as a multiset of the lower-cased byte pairs in
 349 * the string that it represents. Whitespace is added at each end of the
 350 * string. Whitespace pairs are ignored. Whitespace is converted to '\0'.
 351 * For example, the string "Darth   Radar" will be converted to the following
 352 * fingerprint:
 353 * {"\0d", "da", "da", "ar", "ar", "rt", "th", "h\0", "\0r", "ra", "ad", "r\0"}
 354 *
 355 * The similarity between two fingerprints is the size of the intersection of
 356 * their multisets, including repeated elements. See fingerprint_similarity for
 357 * examples.
 358 *
 359 * For ease of implementation, the fingerprint is implemented as a map
 360 * of byte pairs to the count of that byte pair in the string, instead of
 361 * allowing repeated elements in a set.
 362 */
 363struct fingerprint {
 364        struct hashmap map;
 365        /* As we know the maximum number of entries in advance, it's
 366         * convenient to store the entries in a single array instead of having
 367         * the hashmap manage the memory.
 368         */
 369        struct fingerprint_entry *entries;
 370};
 371
 372/* A byte pair in a fingerprint. Stores the number of times the byte pair
 373 * occurs in the string that the fingerprint represents.
 374 */
 375struct fingerprint_entry {
 376        /* The hashmap entry - the hash represents the byte pair in its
 377         * entirety so we don't need to store the byte pair separately.
 378         */
 379        struct hashmap_entry entry;
 380        /* The number of times the byte pair occurs in the string that the
 381         * fingerprint represents.
 382         */
 383        int count;
 384};
 385
 386/* See `struct fingerprint` for an explanation of what a fingerprint is.
 387 * \param result the fingerprint of the string is stored here. This must be
 388 *               freed later using free_fingerprint.
 389 * \param line_begin the start of the string
 390 * \param line_end the end of the string
 391 */
 392static void get_fingerprint(struct fingerprint *result,
 393                            const char *line_begin,
 394                            const char *line_end)
 395{
 396        unsigned int hash, c0 = 0, c1;
 397        const char *p;
 398        int max_map_entry_count = 1 + line_end - line_begin;
 399        struct fingerprint_entry *entry = xcalloc(max_map_entry_count,
 400                sizeof(struct fingerprint_entry));
 401        struct fingerprint_entry *found_entry;
 402
 403        hashmap_init(&result->map, NULL, NULL, max_map_entry_count);
 404        result->entries = entry;
 405        for (p = line_begin; p <= line_end; ++p, c0 = c1) {
 406                /* Always terminate the string with whitespace.
 407                 * Normalise whitespace to 0, and normalise letters to
 408                 * lower case. This won't work for multibyte characters but at
 409                 * worst will match some unrelated characters.
 410                 */
 411                if ((p == line_end) || isspace(*p))
 412                        c1 = 0;
 413                else
 414                        c1 = tolower(*p);
 415                hash = c0 | (c1 << 8);
 416                /* Ignore whitespace pairs */
 417                if (hash == 0)
 418                        continue;
 419                hashmap_entry_init(entry, hash);
 420
 421                found_entry = hashmap_get(&result->map, entry, NULL);
 422                if (found_entry) {
 423                        found_entry->count += 1;
 424                } else {
 425                        entry->count = 1;
 426                        hashmap_add(&result->map, entry);
 427                        ++entry;
 428                }
 429        }
 430}
 431
 432static void free_fingerprint(struct fingerprint *f)
 433{
 434        hashmap_free(&f->map, 0);
 435        free(f->entries);
 436}
 437
 438/* Calculates the similarity between two fingerprints as the size of the
 439 * intersection of their multisets, including repeated elements. See
 440 * `struct fingerprint` for an explanation of the fingerprint representation.
 441 * The similarity between "cat mat" and "father rather" is 2 because "at" is
 442 * present twice in both strings while the similarity between "tim" and "mit"
 443 * is 0.
 444 */
 445static int fingerprint_similarity(struct fingerprint *a, struct fingerprint *b)
 446{
 447        int intersection = 0;
 448        struct hashmap_iter iter;
 449        const struct fingerprint_entry *entry_a, *entry_b;
 450
 451        hashmap_iter_init(&b->map, &iter);
 452
 453        while ((entry_b = hashmap_iter_next(&iter))) {
 454                if ((entry_a = hashmap_get(&a->map, entry_b, NULL))) {
 455                        intersection += entry_a->count < entry_b->count ?
 456                                        entry_a->count : entry_b->count;
 457                }
 458        }
 459        return intersection;
 460}
 461
 462/* Subtracts byte-pair elements in B from A, modifying A in place.
 463 */
 464static void fingerprint_subtract(struct fingerprint *a, struct fingerprint *b)
 465{
 466        struct hashmap_iter iter;
 467        struct fingerprint_entry *entry_a;
 468        const struct fingerprint_entry *entry_b;
 469
 470        hashmap_iter_init(&b->map, &iter);
 471
 472        while ((entry_b = hashmap_iter_next(&iter))) {
 473                if ((entry_a = hashmap_get(&a->map, entry_b, NULL))) {
 474                        if (entry_a->count <= entry_b->count)
 475                                hashmap_remove(&a->map, entry_b, NULL);
 476                        else
 477                                entry_a->count -= entry_b->count;
 478                }
 479        }
 480}
 481
 482/* Calculate fingerprints for a series of lines.
 483 * Puts the fingerprints in the fingerprints array, which must have been
 484 * preallocated to allow storing line_count elements.
 485 */
 486static void get_line_fingerprints(struct fingerprint *fingerprints,
 487                                  const char *content, const int *line_starts,
 488                                  long first_line, long line_count)
 489{
 490        int i;
 491        const char *linestart, *lineend;
 492
 493        line_starts += first_line;
 494        for (i = 0; i < line_count; ++i) {
 495                linestart = content + line_starts[i];
 496                lineend = content + line_starts[i + 1];
 497                get_fingerprint(fingerprints + i, linestart, lineend);
 498        }
 499}
 500
 501static void free_line_fingerprints(struct fingerprint *fingerprints,
 502                                   int nr_fingerprints)
 503{
 504        int i;
 505
 506        for (i = 0; i < nr_fingerprints; i++)
 507                free_fingerprint(&fingerprints[i]);
 508}
 509
 510/* This contains the data necessary to linearly map a line number in one half
 511 * of a diff chunk to the line in the other half of the diff chunk that is
 512 * closest in terms of its position as a fraction of the length of the chunk.
 513 */
 514struct line_number_mapping {
 515        int destination_start, destination_length,
 516                source_start, source_length;
 517};
 518
 519/* Given a line number in one range, offset and scale it to map it onto the
 520 * other range.
 521 * Essentially this mapping is a simple linear equation but the calculation is
 522 * more complicated to allow performing it with integer operations.
 523 * Another complication is that if a line could map onto many lines in the
 524 * destination range then we want to choose the line at the center of those
 525 * possibilities.
 526 * Example: if the chunk is 2 lines long in A and 10 lines long in B then the
 527 * first 5 lines in B will map onto the first line in the A chunk, while the
 528 * last 5 lines will all map onto the second line in the A chunk.
 529 * Example: if the chunk is 10 lines long in A and 2 lines long in B then line
 530 * 0 in B will map onto line 2 in A, and line 1 in B will map onto line 7 in A.
 531 */
 532static int map_line_number(int line_number,
 533        const struct line_number_mapping *mapping)
 534{
 535        return ((line_number - mapping->source_start) * 2 + 1) *
 536               mapping->destination_length /
 537               (mapping->source_length * 2) +
 538               mapping->destination_start;
 539}
 540
 541/* Get a pointer to the element storing the similarity between a line in A
 542 * and a line in B.
 543 *
 544 * The similarities are stored in a 2-dimensional array. Each "row" in the
 545 * array contains the similarities for a line in B. The similarities stored in
 546 * a row are the similarities between the line in B and the nearby lines in A.
 547 * To keep the length of each row the same, it is padded out with values of -1
 548 * where the search range extends beyond the lines in A.
 549 * For example, if max_search_distance_a is 2 and the two sides of a diff chunk
 550 * look like this:
 551 * a | m
 552 * b | n
 553 * c | o
 554 * d | p
 555 * e | q
 556 * Then the similarity array will contain:
 557 * [-1, -1, am, bm, cm,
 558 *  -1, an, bn, cn, dn,
 559 *  ao, bo, co, do, eo,
 560 *  bp, cp, dp, ep, -1,
 561 *  cq, dq, eq, -1, -1]
 562 * Where similarities are denoted either by -1 for invalid, or the
 563 * concatenation of the two lines in the diff being compared.
 564 *
 565 * \param similarities array of similarities between lines in A and B
 566 * \param line_a the index of the line in A, in the same frame of reference as
 567 *      closest_line_a.
 568 * \param local_line_b the index of the line in B, relative to the first line
 569 *                     in B that similarities represents.
 570 * \param closest_line_a the index of the line in A that is deemed to be
 571 *                       closest to local_line_b. This must be in the same
 572 *                       frame of reference as line_a. This value defines
 573 *                       where similarities is centered for the line in B.
 574 * \param max_search_distance_a maximum distance in lines from the closest line
 575 *                              in A for other lines in A for which
 576 *                              similarities may be calculated.
 577 */
 578static int *get_similarity(int *similarities,
 579                           int line_a, int local_line_b,
 580                           int closest_line_a, int max_search_distance_a)
 581{
 582        assert(abs(line_a - closest_line_a) <=
 583               max_search_distance_a);
 584        return similarities + line_a - closest_line_a +
 585               max_search_distance_a +
 586               local_line_b * (max_search_distance_a * 2 + 1);
 587}
 588
 589#define CERTAIN_NOTHING_MATCHES -2
 590#define CERTAINTY_NOT_CALCULATED -1
 591
 592/* Given a line in B, first calculate its similarities with nearby lines in A
 593 * if not already calculated, then identify the most similar and second most
 594 * similar lines. The "certainty" is calculated based on those two
 595 * similarities.
 596 *
 597 * \param start_a the index of the first line of the chunk in A
 598 * \param length_a the length in lines of the chunk in A
 599 * \param local_line_b the index of the line in B, relative to the first line
 600 *                     in the chunk.
 601 * \param fingerprints_a array of fingerprints for the chunk in A
 602 * \param fingerprints_b array of fingerprints for the chunk in B
 603 * \param similarities 2-dimensional array of similarities between lines in A
 604 *                     and B. See get_similarity() for more details.
 605 * \param certainties array of values indicating how strongly a line in B is
 606 *                    matched with some line in A.
 607 * \param second_best_result array of absolute indices in A for the second
 608 *                           closest match of a line in B.
 609 * \param result array of absolute indices in A for the closest match of a line
 610 *               in B.
 611 * \param max_search_distance_a maximum distance in lines from the closest line
 612 *                              in A for other lines in A for which
 613 *                              similarities may be calculated.
 614 * \param map_line_number_in_b_to_a parameter to map_line_number().
 615 */
 616static void find_best_line_matches(
 617        int start_a,
 618        int length_a,
 619        int start_b,
 620        int local_line_b,
 621        struct fingerprint *fingerprints_a,
 622        struct fingerprint *fingerprints_b,
 623        int *similarities,
 624        int *certainties,
 625        int *second_best_result,
 626        int *result,
 627        const int max_search_distance_a,
 628        const struct line_number_mapping *map_line_number_in_b_to_a)
 629{
 630
 631        int i, search_start, search_end, closest_local_line_a, *similarity,
 632                best_similarity = 0, second_best_similarity = 0,
 633                best_similarity_index = 0, second_best_similarity_index = 0;
 634
 635        /* certainty has already been calculated so no need to redo the work */
 636        if (certainties[local_line_b] != CERTAINTY_NOT_CALCULATED)
 637                return;
 638
 639        closest_local_line_a = map_line_number(
 640                local_line_b + start_b, map_line_number_in_b_to_a) - start_a;
 641
 642        search_start = closest_local_line_a - max_search_distance_a;
 643        if (search_start < 0)
 644                search_start = 0;
 645
 646        search_end = closest_local_line_a + max_search_distance_a + 1;
 647        if (search_end > length_a)
 648                search_end = length_a;
 649
 650        for (i = search_start; i < search_end; ++i) {
 651                similarity = get_similarity(similarities,
 652                                            i, local_line_b,
 653                                            closest_local_line_a,
 654                                            max_search_distance_a);
 655                if (*similarity == -1) {
 656                        /* This value will never exceed 10 but assert just in
 657                         * case
 658                         */
 659                        assert(abs(i - closest_local_line_a) < 1000);
 660                        /* scale the similarity by (1000 - distance from
 661                         * closest line) to act as a tie break between lines
 662                         * that otherwise are equally similar.
 663                         */
 664                        *similarity = fingerprint_similarity(
 665                                fingerprints_b + local_line_b,
 666                                fingerprints_a + i) *
 667                                (1000 - abs(i - closest_local_line_a));
 668                }
 669                if (*similarity > best_similarity) {
 670                        second_best_similarity = best_similarity;
 671                        second_best_similarity_index = best_similarity_index;
 672                        best_similarity = *similarity;
 673                        best_similarity_index = i;
 674                } else if (*similarity > second_best_similarity) {
 675                        second_best_similarity = *similarity;
 676                        second_best_similarity_index = i;
 677                }
 678        }
 679
 680        if (best_similarity == 0) {
 681                /* this line definitely doesn't match with anything. Mark it
 682                 * with this special value so it doesn't get invalidated and
 683                 * won't be recalculated.
 684                 */
 685                certainties[local_line_b] = CERTAIN_NOTHING_MATCHES;
 686                result[local_line_b] = -1;
 687        } else {
 688                /* Calculate the certainty with which this line matches.
 689                 * If the line matches well with two lines then that reduces
 690                 * the certainty. However we still want to prioritise matching
 691                 * a line that matches very well with two lines over matching a
 692                 * line that matches poorly with one line, hence doubling
 693                 * best_similarity.
 694                 * This means that if we have
 695                 * line X that matches only one line with a score of 3,
 696                 * line Y that matches two lines equally with a score of 5,
 697                 * and line Z that matches only one line with a score or 2,
 698                 * then the lines in order of certainty are X, Y, Z.
 699                 */
 700                certainties[local_line_b] = best_similarity * 2 -
 701                        second_best_similarity;
 702
 703                /* We keep both the best and second best results to allow us to
 704                 * check at a later stage of the matching process whether the
 705                 * result needs to be invalidated.
 706                 */
 707                result[local_line_b] = start_a + best_similarity_index;
 708                second_best_result[local_line_b] =
 709                        start_a + second_best_similarity_index;
 710        }
 711}
 712
 713/*
 714 * This finds the line that we can match with the most confidence, and
 715 * uses it as a partition. It then calls itself on the lines on either side of
 716 * that partition. In this way we avoid lines appearing out of order, and
 717 * retain a sensible line ordering.
 718 * \param start_a index of the first line in A with which lines in B may be
 719 *                compared.
 720 * \param start_b index of the first line in B for which matching should be
 721 *                done.
 722 * \param length_a number of lines in A with which lines in B may be compared.
 723 * \param length_b number of lines in B for which matching should be done.
 724 * \param fingerprints_a mutable array of fingerprints in A. The first element
 725 *                       corresponds to the line at start_a.
 726 * \param fingerprints_b array of fingerprints in B. The first element
 727 *                       corresponds to the line at start_b.
 728 * \param similarities 2-dimensional array of similarities between lines in A
 729 *                     and B. See get_similarity() for more details.
 730 * \param certainties array of values indicating how strongly a line in B is
 731 *                    matched with some line in A.
 732 * \param second_best_result array of absolute indices in A for the second
 733 *                           closest match of a line in B.
 734 * \param result array of absolute indices in A for the closest match of a line
 735 *               in B.
 736 * \param max_search_distance_a maximum distance in lines from the closest line
 737 *                            in A for other lines in A for which
 738 *                            similarities may be calculated.
 739 * \param max_search_distance_b an upper bound on the greatest possible
 740 *                            distance between lines in B such that they will
 741 *                              both be compared with the same line in A
 742 *                            according to max_search_distance_a.
 743 * \param map_line_number_in_b_to_a parameter to map_line_number().
 744 */
 745static void fuzzy_find_matching_lines_recurse(
 746        int start_a, int start_b,
 747        int length_a, int length_b,
 748        struct fingerprint *fingerprints_a,
 749        struct fingerprint *fingerprints_b,
 750        int *similarities,
 751        int *certainties,
 752        int *second_best_result,
 753        int *result,
 754        int max_search_distance_a,
 755        int max_search_distance_b,
 756        const struct line_number_mapping *map_line_number_in_b_to_a)
 757{
 758        int i, invalidate_min, invalidate_max, offset_b,
 759                second_half_start_a, second_half_start_b,
 760                second_half_length_a, second_half_length_b,
 761                most_certain_line_a, most_certain_local_line_b = -1,
 762                most_certain_line_certainty = -1,
 763                closest_local_line_a;
 764
 765        for (i = 0; i < length_b; ++i) {
 766                find_best_line_matches(start_a,
 767                                       length_a,
 768                                       start_b,
 769                                       i,
 770                                       fingerprints_a,
 771                                       fingerprints_b,
 772                                       similarities,
 773                                       certainties,
 774                                       second_best_result,
 775                                       result,
 776                                       max_search_distance_a,
 777                                       map_line_number_in_b_to_a);
 778
 779                if (certainties[i] > most_certain_line_certainty) {
 780                        most_certain_line_certainty = certainties[i];
 781                        most_certain_local_line_b = i;
 782                }
 783        }
 784
 785        /* No matches. */
 786        if (most_certain_local_line_b == -1)
 787                return;
 788
 789        most_certain_line_a = result[most_certain_local_line_b];
 790
 791        /*
 792         * Subtract the most certain line's fingerprint in B from the matched
 793         * fingerprint in A. This means that other lines in B can't also match
 794         * the same parts of the line in A.
 795         */
 796        fingerprint_subtract(fingerprints_a + most_certain_line_a - start_a,
 797                             fingerprints_b + most_certain_local_line_b);
 798
 799        /* Invalidate results that may be affected by the choice of most
 800         * certain line.
 801         */
 802        invalidate_min = most_certain_local_line_b - max_search_distance_b;
 803        invalidate_max = most_certain_local_line_b + max_search_distance_b + 1;
 804        if (invalidate_min < 0)
 805                invalidate_min = 0;
 806        if (invalidate_max > length_b)
 807                invalidate_max = length_b;
 808
 809        /* As the fingerprint in A has changed, discard previously calculated
 810         * similarity values with that fingerprint.
 811         */
 812        for (i = invalidate_min; i < invalidate_max; ++i) {
 813                closest_local_line_a = map_line_number(
 814                        i + start_b, map_line_number_in_b_to_a) - start_a;
 815
 816                /* Check that the lines in A and B are close enough that there
 817                 * is a similarity value for them.
 818                 */
 819                if (abs(most_certain_line_a - start_a - closest_local_line_a) >
 820                        max_search_distance_a) {
 821                        continue;
 822                }
 823
 824                *get_similarity(similarities, most_certain_line_a - start_a,
 825                                i, closest_local_line_a,
 826                                max_search_distance_a) = -1;
 827        }
 828
 829        /* More invalidating of results that may be affected by the choice of
 830         * most certain line.
 831         * Discard the matches for lines in B that are currently matched with a
 832         * line in A such that their ordering contradicts the ordering imposed
 833         * by the choice of most certain line.
 834         */
 835        for (i = most_certain_local_line_b - 1; i >= invalidate_min; --i) {
 836                /* In this loop we discard results for lines in B that are
 837                 * before most-certain-line-B but are matched with a line in A
 838                 * that is after most-certain-line-A.
 839                 */
 840                if (certainties[i] >= 0 &&
 841                    (result[i] >= most_certain_line_a ||
 842                     second_best_result[i] >= most_certain_line_a)) {
 843                        certainties[i] = CERTAINTY_NOT_CALCULATED;
 844                }
 845        }
 846        for (i = most_certain_local_line_b + 1; i < invalidate_max; ++i) {
 847                /* In this loop we discard results for lines in B that are
 848                 * after most-certain-line-B but are matched with a line in A
 849                 * that is before most-certain-line-A.
 850                 */
 851                if (certainties[i] >= 0 &&
 852                    (result[i] <= most_certain_line_a ||
 853                     second_best_result[i] <= most_certain_line_a)) {
 854                        certainties[i] = CERTAINTY_NOT_CALCULATED;
 855                }
 856        }
 857
 858        /* Repeat the matching process for lines before the most certain line.
 859         */
 860        if (most_certain_local_line_b > 0) {
 861                fuzzy_find_matching_lines_recurse(
 862                        start_a, start_b,
 863                        most_certain_line_a + 1 - start_a,
 864                        most_certain_local_line_b,
 865                        fingerprints_a, fingerprints_b, similarities,
 866                        certainties, second_best_result, result,
 867                        max_search_distance_a,
 868                        max_search_distance_b,
 869                        map_line_number_in_b_to_a);
 870        }
 871        /* Repeat the matching process for lines after the most certain line.
 872         */
 873        if (most_certain_local_line_b + 1 < length_b) {
 874                second_half_start_a = most_certain_line_a;
 875                offset_b = most_certain_local_line_b + 1;
 876                second_half_start_b = start_b + offset_b;
 877                second_half_length_a =
 878                        length_a + start_a - second_half_start_a;
 879                second_half_length_b =
 880                        length_b + start_b - second_half_start_b;
 881                fuzzy_find_matching_lines_recurse(
 882                        second_half_start_a, second_half_start_b,
 883                        second_half_length_a, second_half_length_b,
 884                        fingerprints_a + second_half_start_a - start_a,
 885                        fingerprints_b + offset_b,
 886                        similarities +
 887                                offset_b * (max_search_distance_a * 2 + 1),
 888                        certainties + offset_b,
 889                        second_best_result + offset_b, result + offset_b,
 890                        max_search_distance_a,
 891                        max_search_distance_b,
 892                        map_line_number_in_b_to_a);
 893        }
 894}
 895
 896/* Find the lines in the parent line range that most closely match the lines in
 897 * the target line range. This is accomplished by matching fingerprints in each
 898 * blame_origin, and choosing the best matches that preserve the line ordering.
 899 * See struct fingerprint for details of fingerprint matching, and
 900 * fuzzy_find_matching_lines_recurse for details of preserving line ordering.
 901 *
 902 * The performance is believed to be O(n log n) in the typical case and O(n^2)
 903 * in a pathological case, where n is the number of lines in the target range.
 904 */
 905static int *fuzzy_find_matching_lines(struct blame_origin *parent,
 906                                      struct blame_origin *target,
 907                                      int tlno, int parent_slno, int same,
 908                                      int parent_len)
 909{
 910        /* We use the terminology "A" for the left hand side of the diff AKA
 911         * parent, and "B" for the right hand side of the diff AKA target. */
 912        int start_a = parent_slno;
 913        int length_a = parent_len;
 914        int start_b = tlno;
 915        int length_b = same - tlno;
 916
 917        struct line_number_mapping map_line_number_in_b_to_a = {
 918                start_a, length_a, start_b, length_b
 919        };
 920
 921        struct fingerprint *fingerprints_a = parent->fingerprints;
 922        struct fingerprint *fingerprints_b = target->fingerprints;
 923
 924        int i, *result, *second_best_result,
 925                *certainties, *similarities, similarity_count;
 926
 927        /*
 928         * max_search_distance_a means that given a line in B, compare it to
 929         * the line in A that is closest to its position, and the lines in A
 930         * that are no greater than max_search_distance_a lines away from the
 931         * closest line in A.
 932         *
 933         * max_search_distance_b is an upper bound on the greatest possible
 934         * distance between lines in B such that they will both be compared
 935         * with the same line in A according to max_search_distance_a.
 936         */
 937        int max_search_distance_a = 10, max_search_distance_b;
 938
 939        if (length_a <= 0)
 940                return NULL;
 941
 942        if (max_search_distance_a >= length_a)
 943                max_search_distance_a = length_a ? length_a - 1 : 0;
 944
 945        max_search_distance_b = ((2 * max_search_distance_a + 1) * length_b
 946                                 - 1) / length_a;
 947
 948        result = xcalloc(sizeof(int), length_b);
 949        second_best_result = xcalloc(sizeof(int), length_b);
 950        certainties = xcalloc(sizeof(int), length_b);
 951
 952        /* See get_similarity() for details of similarities. */
 953        similarity_count = length_b * (max_search_distance_a * 2 + 1);
 954        similarities = xcalloc(sizeof(int), similarity_count);
 955
 956        for (i = 0; i < length_b; ++i) {
 957                result[i] = -1;
 958                second_best_result[i] = -1;
 959                certainties[i] = CERTAINTY_NOT_CALCULATED;
 960        }
 961
 962        for (i = 0; i < similarity_count; ++i)
 963                similarities[i] = -1;
 964
 965        fuzzy_find_matching_lines_recurse(start_a, start_b,
 966                                          length_a, length_b,
 967                                          fingerprints_a + start_a,
 968                                          fingerprints_b + start_b,
 969                                          similarities,
 970                                          certainties,
 971                                          second_best_result,
 972                                          result,
 973                                          max_search_distance_a,
 974                                          max_search_distance_b,
 975                                          &map_line_number_in_b_to_a);
 976
 977        free(similarities);
 978        free(certainties);
 979        free(second_best_result);
 980
 981        return result;
 982}
 983
 984static void fill_origin_fingerprints(struct blame_origin *o, mmfile_t *file)
 985{
 986        int *line_starts;
 987
 988        if (o->fingerprints)
 989                return;
 990        o->num_lines = find_line_starts(&line_starts, o->file.ptr,
 991                                        o->file.size);
 992        o->fingerprints = xcalloc(sizeof(struct fingerprint), o->num_lines);
 993        get_line_fingerprints(o->fingerprints, o->file.ptr, line_starts,
 994                              0, o->num_lines);
 995        free(line_starts);
 996}
 997
 998static void drop_origin_fingerprints(struct blame_origin *o)
 999{
1000        if (o->fingerprints) {
1001                free_line_fingerprints(o->fingerprints, o->num_lines);
1002                o->num_lines = 0;
1003                FREE_AND_NULL(o->fingerprints);
1004        }
1005}
1006
1007/*
1008 * Given an origin, prepare mmfile_t structure to be used by the
1009 * diff machinery
1010 */
1011static void fill_origin_blob(struct diff_options *opt,
1012                             struct blame_origin *o, mmfile_t *file,
1013                             int *num_read_blob, int fill_fingerprints)
1014{
1015        if (!o->file.ptr) {
1016                enum object_type type;
1017                unsigned long file_size;
1018
1019                (*num_read_blob)++;
1020                if (opt->flags.allow_textconv &&
1021                    textconv_object(opt->repo, o->path, o->mode,
1022                                    &o->blob_oid, 1, &file->ptr, &file_size))
1023                        ;
1024                else
1025                        file->ptr = read_object_file(&o->blob_oid, &type,
1026                                                     &file_size);
1027                file->size = file_size;
1028
1029                if (!file->ptr)
1030                        die("Cannot read blob %s for path %s",
1031                            oid_to_hex(&o->blob_oid),
1032                            o->path);
1033                o->file = *file;
1034        }
1035        else
1036                *file = o->file;
1037        if (fill_fingerprints)
1038                fill_origin_fingerprints(o, file);
1039}
1040
1041static void drop_origin_blob(struct blame_origin *o)
1042{
1043        FREE_AND_NULL(o->file.ptr);
1044        drop_origin_fingerprints(o);
1045}
1046
1047/*
1048 * Any merge of blames happens on lists of blames that arrived via
1049 * different parents in a single suspect.  In this case, we want to
1050 * sort according to the suspect line numbers as opposed to the final
1051 * image line numbers.  The function body is somewhat longish because
1052 * it avoids unnecessary writes.
1053 */
1054
1055static struct blame_entry *blame_merge(struct blame_entry *list1,
1056                                       struct blame_entry *list2)
1057{
1058        struct blame_entry *p1 = list1, *p2 = list2,
1059                **tail = &list1;
1060
1061        if (!p1)
1062                return p2;
1063        if (!p2)
1064                return p1;
1065
1066        if (p1->s_lno <= p2->s_lno) {
1067                do {
1068                        tail = &p1->next;
1069                        if ((p1 = *tail) == NULL) {
1070                                *tail = p2;
1071                                return list1;
1072                        }
1073                } while (p1->s_lno <= p2->s_lno);
1074        }
1075        for (;;) {
1076                *tail = p2;
1077                do {
1078                        tail = &p2->next;
1079                        if ((p2 = *tail) == NULL)  {
1080                                *tail = p1;
1081                                return list1;
1082                        }
1083                } while (p1->s_lno > p2->s_lno);
1084                *tail = p1;
1085                do {
1086                        tail = &p1->next;
1087                        if ((p1 = *tail) == NULL) {
1088                                *tail = p2;
1089                                return list1;
1090                        }
1091                } while (p1->s_lno <= p2->s_lno);
1092        }
1093}
1094
1095static void *get_next_blame(const void *p)
1096{
1097        return ((struct blame_entry *)p)->next;
1098}
1099
1100static void set_next_blame(void *p1, void *p2)
1101{
1102        ((struct blame_entry *)p1)->next = p2;
1103}
1104
1105/*
1106 * Final image line numbers are all different, so we don't need a
1107 * three-way comparison here.
1108 */
1109
1110static int compare_blame_final(const void *p1, const void *p2)
1111{
1112        return ((struct blame_entry *)p1)->lno > ((struct blame_entry *)p2)->lno
1113                ? 1 : -1;
1114}
1115
1116static int compare_blame_suspect(const void *p1, const void *p2)
1117{
1118        const struct blame_entry *s1 = p1, *s2 = p2;
1119        /*
1120         * to allow for collating suspects, we sort according to the
1121         * respective pointer value as the primary sorting criterion.
1122         * The actual relation is pretty unimportant as long as it
1123         * establishes a total order.  Comparing as integers gives us
1124         * that.
1125         */
1126        if (s1->suspect != s2->suspect)
1127                return (intptr_t)s1->suspect > (intptr_t)s2->suspect ? 1 : -1;
1128        if (s1->s_lno == s2->s_lno)
1129                return 0;
1130        return s1->s_lno > s2->s_lno ? 1 : -1;
1131}
1132
1133void blame_sort_final(struct blame_scoreboard *sb)
1134{
1135        sb->ent = llist_mergesort(sb->ent, get_next_blame, set_next_blame,
1136                                  compare_blame_final);
1137}
1138
1139static int compare_commits_by_reverse_commit_date(const void *a,
1140                                                  const void *b,
1141                                                  void *c)
1142{
1143        return -compare_commits_by_commit_date(a, b, c);
1144}
1145
1146/*
1147 * For debugging -- origin is refcounted, and this asserts that
1148 * we do not underflow.
1149 */
1150static void sanity_check_refcnt(struct blame_scoreboard *sb)
1151{
1152        int baa = 0;
1153        struct blame_entry *ent;
1154
1155        for (ent = sb->ent; ent; ent = ent->next) {
1156                /* Nobody should have zero or negative refcnt */
1157                if (ent->suspect->refcnt <= 0) {
1158                        fprintf(stderr, "%s in %s has negative refcnt %d\n",
1159                                ent->suspect->path,
1160                                oid_to_hex(&ent->suspect->commit->object.oid),
1161                                ent->suspect->refcnt);
1162                        baa = 1;
1163                }
1164        }
1165        if (baa)
1166                sb->on_sanity_fail(sb, baa);
1167}
1168
1169/*
1170 * If two blame entries that are next to each other came from
1171 * contiguous lines in the same origin (i.e. <commit, path> pair),
1172 * merge them together.
1173 */
1174void blame_coalesce(struct blame_scoreboard *sb)
1175{
1176        struct blame_entry *ent, *next;
1177
1178        for (ent = sb->ent; ent && (next = ent->next); ent = next) {
1179                if (ent->suspect == next->suspect &&
1180                    ent->s_lno + ent->num_lines == next->s_lno &&
1181                    ent->ignored == next->ignored &&
1182                    ent->unblamable == next->unblamable) {
1183                        ent->num_lines += next->num_lines;
1184                        ent->next = next->next;
1185                        blame_origin_decref(next->suspect);
1186                        free(next);
1187                        ent->score = 0;
1188                        next = ent; /* again */
1189                }
1190        }
1191
1192        if (sb->debug) /* sanity */
1193                sanity_check_refcnt(sb);
1194}
1195
1196/*
1197 * Merge the given sorted list of blames into a preexisting origin.
1198 * If there were no previous blames to that commit, it is entered into
1199 * the commit priority queue of the score board.
1200 */
1201
1202static void queue_blames(struct blame_scoreboard *sb, struct blame_origin *porigin,
1203                         struct blame_entry *sorted)
1204{
1205        if (porigin->suspects)
1206                porigin->suspects = blame_merge(porigin->suspects, sorted);
1207        else {
1208                struct blame_origin *o;
1209                for (o = get_blame_suspects(porigin->commit); o; o = o->next) {
1210                        if (o->suspects) {
1211                                porigin->suspects = sorted;
1212                                return;
1213                        }
1214                }
1215                porigin->suspects = sorted;
1216                prio_queue_put(&sb->commits, porigin->commit);
1217        }
1218}
1219
1220/*
1221 * Fill the blob_sha1 field of an origin if it hasn't, so that later
1222 * call to fill_origin_blob() can use it to locate the data.  blob_sha1
1223 * for an origin is also used to pass the blame for the entire file to
1224 * the parent to detect the case where a child's blob is identical to
1225 * that of its parent's.
1226 *
1227 * This also fills origin->mode for corresponding tree path.
1228 */
1229static int fill_blob_sha1_and_mode(struct repository *r,
1230                                   struct blame_origin *origin)
1231{
1232        if (!is_null_oid(&origin->blob_oid))
1233                return 0;
1234        if (get_tree_entry(&origin->commit->object.oid, origin->path, &origin->blob_oid, &origin->mode))
1235                goto error_out;
1236        if (oid_object_info(r, &origin->blob_oid, NULL) != OBJ_BLOB)
1237                goto error_out;
1238        return 0;
1239 error_out:
1240        oidclr(&origin->blob_oid);
1241        origin->mode = S_IFINVALID;
1242        return -1;
1243}
1244
1245/*
1246 * We have an origin -- check if the same path exists in the
1247 * parent and return an origin structure to represent it.
1248 */
1249static struct blame_origin *find_origin(struct repository *r,
1250                                        struct commit *parent,
1251                                        struct blame_origin *origin)
1252{
1253        struct blame_origin *porigin;
1254        struct diff_options diff_opts;
1255        const char *paths[2];
1256
1257        /* First check any existing origins */
1258        for (porigin = get_blame_suspects(parent); porigin; porigin = porigin->next)
1259                if (!strcmp(porigin->path, origin->path)) {
1260                        /*
1261                         * The same path between origin and its parent
1262                         * without renaming -- the most common case.
1263                         */
1264                        return blame_origin_incref (porigin);
1265                }
1266
1267        /* See if the origin->path is different between parent
1268         * and origin first.  Most of the time they are the
1269         * same and diff-tree is fairly efficient about this.
1270         */
1271        repo_diff_setup(r, &diff_opts);
1272        diff_opts.flags.recursive = 1;
1273        diff_opts.detect_rename = 0;
1274        diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;
1275        paths[0] = origin->path;
1276        paths[1] = NULL;
1277
1278        parse_pathspec(&diff_opts.pathspec,
1279                       PATHSPEC_ALL_MAGIC & ~PATHSPEC_LITERAL,
1280                       PATHSPEC_LITERAL_PATH, "", paths);
1281        diff_setup_done(&diff_opts);
1282
1283        if (is_null_oid(&origin->commit->object.oid))
1284                do_diff_cache(get_commit_tree_oid(parent), &diff_opts);
1285        else
1286                diff_tree_oid(get_commit_tree_oid(parent),
1287                              get_commit_tree_oid(origin->commit),
1288                              "", &diff_opts);
1289        diffcore_std(&diff_opts);
1290
1291        if (!diff_queued_diff.nr) {
1292                /* The path is the same as parent */
1293                porigin = get_origin(parent, origin->path);
1294                oidcpy(&porigin->blob_oid, &origin->blob_oid);
1295                porigin->mode = origin->mode;
1296        } else {
1297                /*
1298                 * Since origin->path is a pathspec, if the parent
1299                 * commit had it as a directory, we will see a whole
1300                 * bunch of deletion of files in the directory that we
1301                 * do not care about.
1302                 */
1303                int i;
1304                struct diff_filepair *p = NULL;
1305                for (i = 0; i < diff_queued_diff.nr; i++) {
1306                        const char *name;
1307                        p = diff_queued_diff.queue[i];
1308                        name = p->one->path ? p->one->path : p->two->path;
1309                        if (!strcmp(name, origin->path))
1310                                break;
1311                }
1312                if (!p)
1313                        die("internal error in blame::find_origin");
1314                switch (p->status) {
1315                default:
1316                        die("internal error in blame::find_origin (%c)",
1317                            p->status);
1318                case 'M':
1319                        porigin = get_origin(parent, origin->path);
1320                        oidcpy(&porigin->blob_oid, &p->one->oid);
1321                        porigin->mode = p->one->mode;
1322                        break;
1323                case 'A':
1324                case 'T':
1325                        /* Did not exist in parent, or type changed */
1326                        break;
1327                }
1328        }
1329        diff_flush(&diff_opts);
1330        clear_pathspec(&diff_opts.pathspec);
1331        return porigin;
1332}
1333
1334/*
1335 * We have an origin -- find the path that corresponds to it in its
1336 * parent and return an origin structure to represent it.
1337 */
1338static struct blame_origin *find_rename(struct repository *r,
1339                                        struct commit *parent,
1340                                        struct blame_origin *origin)
1341{
1342        struct blame_origin *porigin = NULL;
1343        struct diff_options diff_opts;
1344        int i;
1345
1346        repo_diff_setup(r, &diff_opts);
1347        diff_opts.flags.recursive = 1;
1348        diff_opts.detect_rename = DIFF_DETECT_RENAME;
1349        diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;
1350        diff_opts.single_follow = origin->path;
1351        diff_setup_done(&diff_opts);
1352
1353        if (is_null_oid(&origin->commit->object.oid))
1354                do_diff_cache(get_commit_tree_oid(parent), &diff_opts);
1355        else
1356                diff_tree_oid(get_commit_tree_oid(parent),
1357                              get_commit_tree_oid(origin->commit),
1358                              "", &diff_opts);
1359        diffcore_std(&diff_opts);
1360
1361        for (i = 0; i < diff_queued_diff.nr; i++) {
1362                struct diff_filepair *p = diff_queued_diff.queue[i];
1363                if ((p->status == 'R' || p->status == 'C') &&
1364                    !strcmp(p->two->path, origin->path)) {
1365                        porigin = get_origin(parent, p->one->path);
1366                        oidcpy(&porigin->blob_oid, &p->one->oid);
1367                        porigin->mode = p->one->mode;
1368                        break;
1369                }
1370        }
1371        diff_flush(&diff_opts);
1372        clear_pathspec(&diff_opts.pathspec);
1373        return porigin;
1374}
1375
1376/*
1377 * Append a new blame entry to a given output queue.
1378 */
1379static void add_blame_entry(struct blame_entry ***queue,
1380                            const struct blame_entry *src)
1381{
1382        struct blame_entry *e = xmalloc(sizeof(*e));
1383        memcpy(e, src, sizeof(*e));
1384        blame_origin_incref(e->suspect);
1385
1386        e->next = **queue;
1387        **queue = e;
1388        *queue = &e->next;
1389}
1390
1391/*
1392 * src typically is on-stack; we want to copy the information in it to
1393 * a malloced blame_entry that gets added to the given queue.  The
1394 * origin of dst loses a refcnt.
1395 */
1396static void dup_entry(struct blame_entry ***queue,
1397                      struct blame_entry *dst, struct blame_entry *src)
1398{
1399        blame_origin_incref(src->suspect);
1400        blame_origin_decref(dst->suspect);
1401        memcpy(dst, src, sizeof(*src));
1402        dst->next = **queue;
1403        **queue = dst;
1404        *queue = &dst->next;
1405}
1406
1407const char *blame_nth_line(struct blame_scoreboard *sb, long lno)
1408{
1409        return sb->final_buf + sb->lineno[lno];
1410}
1411
1412/*
1413 * It is known that lines between tlno to same came from parent, and e
1414 * has an overlap with that range.  it also is known that parent's
1415 * line plno corresponds to e's line tlno.
1416 *
1417 *                <---- e ----->
1418 *                   <------>
1419 *                   <------------>
1420 *             <------------>
1421 *             <------------------>
1422 *
1423 * Split e into potentially three parts; before this chunk, the chunk
1424 * to be blamed for the parent, and after that portion.
1425 */
1426static void split_overlap(struct blame_entry *split,
1427                          struct blame_entry *e,
1428                          int tlno, int plno, int same,
1429                          struct blame_origin *parent)
1430{
1431        int chunk_end_lno;
1432        int i;
1433        memset(split, 0, sizeof(struct blame_entry [3]));
1434
1435        for (i = 0; i < 3; i++) {
1436                split[i].ignored = e->ignored;
1437                split[i].unblamable = e->unblamable;
1438        }
1439
1440        if (e->s_lno < tlno) {
1441                /* there is a pre-chunk part not blamed on parent */
1442                split[0].suspect = blame_origin_incref(e->suspect);
1443                split[0].lno = e->lno;
1444                split[0].s_lno = e->s_lno;
1445                split[0].num_lines = tlno - e->s_lno;
1446                split[1].lno = e->lno + tlno - e->s_lno;
1447                split[1].s_lno = plno;
1448        }
1449        else {
1450                split[1].lno = e->lno;
1451                split[1].s_lno = plno + (e->s_lno - tlno);
1452        }
1453
1454        if (same < e->s_lno + e->num_lines) {
1455                /* there is a post-chunk part not blamed on parent */
1456                split[2].suspect = blame_origin_incref(e->suspect);
1457                split[2].lno = e->lno + (same - e->s_lno);
1458                split[2].s_lno = e->s_lno + (same - e->s_lno);
1459                split[2].num_lines = e->s_lno + e->num_lines - same;
1460                chunk_end_lno = split[2].lno;
1461        }
1462        else
1463                chunk_end_lno = e->lno + e->num_lines;
1464        split[1].num_lines = chunk_end_lno - split[1].lno;
1465
1466        /*
1467         * if it turns out there is nothing to blame the parent for,
1468         * forget about the splitting.  !split[1].suspect signals this.
1469         */
1470        if (split[1].num_lines < 1)
1471                return;
1472        split[1].suspect = blame_origin_incref(parent);
1473}
1474
1475/*
1476 * split_overlap() divided an existing blame e into up to three parts
1477 * in split.  Any assigned blame is moved to queue to
1478 * reflect the split.
1479 */
1480static void split_blame(struct blame_entry ***blamed,
1481                        struct blame_entry ***unblamed,
1482                        struct blame_entry *split,
1483                        struct blame_entry *e)
1484{
1485        if (split[0].suspect && split[2].suspect) {
1486                /* The first part (reuse storage for the existing entry e) */
1487                dup_entry(unblamed, e, &split[0]);
1488
1489                /* The last part -- me */
1490                add_blame_entry(unblamed, &split[2]);
1491
1492                /* ... and the middle part -- parent */
1493                add_blame_entry(blamed, &split[1]);
1494        }
1495        else if (!split[0].suspect && !split[2].suspect)
1496                /*
1497                 * The parent covers the entire area; reuse storage for
1498                 * e and replace it with the parent.
1499                 */
1500                dup_entry(blamed, e, &split[1]);
1501        else if (split[0].suspect) {
1502                /* me and then parent */
1503                dup_entry(unblamed, e, &split[0]);
1504                add_blame_entry(blamed, &split[1]);
1505        }
1506        else {
1507                /* parent and then me */
1508                dup_entry(blamed, e, &split[1]);
1509                add_blame_entry(unblamed, &split[2]);
1510        }
1511}
1512
1513/*
1514 * After splitting the blame, the origins used by the
1515 * on-stack blame_entry should lose one refcnt each.
1516 */
1517static void decref_split(struct blame_entry *split)
1518{
1519        int i;
1520
1521        for (i = 0; i < 3; i++)
1522                blame_origin_decref(split[i].suspect);
1523}
1524
1525/*
1526 * reverse_blame reverses the list given in head, appending tail.
1527 * That allows us to build lists in reverse order, then reverse them
1528 * afterwards.  This can be faster than building the list in proper
1529 * order right away.  The reason is that building in proper order
1530 * requires writing a link in the _previous_ element, while building
1531 * in reverse order just requires placing the list head into the
1532 * _current_ element.
1533 */
1534
1535static struct blame_entry *reverse_blame(struct blame_entry *head,
1536                                         struct blame_entry *tail)
1537{
1538        while (head) {
1539                struct blame_entry *next = head->next;
1540                head->next = tail;
1541                tail = head;
1542                head = next;
1543        }
1544        return tail;
1545}
1546
1547/*
1548 * Splits a blame entry into two entries at 'len' lines.  The original 'e'
1549 * consists of len lines, i.e. [e->lno, e->lno + len), and the second part,
1550 * which is returned, consists of the remainder: [e->lno + len, e->lno +
1551 * e->num_lines).  The caller needs to sort out the reference counting for the
1552 * new entry's suspect.
1553 */
1554static struct blame_entry *split_blame_at(struct blame_entry *e, int len,
1555                                          struct blame_origin *new_suspect)
1556{
1557        struct blame_entry *n = xcalloc(1, sizeof(struct blame_entry));
1558
1559        n->suspect = new_suspect;
1560        n->ignored = e->ignored;
1561        n->unblamable = e->unblamable;
1562        n->lno = e->lno + len;
1563        n->s_lno = e->s_lno + len;
1564        n->num_lines = e->num_lines - len;
1565        e->num_lines = len;
1566        e->score = 0;
1567        return n;
1568}
1569
1570struct blame_line_tracker {
1571        int is_parent;
1572        int s_lno;
1573};
1574
1575static int are_lines_adjacent(struct blame_line_tracker *first,
1576                              struct blame_line_tracker *second)
1577{
1578        return first->is_parent == second->is_parent &&
1579               first->s_lno + 1 == second->s_lno;
1580}
1581
1582static int scan_parent_range(struct fingerprint *p_fps,
1583                             struct fingerprint *t_fps, int t_idx,
1584                             int from, int nr_lines)
1585{
1586        int sim, p_idx;
1587        #define FINGERPRINT_FILE_THRESHOLD      10
1588        int best_sim_val = FINGERPRINT_FILE_THRESHOLD;
1589        int best_sim_idx = -1;
1590
1591        for (p_idx = from; p_idx < from + nr_lines; p_idx++) {
1592                sim = fingerprint_similarity(&t_fps[t_idx], &p_fps[p_idx]);
1593                if (sim < best_sim_val)
1594                        continue;
1595                /* Break ties with the closest-to-target line number */
1596                if (sim == best_sim_val && best_sim_idx != -1 &&
1597                    abs(best_sim_idx - t_idx) < abs(p_idx - t_idx))
1598                        continue;
1599                best_sim_val = sim;
1600                best_sim_idx = p_idx;
1601        }
1602        return best_sim_idx;
1603}
1604
1605/*
1606 * The first pass checks the blame entry (from the target) against the parent's
1607 * diff chunk.  If that fails for a line, the second pass tries to match that
1608 * line to any part of parent file.  That catches cases where a change was
1609 * broken into two chunks by 'context.'
1610 */
1611static void guess_line_blames(struct blame_origin *parent,
1612                              struct blame_origin *target,
1613                              int tlno, int offset, int same, int parent_len,
1614                              struct blame_line_tracker *line_blames)
1615{
1616        int i, best_idx, target_idx;
1617        int parent_slno = tlno + offset;
1618        int *fuzzy_matches;
1619
1620        fuzzy_matches = fuzzy_find_matching_lines(parent, target,
1621                                                  tlno, parent_slno, same,
1622                                                  parent_len);
1623        for (i = 0; i < same - tlno; i++) {
1624                target_idx = tlno + i;
1625                if (fuzzy_matches && fuzzy_matches[i] >= 0) {
1626                        best_idx = fuzzy_matches[i];
1627                } else {
1628                        best_idx = scan_parent_range(parent->fingerprints,
1629                                                     target->fingerprints,
1630                                                     target_idx, 0,
1631                                                     parent->num_lines);
1632                }
1633                if (best_idx >= 0) {
1634                        line_blames[i].is_parent = 1;
1635                        line_blames[i].s_lno = best_idx;
1636                } else {
1637                        line_blames[i].is_parent = 0;
1638                        line_blames[i].s_lno = target_idx;
1639                }
1640        }
1641        free(fuzzy_matches);
1642}
1643
1644/*
1645 * This decides which parts of a blame entry go to the parent (added to the
1646 * ignoredp list) and which stay with the target (added to the diffp list).  The
1647 * actual decision was made in a separate heuristic function, and those answers
1648 * for the lines in 'e' are in line_blames.  This consumes e, essentially
1649 * putting it on a list.
1650 *
1651 * Note that the blame entries on the ignoredp list are not necessarily sorted
1652 * with respect to the parent's line numbers yet.
1653 */
1654static void ignore_blame_entry(struct blame_entry *e,
1655                               struct blame_origin *parent,
1656                               struct blame_origin *target,
1657                               struct blame_entry **diffp,
1658                               struct blame_entry **ignoredp,
1659                               struct blame_line_tracker *line_blames)
1660{
1661        int entry_len, nr_lines, i;
1662
1663        /*
1664         * We carve new entries off the front of e.  Each entry comes from a
1665         * contiguous chunk of lines: adjacent lines from the same origin
1666         * (either the parent or the target).
1667         */
1668        entry_len = 1;
1669        nr_lines = e->num_lines;        /* e changes in the loop */
1670        for (i = 0; i < nr_lines; i++) {
1671                struct blame_entry *next = NULL;
1672
1673                /*
1674                 * We are often adjacent to the next line - only split the blame
1675                 * entry when we have to.
1676                 */
1677                if (i + 1 < nr_lines) {
1678                        if (are_lines_adjacent(&line_blames[i],
1679                                               &line_blames[i + 1])) {
1680                                entry_len++;
1681                                continue;
1682                        }
1683                        next = split_blame_at(e, entry_len,
1684                                              blame_origin_incref(e->suspect));
1685                }
1686                if (line_blames[i].is_parent) {
1687                        e->ignored = 1;
1688                        blame_origin_decref(e->suspect);
1689                        e->suspect = blame_origin_incref(parent);
1690                        e->s_lno = line_blames[i - entry_len + 1].s_lno;
1691                        e->next = *ignoredp;
1692                        *ignoredp = e;
1693                } else {
1694                        e->unblamable = 1;
1695                        /* e->s_lno is already in the target's address space. */
1696                        e->next = *diffp;
1697                        *diffp = e;
1698                }
1699                assert(e->num_lines == entry_len);
1700                e = next;
1701                entry_len = 1;
1702        }
1703        assert(!e);
1704}
1705
1706/*
1707 * Process one hunk from the patch between the current suspect for
1708 * blame_entry e and its parent.  This first blames any unfinished
1709 * entries before the chunk (which is where target and parent start
1710 * differing) on the parent, and then splits blame entries at the
1711 * start and at the end of the difference region.  Since use of -M and
1712 * -C options may lead to overlapping/duplicate source line number
1713 * ranges, all we can rely on from sorting/merging is the order of the
1714 * first suspect line number.
1715 *
1716 * tlno: line number in the target where this chunk begins
1717 * same: line number in the target where this chunk ends
1718 * offset: add to tlno to get the chunk starting point in the parent
1719 * parent_len: number of lines in the parent chunk
1720 */
1721static void blame_chunk(struct blame_entry ***dstq, struct blame_entry ***srcq,
1722                        int tlno, int offset, int same, int parent_len,
1723                        struct blame_origin *parent,
1724                        struct blame_origin *target, int ignore_diffs)
1725{
1726        struct blame_entry *e = **srcq;
1727        struct blame_entry *samep = NULL, *diffp = NULL, *ignoredp = NULL;
1728        struct blame_line_tracker *line_blames = NULL;
1729
1730        while (e && e->s_lno < tlno) {
1731                struct blame_entry *next = e->next;
1732                /*
1733                 * current record starts before differing portion.  If
1734                 * it reaches into it, we need to split it up and
1735                 * examine the second part separately.
1736                 */
1737                if (e->s_lno + e->num_lines > tlno) {
1738                        /* Move second half to a new record */
1739                        struct blame_entry *n;
1740
1741                        n = split_blame_at(e, tlno - e->s_lno, e->suspect);
1742                        /* Push new record to diffp */
1743                        n->next = diffp;
1744                        diffp = n;
1745                } else
1746                        blame_origin_decref(e->suspect);
1747                /* Pass blame for everything before the differing
1748                 * chunk to the parent */
1749                e->suspect = blame_origin_incref(parent);
1750                e->s_lno += offset;
1751                e->next = samep;
1752                samep = e;
1753                e = next;
1754        }
1755        /*
1756         * As we don't know how much of a common stretch after this
1757         * diff will occur, the currently blamed parts are all that we
1758         * can assign to the parent for now.
1759         */
1760
1761        if (samep) {
1762                **dstq = reverse_blame(samep, **dstq);
1763                *dstq = &samep->next;
1764        }
1765        /*
1766         * Prepend the split off portions: everything after e starts
1767         * after the blameable portion.
1768         */
1769        e = reverse_blame(diffp, e);
1770
1771        /*
1772         * Now retain records on the target while parts are different
1773         * from the parent.
1774         */
1775        samep = NULL;
1776        diffp = NULL;
1777
1778        if (ignore_diffs && same - tlno > 0) {
1779                line_blames = xcalloc(sizeof(struct blame_line_tracker),
1780                                      same - tlno);
1781                guess_line_blames(parent, target, tlno, offset, same,
1782                                  parent_len, line_blames);
1783        }
1784
1785        while (e && e->s_lno < same) {
1786                struct blame_entry *next = e->next;
1787
1788                /*
1789                 * If current record extends into sameness, need to split.
1790                 */
1791                if (e->s_lno + e->num_lines > same) {
1792                        /*
1793                         * Move second half to a new record to be
1794                         * processed by later chunks
1795                         */
1796                        struct blame_entry *n;
1797
1798                        n = split_blame_at(e, same - e->s_lno,
1799                                           blame_origin_incref(e->suspect));
1800                        /* Push new record to samep */
1801                        n->next = samep;
1802                        samep = n;
1803                }
1804                if (ignore_diffs) {
1805                        ignore_blame_entry(e, parent, target, &diffp, &ignoredp,
1806                                           line_blames + e->s_lno - tlno);
1807                } else {
1808                        e->next = diffp;
1809                        diffp = e;
1810                }
1811                e = next;
1812        }
1813        free(line_blames);
1814        if (ignoredp) {
1815                /*
1816                 * Note ignoredp is not sorted yet, and thus neither is dstq.
1817                 * That list must be sorted before we queue_blames().  We defer
1818                 * sorting until after all diff hunks are processed, so that
1819                 * guess_line_blames() can pick *any* line in the parent.  The
1820                 * slight drawback is that we end up sorting all blame entries
1821                 * passed to the parent, including those that are unrelated to
1822                 * changes made by the ignored commit.
1823                 */
1824                **dstq = reverse_blame(ignoredp, **dstq);
1825                *dstq = &ignoredp->next;
1826        }
1827        **srcq = reverse_blame(diffp, reverse_blame(samep, e));
1828        /* Move across elements that are in the unblamable portion */
1829        if (diffp)
1830                *srcq = &diffp->next;
1831}
1832
1833struct blame_chunk_cb_data {
1834        struct blame_origin *parent;
1835        struct blame_origin *target;
1836        long offset;
1837        int ignore_diffs;
1838        struct blame_entry **dstq;
1839        struct blame_entry **srcq;
1840};
1841
1842/* diff chunks are from parent to target */
1843static int blame_chunk_cb(long start_a, long count_a,
1844                          long start_b, long count_b, void *data)
1845{
1846        struct blame_chunk_cb_data *d = data;
1847        if (start_a - start_b != d->offset)
1848                die("internal error in blame::blame_chunk_cb");
1849        blame_chunk(&d->dstq, &d->srcq, start_b, start_a - start_b,
1850                    start_b + count_b, count_a, d->parent, d->target,
1851                    d->ignore_diffs);
1852        d->offset = start_a + count_a - (start_b + count_b);
1853        return 0;
1854}
1855
1856/*
1857 * We are looking at the origin 'target' and aiming to pass blame
1858 * for the lines it is suspected to its parent.  Run diff to find
1859 * which lines came from parent and pass blame for them.
1860 */
1861static void pass_blame_to_parent(struct blame_scoreboard *sb,
1862                                 struct blame_origin *target,
1863                                 struct blame_origin *parent, int ignore_diffs)
1864{
1865        mmfile_t file_p, file_o;
1866        struct blame_chunk_cb_data d;
1867        struct blame_entry *newdest = NULL;
1868
1869        if (!target->suspects)
1870                return; /* nothing remains for this target */
1871
1872        d.parent = parent;
1873        d.target = target;
1874        d.offset = 0;
1875        d.ignore_diffs = ignore_diffs;
1876        d.dstq = &newdest; d.srcq = &target->suspects;
1877
1878        fill_origin_blob(&sb->revs->diffopt, parent, &file_p,
1879                         &sb->num_read_blob, ignore_diffs);
1880        fill_origin_blob(&sb->revs->diffopt, target, &file_o,
1881                         &sb->num_read_blob, ignore_diffs);
1882        sb->num_get_patch++;
1883
1884        if (diff_hunks(&file_p, &file_o, blame_chunk_cb, &d, sb->xdl_opts))
1885                die("unable to generate diff (%s -> %s)",
1886                    oid_to_hex(&parent->commit->object.oid),
1887                    oid_to_hex(&target->commit->object.oid));
1888        /* The rest are the same as the parent */
1889        blame_chunk(&d.dstq, &d.srcq, INT_MAX, d.offset, INT_MAX, 0,
1890                    parent, target, 0);
1891        *d.dstq = NULL;
1892        if (ignore_diffs)
1893                newdest = llist_mergesort(newdest, get_next_blame,
1894                                          set_next_blame,
1895                                          compare_blame_suspect);
1896        queue_blames(sb, parent, newdest);
1897
1898        return;
1899}
1900
1901/*
1902 * The lines in blame_entry after splitting blames many times can become
1903 * very small and trivial, and at some point it becomes pointless to
1904 * blame the parents.  E.g. "\t\t}\n\t}\n\n" appears everywhere in any
1905 * ordinary C program, and it is not worth to say it was copied from
1906 * totally unrelated file in the parent.
1907 *
1908 * Compute how trivial the lines in the blame_entry are.
1909 */
1910unsigned blame_entry_score(struct blame_scoreboard *sb, struct blame_entry *e)
1911{
1912        unsigned score;
1913        const char *cp, *ep;
1914
1915        if (e->score)
1916                return e->score;
1917
1918        score = 1;
1919        cp = blame_nth_line(sb, e->lno);
1920        ep = blame_nth_line(sb, e->lno + e->num_lines);
1921        while (cp < ep) {
1922                unsigned ch = *((unsigned char *)cp);
1923                if (isalnum(ch))
1924                        score++;
1925                cp++;
1926        }
1927        e->score = score;
1928        return score;
1929}
1930
1931/*
1932 * best_so_far[] and potential[] are both a split of an existing blame_entry
1933 * that passes blame to the parent.  Maintain best_so_far the best split so
1934 * far, by comparing potential and best_so_far and copying potential into
1935 * bst_so_far as needed.
1936 */
1937static void copy_split_if_better(struct blame_scoreboard *sb,
1938                                 struct blame_entry *best_so_far,
1939                                 struct blame_entry *potential)
1940{
1941        int i;
1942
1943        if (!potential[1].suspect)
1944                return;
1945        if (best_so_far[1].suspect) {
1946                if (blame_entry_score(sb, &potential[1]) <
1947                    blame_entry_score(sb, &best_so_far[1]))
1948                        return;
1949        }
1950
1951        for (i = 0; i < 3; i++)
1952                blame_origin_incref(potential[i].suspect);
1953        decref_split(best_so_far);
1954        memcpy(best_so_far, potential, sizeof(struct blame_entry[3]));
1955}
1956
1957/*
1958 * We are looking at a part of the final image represented by
1959 * ent (tlno and same are offset by ent->s_lno).
1960 * tlno is where we are looking at in the final image.
1961 * up to (but not including) same match preimage.
1962 * plno is where we are looking at in the preimage.
1963 *
1964 * <-------------- final image ---------------------->
1965 *       <------ent------>
1966 *         ^tlno ^same
1967 *    <---------preimage----->
1968 *         ^plno
1969 *
1970 * All line numbers are 0-based.
1971 */
1972static void handle_split(struct blame_scoreboard *sb,
1973                         struct blame_entry *ent,
1974                         int tlno, int plno, int same,
1975                         struct blame_origin *parent,
1976                         struct blame_entry *split)
1977{
1978        if (ent->num_lines <= tlno)
1979                return;
1980        if (tlno < same) {
1981                struct blame_entry potential[3];
1982                tlno += ent->s_lno;
1983                same += ent->s_lno;
1984                split_overlap(potential, ent, tlno, plno, same, parent);
1985                copy_split_if_better(sb, split, potential);
1986                decref_split(potential);
1987        }
1988}
1989
1990struct handle_split_cb_data {
1991        struct blame_scoreboard *sb;
1992        struct blame_entry *ent;
1993        struct blame_origin *parent;
1994        struct blame_entry *split;
1995        long plno;
1996        long tlno;
1997};
1998
1999static int handle_split_cb(long start_a, long count_a,
2000                           long start_b, long count_b, void *data)
2001{
2002        struct handle_split_cb_data *d = data;
2003        handle_split(d->sb, d->ent, d->tlno, d->plno, start_b, d->parent,
2004                     d->split);
2005        d->plno = start_a + count_a;
2006        d->tlno = start_b + count_b;
2007        return 0;
2008}
2009
2010/*
2011 * Find the lines from parent that are the same as ent so that
2012 * we can pass blames to it.  file_p has the blob contents for
2013 * the parent.
2014 */
2015static void find_copy_in_blob(struct blame_scoreboard *sb,
2016                              struct blame_entry *ent,
2017                              struct blame_origin *parent,
2018                              struct blame_entry *split,
2019                              mmfile_t *file_p)
2020{
2021        const char *cp;
2022        mmfile_t file_o;
2023        struct handle_split_cb_data d;
2024
2025        memset(&d, 0, sizeof(d));
2026        d.sb = sb; d.ent = ent; d.parent = parent; d.split = split;
2027        /*
2028         * Prepare mmfile that contains only the lines in ent.
2029         */
2030        cp = blame_nth_line(sb, ent->lno);
2031        file_o.ptr = (char *) cp;
2032        file_o.size = blame_nth_line(sb, ent->lno + ent->num_lines) - cp;
2033
2034        /*
2035         * file_o is a part of final image we are annotating.
2036         * file_p partially may match that image.
2037         */
2038        memset(split, 0, sizeof(struct blame_entry [3]));
2039        if (diff_hunks(file_p, &file_o, handle_split_cb, &d, sb->xdl_opts))
2040                die("unable to generate diff (%s)",
2041                    oid_to_hex(&parent->commit->object.oid));
2042        /* remainder, if any, all match the preimage */
2043        handle_split(sb, ent, d.tlno, d.plno, ent->num_lines, parent, split);
2044}
2045
2046/* Move all blame entries from list *source that have a score smaller
2047 * than score_min to the front of list *small.
2048 * Returns a pointer to the link pointing to the old head of the small list.
2049 */
2050
2051static struct blame_entry **filter_small(struct blame_scoreboard *sb,
2052                                         struct blame_entry **small,
2053                                         struct blame_entry **source,
2054                                         unsigned score_min)
2055{
2056        struct blame_entry *p = *source;
2057        struct blame_entry *oldsmall = *small;
2058        while (p) {
2059                if (blame_entry_score(sb, p) <= score_min) {
2060                        *small = p;
2061                        small = &p->next;
2062                        p = *small;
2063                } else {
2064                        *source = p;
2065                        source = &p->next;
2066                        p = *source;
2067                }
2068        }
2069        *small = oldsmall;
2070        *source = NULL;
2071        return small;
2072}
2073
2074/*
2075 * See if lines currently target is suspected for can be attributed to
2076 * parent.
2077 */
2078static void find_move_in_parent(struct blame_scoreboard *sb,
2079                                struct blame_entry ***blamed,
2080                                struct blame_entry **toosmall,
2081                                struct blame_origin *target,
2082                                struct blame_origin *parent)
2083{
2084        struct blame_entry *e, split[3];
2085        struct blame_entry *unblamed = target->suspects;
2086        struct blame_entry *leftover = NULL;
2087        mmfile_t file_p;
2088
2089        if (!unblamed)
2090                return; /* nothing remains for this target */
2091
2092        fill_origin_blob(&sb->revs->diffopt, parent, &file_p,
2093                         &sb->num_read_blob, 0);
2094        if (!file_p.ptr)
2095                return;
2096
2097        /* At each iteration, unblamed has a NULL-terminated list of
2098         * entries that have not yet been tested for blame.  leftover
2099         * contains the reversed list of entries that have been tested
2100         * without being assignable to the parent.
2101         */
2102        do {
2103                struct blame_entry **unblamedtail = &unblamed;
2104                struct blame_entry *next;
2105                for (e = unblamed; e; e = next) {
2106                        next = e->next;
2107                        find_copy_in_blob(sb, e, parent, split, &file_p);
2108                        if (split[1].suspect &&
2109                            sb->move_score < blame_entry_score(sb, &split[1])) {
2110                                split_blame(blamed, &unblamedtail, split, e);
2111                        } else {
2112                                e->next = leftover;
2113                                leftover = e;
2114                        }
2115                        decref_split(split);
2116                }
2117                *unblamedtail = NULL;
2118                toosmall = filter_small(sb, toosmall, &unblamed, sb->move_score);
2119        } while (unblamed);
2120        target->suspects = reverse_blame(leftover, NULL);
2121}
2122
2123struct blame_list {
2124        struct blame_entry *ent;
2125        struct blame_entry split[3];
2126};
2127
2128/*
2129 * Count the number of entries the target is suspected for,
2130 * and prepare a list of entry and the best split.
2131 */
2132static struct blame_list *setup_blame_list(struct blame_entry *unblamed,
2133                                           int *num_ents_p)
2134{
2135        struct blame_entry *e;
2136        int num_ents, i;
2137        struct blame_list *blame_list = NULL;
2138
2139        for (e = unblamed, num_ents = 0; e; e = e->next)
2140                num_ents++;
2141        if (num_ents) {
2142                blame_list = xcalloc(num_ents, sizeof(struct blame_list));
2143                for (e = unblamed, i = 0; e; e = e->next)
2144                        blame_list[i++].ent = e;
2145        }
2146        *num_ents_p = num_ents;
2147        return blame_list;
2148}
2149
2150/*
2151 * For lines target is suspected for, see if we can find code movement
2152 * across file boundary from the parent commit.  porigin is the path
2153 * in the parent we already tried.
2154 */
2155static void find_copy_in_parent(struct blame_scoreboard *sb,
2156                                struct blame_entry ***blamed,
2157                                struct blame_entry **toosmall,
2158                                struct blame_origin *target,
2159                                struct commit *parent,
2160                                struct blame_origin *porigin,
2161                                int opt)
2162{
2163        struct diff_options diff_opts;
2164        int i, j;
2165        struct blame_list *blame_list;
2166        int num_ents;
2167        struct blame_entry *unblamed = target->suspects;
2168        struct blame_entry *leftover = NULL;
2169
2170        if (!unblamed)
2171                return; /* nothing remains for this target */
2172
2173        repo_diff_setup(sb->repo, &diff_opts);
2174        diff_opts.flags.recursive = 1;
2175        diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;
2176
2177        diff_setup_done(&diff_opts);
2178
2179        /* Try "find copies harder" on new path if requested;
2180         * we do not want to use diffcore_rename() actually to
2181         * match things up; find_copies_harder is set only to
2182         * force diff_tree_oid() to feed all filepairs to diff_queue,
2183         * and this code needs to be after diff_setup_done(), which
2184         * usually makes find-copies-harder imply copy detection.
2185         */
2186        if ((opt & PICKAXE_BLAME_COPY_HARDEST)
2187            || ((opt & PICKAXE_BLAME_COPY_HARDER)
2188                && (!porigin || strcmp(target->path, porigin->path))))
2189                diff_opts.flags.find_copies_harder = 1;
2190
2191        if (is_null_oid(&target->commit->object.oid))
2192                do_diff_cache(get_commit_tree_oid(parent), &diff_opts);
2193        else
2194                diff_tree_oid(get_commit_tree_oid(parent),
2195                              get_commit_tree_oid(target->commit),
2196                              "", &diff_opts);
2197
2198        if (!diff_opts.flags.find_copies_harder)
2199                diffcore_std(&diff_opts);
2200
2201        do {
2202                struct blame_entry **unblamedtail = &unblamed;
2203                blame_list = setup_blame_list(unblamed, &num_ents);
2204
2205                for (i = 0; i < diff_queued_diff.nr; i++) {
2206                        struct diff_filepair *p = diff_queued_diff.queue[i];
2207                        struct blame_origin *norigin;
2208                        mmfile_t file_p;
2209                        struct blame_entry potential[3];
2210
2211                        if (!DIFF_FILE_VALID(p->one))
2212                                continue; /* does not exist in parent */
2213                        if (S_ISGITLINK(p->one->mode))
2214                                continue; /* ignore git links */
2215                        if (porigin && !strcmp(p->one->path, porigin->path))
2216                                /* find_move already dealt with this path */
2217                                continue;
2218
2219                        norigin = get_origin(parent, p->one->path);
2220                        oidcpy(&norigin->blob_oid, &p->one->oid);
2221                        norigin->mode = p->one->mode;
2222                        fill_origin_blob(&sb->revs->diffopt, norigin, &file_p,
2223                                         &sb->num_read_blob, 0);
2224                        if (!file_p.ptr)
2225                                continue;
2226
2227                        for (j = 0; j < num_ents; j++) {
2228                                find_copy_in_blob(sb, blame_list[j].ent,
2229                                                  norigin, potential, &file_p);
2230                                copy_split_if_better(sb, blame_list[j].split,
2231                                                     potential);
2232                                decref_split(potential);
2233                        }
2234                        blame_origin_decref(norigin);
2235                }
2236
2237                for (j = 0; j < num_ents; j++) {
2238                        struct blame_entry *split = blame_list[j].split;
2239                        if (split[1].suspect &&
2240                            sb->copy_score < blame_entry_score(sb, &split[1])) {
2241                                split_blame(blamed, &unblamedtail, split,
2242                                            blame_list[j].ent);
2243                        } else {
2244                                blame_list[j].ent->next = leftover;
2245                                leftover = blame_list[j].ent;
2246                        }
2247                        decref_split(split);
2248                }
2249                free(blame_list);
2250                *unblamedtail = NULL;
2251                toosmall = filter_small(sb, toosmall, &unblamed, sb->copy_score);
2252        } while (unblamed);
2253        target->suspects = reverse_blame(leftover, NULL);
2254        diff_flush(&diff_opts);
2255        clear_pathspec(&diff_opts.pathspec);
2256}
2257
2258/*
2259 * The blobs of origin and porigin exactly match, so everything
2260 * origin is suspected for can be blamed on the parent.
2261 */
2262static void pass_whole_blame(struct blame_scoreboard *sb,
2263                             struct blame_origin *origin, struct blame_origin *porigin)
2264{
2265        struct blame_entry *e, *suspects;
2266
2267        if (!porigin->file.ptr && origin->file.ptr) {
2268                /* Steal its file */
2269                porigin->file = origin->file;
2270                origin->file.ptr = NULL;
2271        }
2272        suspects = origin->suspects;
2273        origin->suspects = NULL;
2274        for (e = suspects; e; e = e->next) {
2275                blame_origin_incref(porigin);
2276                blame_origin_decref(e->suspect);
2277                e->suspect = porigin;
2278        }
2279        queue_blames(sb, porigin, suspects);
2280}
2281
2282/*
2283 * We pass blame from the current commit to its parents.  We keep saying
2284 * "parent" (and "porigin"), but what we mean is to find scapegoat to
2285 * exonerate ourselves.
2286 */
2287static struct commit_list *first_scapegoat(struct rev_info *revs, struct commit *commit,
2288                                        int reverse)
2289{
2290        if (!reverse) {
2291                if (revs->first_parent_only &&
2292                    commit->parents &&
2293                    commit->parents->next) {
2294                        free_commit_list(commit->parents->next);
2295                        commit->parents->next = NULL;
2296                }
2297                return commit->parents;
2298        }
2299        return lookup_decoration(&revs->children, &commit->object);
2300}
2301
2302static int num_scapegoats(struct rev_info *revs, struct commit *commit, int reverse)
2303{
2304        struct commit_list *l = first_scapegoat(revs, commit, reverse);
2305        return commit_list_count(l);
2306}
2307
2308/* Distribute collected unsorted blames to the respected sorted lists
2309 * in the various origins.
2310 */
2311static void distribute_blame(struct blame_scoreboard *sb, struct blame_entry *blamed)
2312{
2313        blamed = llist_mergesort(blamed, get_next_blame, set_next_blame,
2314                                 compare_blame_suspect);
2315        while (blamed)
2316        {
2317                struct blame_origin *porigin = blamed->suspect;
2318                struct blame_entry *suspects = NULL;
2319                do {
2320                        struct blame_entry *next = blamed->next;
2321                        blamed->next = suspects;
2322                        suspects = blamed;
2323                        blamed = next;
2324                } while (blamed && blamed->suspect == porigin);
2325                suspects = reverse_blame(suspects, NULL);
2326                queue_blames(sb, porigin, suspects);
2327        }
2328}
2329
2330#define MAXSG 16
2331
2332static void pass_blame(struct blame_scoreboard *sb, struct blame_origin *origin, int opt)
2333{
2334        struct rev_info *revs = sb->revs;
2335        int i, pass, num_sg;
2336        struct commit *commit = origin->commit;
2337        struct commit_list *sg;
2338        struct blame_origin *sg_buf[MAXSG];
2339        struct blame_origin *porigin, **sg_origin = sg_buf;
2340        struct blame_entry *toosmall = NULL;
2341        struct blame_entry *blames, **blametail = &blames;
2342
2343        num_sg = num_scapegoats(revs, commit, sb->reverse);
2344        if (!num_sg)
2345                goto finish;
2346        else if (num_sg < ARRAY_SIZE(sg_buf))
2347                memset(sg_buf, 0, sizeof(sg_buf));
2348        else
2349                sg_origin = xcalloc(num_sg, sizeof(*sg_origin));
2350
2351        /*
2352         * The first pass looks for unrenamed path to optimize for
2353         * common cases, then we look for renames in the second pass.
2354         */
2355        for (pass = 0; pass < 2 - sb->no_whole_file_rename; pass++) {
2356                struct blame_origin *(*find)(struct repository *, struct commit *, struct blame_origin *);
2357                find = pass ? find_rename : find_origin;
2358
2359                for (i = 0, sg = first_scapegoat(revs, commit, sb->reverse);
2360                     i < num_sg && sg;
2361                     sg = sg->next, i++) {
2362                        struct commit *p = sg->item;
2363                        int j, same;
2364
2365                        if (sg_origin[i])
2366                                continue;
2367                        if (parse_commit(p))
2368                                continue;
2369                        porigin = find(sb->repo, p, origin);
2370                        if (!porigin)
2371                                continue;
2372                        if (oideq(&porigin->blob_oid, &origin->blob_oid)) {
2373                                pass_whole_blame(sb, origin, porigin);
2374                                blame_origin_decref(porigin);
2375                                goto finish;
2376                        }
2377                        for (j = same = 0; j < i; j++)
2378                                if (sg_origin[j] &&
2379                                    oideq(&sg_origin[j]->blob_oid, &porigin->blob_oid)) {
2380                                        same = 1;
2381                                        break;
2382                                }
2383                        if (!same)
2384                                sg_origin[i] = porigin;
2385                        else
2386                                blame_origin_decref(porigin);
2387                }
2388        }
2389
2390        sb->num_commits++;
2391        for (i = 0, sg = first_scapegoat(revs, commit, sb->reverse);
2392             i < num_sg && sg;
2393             sg = sg->next, i++) {
2394                struct blame_origin *porigin = sg_origin[i];
2395                if (!porigin)
2396                        continue;
2397                if (!origin->previous) {
2398                        blame_origin_incref(porigin);
2399                        origin->previous = porigin;
2400                }
2401                pass_blame_to_parent(sb, origin, porigin, 0);
2402                if (!origin->suspects)
2403                        goto finish;
2404        }
2405
2406        /*
2407         * Pass remaining suspects for ignored commits to their parents.
2408         */
2409        if (oidset_contains(&sb->ignore_list, &commit->object.oid)) {
2410                for (i = 0, sg = first_scapegoat(revs, commit, sb->reverse);
2411                     i < num_sg && sg;
2412                     sg = sg->next, i++) {
2413                        struct blame_origin *porigin = sg_origin[i];
2414
2415                        if (!porigin)
2416                                continue;
2417                        pass_blame_to_parent(sb, origin, porigin, 1);
2418                        /*
2419                         * Preemptively drop porigin so we can refresh the
2420                         * fingerprints if we use the parent again, which can
2421                         * occur if you ignore back-to-back commits.
2422                         */
2423                        drop_origin_blob(porigin);
2424                        if (!origin->suspects)
2425                                goto finish;
2426                }
2427        }
2428
2429        /*
2430         * Optionally find moves in parents' files.
2431         */
2432        if (opt & PICKAXE_BLAME_MOVE) {
2433                filter_small(sb, &toosmall, &origin->suspects, sb->move_score);
2434                if (origin->suspects) {
2435                        for (i = 0, sg = first_scapegoat(revs, commit, sb->reverse);
2436                             i < num_sg && sg;
2437                             sg = sg->next, i++) {
2438                                struct blame_origin *porigin = sg_origin[i];
2439                                if (!porigin)
2440                                        continue;
2441                                find_move_in_parent(sb, &blametail, &toosmall, origin, porigin);
2442                                if (!origin->suspects)
2443                                        break;
2444                        }
2445                }
2446        }
2447
2448        /*
2449         * Optionally find copies from parents' files.
2450         */
2451        if (opt & PICKAXE_BLAME_COPY) {
2452                if (sb->copy_score > sb->move_score)
2453                        filter_small(sb, &toosmall, &origin->suspects, sb->copy_score);
2454                else if (sb->copy_score < sb->move_score) {
2455                        origin->suspects = blame_merge(origin->suspects, toosmall);
2456                        toosmall = NULL;
2457                        filter_small(sb, &toosmall, &origin->suspects, sb->copy_score);
2458                }
2459                if (!origin->suspects)
2460                        goto finish;
2461
2462                for (i = 0, sg = first_scapegoat(revs, commit, sb->reverse);
2463                     i < num_sg && sg;
2464                     sg = sg->next, i++) {
2465                        struct blame_origin *porigin = sg_origin[i];
2466                        find_copy_in_parent(sb, &blametail, &toosmall,
2467                                            origin, sg->item, porigin, opt);
2468                        if (!origin->suspects)
2469                                goto finish;
2470                }
2471        }
2472
2473finish:
2474        *blametail = NULL;
2475        distribute_blame(sb, blames);
2476        /*
2477         * prepend toosmall to origin->suspects
2478         *
2479         * There is no point in sorting: this ends up on a big
2480         * unsorted list in the caller anyway.
2481         */
2482        if (toosmall) {
2483                struct blame_entry **tail = &toosmall;
2484                while (*tail)
2485                        tail = &(*tail)->next;
2486                *tail = origin->suspects;
2487                origin->suspects = toosmall;
2488        }
2489        for (i = 0; i < num_sg; i++) {
2490                if (sg_origin[i]) {
2491                        drop_origin_blob(sg_origin[i]);
2492                        blame_origin_decref(sg_origin[i]);
2493                }
2494        }
2495        drop_origin_blob(origin);
2496        if (sg_buf != sg_origin)
2497                free(sg_origin);
2498}
2499
2500/*
2501 * The main loop -- while we have blobs with lines whose true origin
2502 * is still unknown, pick one blob, and allow its lines to pass blames
2503 * to its parents. */
2504void assign_blame(struct blame_scoreboard *sb, int opt)
2505{
2506        struct rev_info *revs = sb->revs;
2507        struct commit *commit = prio_queue_get(&sb->commits);
2508
2509        while (commit) {
2510                struct blame_entry *ent;
2511                struct blame_origin *suspect = get_blame_suspects(commit);
2512
2513                /* find one suspect to break down */
2514                while (suspect && !suspect->suspects)
2515                        suspect = suspect->next;
2516
2517                if (!suspect) {
2518                        commit = prio_queue_get(&sb->commits);
2519                        continue;
2520                }
2521
2522                assert(commit == suspect->commit);
2523
2524                /*
2525                 * We will use this suspect later in the loop,
2526                 * so hold onto it in the meantime.
2527                 */
2528                blame_origin_incref(suspect);
2529                parse_commit(commit);
2530                if (sb->reverse ||
2531                    (!(commit->object.flags & UNINTERESTING) &&
2532                     !(revs->max_age != -1 && commit->date < revs->max_age)))
2533                        pass_blame(sb, suspect, opt);
2534                else {
2535                        commit->object.flags |= UNINTERESTING;
2536                        if (commit->object.parsed)
2537                                mark_parents_uninteresting(commit);
2538                }
2539                /* treat root commit as boundary */
2540                if (!commit->parents && !sb->show_root)
2541                        commit->object.flags |= UNINTERESTING;
2542
2543                /* Take responsibility for the remaining entries */
2544                ent = suspect->suspects;
2545                if (ent) {
2546                        suspect->guilty = 1;
2547                        for (;;) {
2548                                struct blame_entry *next = ent->next;
2549                                if (sb->found_guilty_entry)
2550                                        sb->found_guilty_entry(ent, sb->found_guilty_entry_data);
2551                                if (next) {
2552                                        ent = next;
2553                                        continue;
2554                                }
2555                                ent->next = sb->ent;
2556                                sb->ent = suspect->suspects;
2557                                suspect->suspects = NULL;
2558                                break;
2559                        }
2560                }
2561                blame_origin_decref(suspect);
2562
2563                if (sb->debug) /* sanity */
2564                        sanity_check_refcnt(sb);
2565        }
2566}
2567
2568/*
2569 * To allow quick access to the contents of nth line in the
2570 * final image, prepare an index in the scoreboard.
2571 */
2572static int prepare_lines(struct blame_scoreboard *sb)
2573{
2574        sb->num_lines = find_line_starts(&sb->lineno, sb->final_buf,
2575                                         sb->final_buf_size);
2576        return sb->num_lines;
2577}
2578
2579static struct commit *find_single_final(struct rev_info *revs,
2580                                        const char **name_p)
2581{
2582        int i;
2583        struct commit *found = NULL;
2584        const char *name = NULL;
2585
2586        for (i = 0; i < revs->pending.nr; i++) {
2587                struct object *obj = revs->pending.objects[i].item;
2588                if (obj->flags & UNINTERESTING)
2589                        continue;
2590                obj = deref_tag(revs->repo, obj, NULL, 0);
2591                if (obj->type != OBJ_COMMIT)
2592                        die("Non commit %s?", revs->pending.objects[i].name);
2593                if (found)
2594                        die("More than one commit to dig from %s and %s?",
2595                            revs->pending.objects[i].name, name);
2596                found = (struct commit *)obj;
2597                name = revs->pending.objects[i].name;
2598        }
2599        if (name_p)
2600                *name_p = xstrdup_or_null(name);
2601        return found;
2602}
2603
2604static struct commit *dwim_reverse_initial(struct rev_info *revs,
2605                                           const char **name_p)
2606{
2607        /*
2608         * DWIM "git blame --reverse ONE -- PATH" as
2609         * "git blame --reverse ONE..HEAD -- PATH" but only do so
2610         * when it makes sense.
2611         */
2612        struct object *obj;
2613        struct commit *head_commit;
2614        struct object_id head_oid;
2615
2616        if (revs->pending.nr != 1)
2617                return NULL;
2618
2619        /* Is that sole rev a committish? */
2620        obj = revs->pending.objects[0].item;
2621        obj = deref_tag(revs->repo, obj, NULL, 0);
2622        if (obj->type != OBJ_COMMIT)
2623                return NULL;
2624
2625        /* Do we have HEAD? */
2626        if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, &head_oid, NULL))
2627                return NULL;
2628        head_commit = lookup_commit_reference_gently(revs->repo,
2629                                                     &head_oid, 1);
2630        if (!head_commit)
2631                return NULL;
2632
2633        /* Turn "ONE" into "ONE..HEAD" then */
2634        obj->flags |= UNINTERESTING;
2635        add_pending_object(revs, &head_commit->object, "HEAD");
2636
2637        if (name_p)
2638                *name_p = revs->pending.objects[0].name;
2639        return (struct commit *)obj;
2640}
2641
2642static struct commit *find_single_initial(struct rev_info *revs,
2643                                          const char **name_p)
2644{
2645        int i;
2646        struct commit *found = NULL;
2647        const char *name = NULL;
2648
2649        /*
2650         * There must be one and only one negative commit, and it must be
2651         * the boundary.
2652         */
2653        for (i = 0; i < revs->pending.nr; i++) {
2654                struct object *obj = revs->pending.objects[i].item;
2655                if (!(obj->flags & UNINTERESTING))
2656                        continue;
2657                obj = deref_tag(revs->repo, obj, NULL, 0);
2658                if (obj->type != OBJ_COMMIT)
2659                        die("Non commit %s?", revs->pending.objects[i].name);
2660                if (found)
2661                        die("More than one commit to dig up from, %s and %s?",
2662                            revs->pending.objects[i].name, name);
2663                found = (struct commit *) obj;
2664                name = revs->pending.objects[i].name;
2665        }
2666
2667        if (!name)
2668                found = dwim_reverse_initial(revs, &name);
2669        if (!name)
2670                die("No commit to dig up from?");
2671
2672        if (name_p)
2673                *name_p = xstrdup(name);
2674        return found;
2675}
2676
2677void init_scoreboard(struct blame_scoreboard *sb)
2678{
2679        memset(sb, 0, sizeof(struct blame_scoreboard));
2680        sb->move_score = BLAME_DEFAULT_MOVE_SCORE;
2681        sb->copy_score = BLAME_DEFAULT_COPY_SCORE;
2682}
2683
2684void setup_scoreboard(struct blame_scoreboard *sb,
2685                      const char *path,
2686                      struct blame_origin **orig)
2687{
2688        const char *final_commit_name = NULL;
2689        struct blame_origin *o;
2690        struct commit *final_commit = NULL;
2691        enum object_type type;
2692
2693        init_blame_suspects(&blame_suspects);
2694
2695        if (sb->reverse && sb->contents_from)
2696                die(_("--contents and --reverse do not blend well."));
2697
2698        if (!sb->repo)
2699                BUG("repo is NULL");
2700
2701        if (!sb->reverse) {
2702                sb->final = find_single_final(sb->revs, &final_commit_name);
2703                sb->commits.compare = compare_commits_by_commit_date;
2704        } else {
2705                sb->final = find_single_initial(sb->revs, &final_commit_name);
2706                sb->commits.compare = compare_commits_by_reverse_commit_date;
2707        }
2708
2709        if (sb->final && sb->contents_from)
2710                die(_("cannot use --contents with final commit object name"));
2711
2712        if (sb->reverse && sb->revs->first_parent_only)
2713                sb->revs->children.name = NULL;
2714
2715        if (!sb->final) {
2716                /*
2717                 * "--not A B -- path" without anything positive;
2718                 * do not default to HEAD, but use the working tree
2719                 * or "--contents".
2720                 */
2721                setup_work_tree();
2722                sb->final = fake_working_tree_commit(sb->repo,
2723                                                     &sb->revs->diffopt,
2724                                                     path, sb->contents_from);
2725                add_pending_object(sb->revs, &(sb->final->object), ":");
2726        }
2727
2728        if (sb->reverse && sb->revs->first_parent_only) {
2729                final_commit = find_single_final(sb->revs, NULL);
2730                if (!final_commit)
2731                        die(_("--reverse and --first-parent together require specified latest commit"));
2732        }
2733
2734        /*
2735         * If we have bottom, this will mark the ancestors of the
2736         * bottom commits we would reach while traversing as
2737         * uninteresting.
2738         */
2739        if (prepare_revision_walk(sb->revs))
2740                die(_("revision walk setup failed"));
2741
2742        if (sb->reverse && sb->revs->first_parent_only) {
2743                struct commit *c = final_commit;
2744
2745                sb->revs->children.name = "children";
2746                while (c->parents &&
2747                       !oideq(&c->object.oid, &sb->final->object.oid)) {
2748                        struct commit_list *l = xcalloc(1, sizeof(*l));
2749
2750                        l->item = c;
2751                        if (add_decoration(&sb->revs->children,
2752                                           &c->parents->item->object, l))
2753                                BUG("not unique item in first-parent chain");
2754                        c = c->parents->item;
2755                }
2756
2757                if (!oideq(&c->object.oid, &sb->final->object.oid))
2758                        die(_("--reverse --first-parent together require range along first-parent chain"));
2759        }
2760
2761        if (is_null_oid(&sb->final->object.oid)) {
2762                o = get_blame_suspects(sb->final);
2763                sb->final_buf = xmemdupz(o->file.ptr, o->file.size);
2764                sb->final_buf_size = o->file.size;
2765        }
2766        else {
2767                o = get_origin(sb->final, path);
2768                if (fill_blob_sha1_and_mode(sb->repo, o))
2769                        die(_("no such path %s in %s"), path, final_commit_name);
2770
2771                if (sb->revs->diffopt.flags.allow_textconv &&
2772                    textconv_object(sb->repo, path, o->mode, &o->blob_oid, 1, (char **) &sb->final_buf,
2773                                    &sb->final_buf_size))
2774                        ;
2775                else
2776                        sb->final_buf = read_object_file(&o->blob_oid, &type,
2777                                                         &sb->final_buf_size);
2778
2779                if (!sb->final_buf)
2780                        die(_("cannot read blob %s for path %s"),
2781                            oid_to_hex(&o->blob_oid),
2782                            path);
2783        }
2784        sb->num_read_blob++;
2785        prepare_lines(sb);
2786
2787        if (orig)
2788                *orig = o;
2789
2790        free((char *)final_commit_name);
2791}
2792
2793
2794
2795struct blame_entry *blame_entry_prepend(struct blame_entry *head,
2796                                        long start, long end,
2797                                        struct blame_origin *o)
2798{
2799        struct blame_entry *new_head = xcalloc(1, sizeof(struct blame_entry));
2800        new_head->lno = start;
2801        new_head->num_lines = end - start;
2802        new_head->suspect = o;
2803        new_head->s_lno = start;
2804        new_head->next = head;
2805        blame_origin_incref(o);
2806        return new_head;
2807}