blame.con commit t3311: use test_commit_bulk (737b19b)
   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 short 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        repo_read_index(r);
 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",
 208                        WANT_BLANK_IDENT, NULL, 0);
 209        strbuf_addstr(&msg, "tree 0000000000000000000000000000000000000000\n");
 210        for (parent = commit->parents; parent; parent = parent->next)
 211                strbuf_addf(&msg, "parent %s\n",
 212                            oid_to_hex(&parent->item->object.oid));
 213        strbuf_addf(&msg,
 214                    "author %s\n"
 215                    "committer %s\n\n"
 216                    "Version of %s from %s\n",
 217                    ident, ident, path,
 218                    (!contents_from ? path :
 219                     (!strcmp(contents_from, "-") ? "standard input" : contents_from)));
 220        set_commit_buffer_from_strbuf(r, commit, &msg);
 221
 222        if (!contents_from || strcmp("-", contents_from)) {
 223                struct stat st;
 224                const char *read_from;
 225                char *buf_ptr;
 226                unsigned long buf_len;
 227
 228                if (contents_from) {
 229                        if (stat(contents_from, &st) < 0)
 230                                die_errno("Cannot stat '%s'", contents_from);
 231                        read_from = contents_from;
 232                }
 233                else {
 234                        if (lstat(path, &st) < 0)
 235                                die_errno("Cannot lstat '%s'", path);
 236                        read_from = path;
 237                }
 238                mode = canon_mode(st.st_mode);
 239
 240                switch (st.st_mode & S_IFMT) {
 241                case S_IFREG:
 242                        if (opt->flags.allow_textconv &&
 243                            textconv_object(r, read_from, mode, &null_oid, 0, &buf_ptr, &buf_len))
 244                                strbuf_attach(&buf, buf_ptr, buf_len, buf_len + 1);
 245                        else if (strbuf_read_file(&buf, read_from, st.st_size) != st.st_size)
 246                                die_errno("cannot open or read '%s'", read_from);
 247                        break;
 248                case S_IFLNK:
 249                        if (strbuf_readlink(&buf, read_from, st.st_size) < 0)
 250                                die_errno("cannot readlink '%s'", read_from);
 251                        break;
 252                default:
 253                        die("unsupported file type %s", read_from);
 254                }
 255        }
 256        else {
 257                /* Reading from stdin */
 258                mode = 0;
 259                if (strbuf_read(&buf, 0, 0) < 0)
 260                        die_errno("failed to read from stdin");
 261        }
 262        convert_to_git(r->index, path, buf.buf, buf.len, &buf, 0);
 263        origin->file.ptr = buf.buf;
 264        origin->file.size = buf.len;
 265        pretend_object_file(buf.buf, buf.len, OBJ_BLOB, &origin->blob_oid);
 266
 267        /*
 268         * Read the current index, replace the path entry with
 269         * origin->blob_sha1 without mucking with its mode or type
 270         * bits; we are not going to write this index out -- we just
 271         * want to run "diff-index --cached".
 272         */
 273        discard_index(r->index);
 274        repo_read_index(r);
 275
 276        len = strlen(path);
 277        if (!mode) {
 278                int pos = index_name_pos(r->index, path, len);
 279                if (0 <= pos)
 280                        mode = r->index->cache[pos]->ce_mode;
 281                else
 282                        /* Let's not bother reading from HEAD tree */
 283                        mode = S_IFREG | 0644;
 284        }
 285        ce = make_empty_cache_entry(r->index, len);
 286        oidcpy(&ce->oid, &origin->blob_oid);
 287        memcpy(ce->name, path, len);
 288        ce->ce_flags = create_ce_flags(0);
 289        ce->ce_namelen = len;
 290        ce->ce_mode = create_ce_mode(mode);
 291        add_index_entry(r->index, ce,
 292                        ADD_CACHE_OK_TO_ADD | ADD_CACHE_OK_TO_REPLACE);
 293
 294        cache_tree_invalidate_path(r->index, path);
 295
 296        return commit;
 297}
 298
 299
 300
 301static int diff_hunks(mmfile_t *file_a, mmfile_t *file_b,
 302                      xdl_emit_hunk_consume_func_t hunk_func, void *cb_data, int xdl_opts)
 303{
 304        xpparam_t xpp = {0};
 305        xdemitconf_t xecfg = {0};
 306        xdemitcb_t ecb = {NULL};
 307
 308        xpp.flags = xdl_opts;
 309        xecfg.hunk_func = hunk_func;
 310        ecb.priv = cb_data;
 311        return xdi_diff(file_a, file_b, &xpp, &xecfg, &ecb);
 312}
 313
 314/*
 315 * Given an origin, prepare mmfile_t structure to be used by the
 316 * diff machinery
 317 */
 318static void fill_origin_blob(struct diff_options *opt,
 319                             struct blame_origin *o, mmfile_t *file, int *num_read_blob)
 320{
 321        if (!o->file.ptr) {
 322                enum object_type type;
 323                unsigned long file_size;
 324
 325                (*num_read_blob)++;
 326                if (opt->flags.allow_textconv &&
 327                    textconv_object(opt->repo, o->path, o->mode,
 328                                    &o->blob_oid, 1, &file->ptr, &file_size))
 329                        ;
 330                else
 331                        file->ptr = read_object_file(&o->blob_oid, &type,
 332                                                     &file_size);
 333                file->size = file_size;
 334
 335                if (!file->ptr)
 336                        die("Cannot read blob %s for path %s",
 337                            oid_to_hex(&o->blob_oid),
 338                            o->path);
 339                o->file = *file;
 340        }
 341        else
 342                *file = o->file;
 343}
 344
 345static void drop_origin_blob(struct blame_origin *o)
 346{
 347        FREE_AND_NULL(o->file.ptr);
 348}
 349
 350/*
 351 * Any merge of blames happens on lists of blames that arrived via
 352 * different parents in a single suspect.  In this case, we want to
 353 * sort according to the suspect line numbers as opposed to the final
 354 * image line numbers.  The function body is somewhat longish because
 355 * it avoids unnecessary writes.
 356 */
 357
 358static struct blame_entry *blame_merge(struct blame_entry *list1,
 359                                       struct blame_entry *list2)
 360{
 361        struct blame_entry *p1 = list1, *p2 = list2,
 362                **tail = &list1;
 363
 364        if (!p1)
 365                return p2;
 366        if (!p2)
 367                return p1;
 368
 369        if (p1->s_lno <= p2->s_lno) {
 370                do {
 371                        tail = &p1->next;
 372                        if ((p1 = *tail) == NULL) {
 373                                *tail = p2;
 374                                return list1;
 375                        }
 376                } while (p1->s_lno <= p2->s_lno);
 377        }
 378        for (;;) {
 379                *tail = p2;
 380                do {
 381                        tail = &p2->next;
 382                        if ((p2 = *tail) == NULL)  {
 383                                *tail = p1;
 384                                return list1;
 385                        }
 386                } while (p1->s_lno > p2->s_lno);
 387                *tail = p1;
 388                do {
 389                        tail = &p1->next;
 390                        if ((p1 = *tail) == NULL) {
 391                                *tail = p2;
 392                                return list1;
 393                        }
 394                } while (p1->s_lno <= p2->s_lno);
 395        }
 396}
 397
 398static void *get_next_blame(const void *p)
 399{
 400        return ((struct blame_entry *)p)->next;
 401}
 402
 403static void set_next_blame(void *p1, void *p2)
 404{
 405        ((struct blame_entry *)p1)->next = p2;
 406}
 407
 408/*
 409 * Final image line numbers are all different, so we don't need a
 410 * three-way comparison here.
 411 */
 412
 413static int compare_blame_final(const void *p1, const void *p2)
 414{
 415        return ((struct blame_entry *)p1)->lno > ((struct blame_entry *)p2)->lno
 416                ? 1 : -1;
 417}
 418
 419static int compare_blame_suspect(const void *p1, const void *p2)
 420{
 421        const struct blame_entry *s1 = p1, *s2 = p2;
 422        /*
 423         * to allow for collating suspects, we sort according to the
 424         * respective pointer value as the primary sorting criterion.
 425         * The actual relation is pretty unimportant as long as it
 426         * establishes a total order.  Comparing as integers gives us
 427         * that.
 428         */
 429        if (s1->suspect != s2->suspect)
 430                return (intptr_t)s1->suspect > (intptr_t)s2->suspect ? 1 : -1;
 431        if (s1->s_lno == s2->s_lno)
 432                return 0;
 433        return s1->s_lno > s2->s_lno ? 1 : -1;
 434}
 435
 436void blame_sort_final(struct blame_scoreboard *sb)
 437{
 438        sb->ent = llist_mergesort(sb->ent, get_next_blame, set_next_blame,
 439                                  compare_blame_final);
 440}
 441
 442static int compare_commits_by_reverse_commit_date(const void *a,
 443                                                  const void *b,
 444                                                  void *c)
 445{
 446        return -compare_commits_by_commit_date(a, b, c);
 447}
 448
 449/*
 450 * For debugging -- origin is refcounted, and this asserts that
 451 * we do not underflow.
 452 */
 453static void sanity_check_refcnt(struct blame_scoreboard *sb)
 454{
 455        int baa = 0;
 456        struct blame_entry *ent;
 457
 458        for (ent = sb->ent; ent; ent = ent->next) {
 459                /* Nobody should have zero or negative refcnt */
 460                if (ent->suspect->refcnt <= 0) {
 461                        fprintf(stderr, "%s in %s has negative refcnt %d\n",
 462                                ent->suspect->path,
 463                                oid_to_hex(&ent->suspect->commit->object.oid),
 464                                ent->suspect->refcnt);
 465                        baa = 1;
 466                }
 467        }
 468        if (baa)
 469                sb->on_sanity_fail(sb, baa);
 470}
 471
 472/*
 473 * If two blame entries that are next to each other came from
 474 * contiguous lines in the same origin (i.e. <commit, path> pair),
 475 * merge them together.
 476 */
 477void blame_coalesce(struct blame_scoreboard *sb)
 478{
 479        struct blame_entry *ent, *next;
 480
 481        for (ent = sb->ent; ent && (next = ent->next); ent = next) {
 482                if (ent->suspect == next->suspect &&
 483                    ent->s_lno + ent->num_lines == next->s_lno) {
 484                        ent->num_lines += next->num_lines;
 485                        ent->next = next->next;
 486                        blame_origin_decref(next->suspect);
 487                        free(next);
 488                        ent->score = 0;
 489                        next = ent; /* again */
 490                }
 491        }
 492
 493        if (sb->debug) /* sanity */
 494                sanity_check_refcnt(sb);
 495}
 496
 497/*
 498 * Merge the given sorted list of blames into a preexisting origin.
 499 * If there were no previous blames to that commit, it is entered into
 500 * the commit priority queue of the score board.
 501 */
 502
 503static void queue_blames(struct blame_scoreboard *sb, struct blame_origin *porigin,
 504                         struct blame_entry *sorted)
 505{
 506        if (porigin->suspects)
 507                porigin->suspects = blame_merge(porigin->suspects, sorted);
 508        else {
 509                struct blame_origin *o;
 510                for (o = get_blame_suspects(porigin->commit); o; o = o->next) {
 511                        if (o->suspects) {
 512                                porigin->suspects = sorted;
 513                                return;
 514                        }
 515                }
 516                porigin->suspects = sorted;
 517                prio_queue_put(&sb->commits, porigin->commit);
 518        }
 519}
 520
 521/*
 522 * Fill the blob_sha1 field of an origin if it hasn't, so that later
 523 * call to fill_origin_blob() can use it to locate the data.  blob_sha1
 524 * for an origin is also used to pass the blame for the entire file to
 525 * the parent to detect the case where a child's blob is identical to
 526 * that of its parent's.
 527 *
 528 * This also fills origin->mode for corresponding tree path.
 529 */
 530static int fill_blob_sha1_and_mode(struct repository *r,
 531                                   struct blame_origin *origin)
 532{
 533        if (!is_null_oid(&origin->blob_oid))
 534                return 0;
 535        if (get_tree_entry(&origin->commit->object.oid, origin->path, &origin->blob_oid, &origin->mode))
 536                goto error_out;
 537        if (oid_object_info(r, &origin->blob_oid, NULL) != OBJ_BLOB)
 538                goto error_out;
 539        return 0;
 540 error_out:
 541        oidclr(&origin->blob_oid);
 542        origin->mode = S_IFINVALID;
 543        return -1;
 544}
 545
 546/*
 547 * We have an origin -- check if the same path exists in the
 548 * parent and return an origin structure to represent it.
 549 */
 550static struct blame_origin *find_origin(struct repository *r,
 551                                        struct commit *parent,
 552                                        struct blame_origin *origin)
 553{
 554        struct blame_origin *porigin;
 555        struct diff_options diff_opts;
 556        const char *paths[2];
 557
 558        /* First check any existing origins */
 559        for (porigin = get_blame_suspects(parent); porigin; porigin = porigin->next)
 560                if (!strcmp(porigin->path, origin->path)) {
 561                        /*
 562                         * The same path between origin and its parent
 563                         * without renaming -- the most common case.
 564                         */
 565                        return blame_origin_incref (porigin);
 566                }
 567
 568        /* See if the origin->path is different between parent
 569         * and origin first.  Most of the time they are the
 570         * same and diff-tree is fairly efficient about this.
 571         */
 572        repo_diff_setup(r, &diff_opts);
 573        diff_opts.flags.recursive = 1;
 574        diff_opts.detect_rename = 0;
 575        diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;
 576        paths[0] = origin->path;
 577        paths[1] = NULL;
 578
 579        parse_pathspec(&diff_opts.pathspec,
 580                       PATHSPEC_ALL_MAGIC & ~PATHSPEC_LITERAL,
 581                       PATHSPEC_LITERAL_PATH, "", paths);
 582        diff_setup_done(&diff_opts);
 583
 584        if (is_null_oid(&origin->commit->object.oid))
 585                do_diff_cache(get_commit_tree_oid(parent), &diff_opts);
 586        else
 587                diff_tree_oid(get_commit_tree_oid(parent),
 588                              get_commit_tree_oid(origin->commit),
 589                              "", &diff_opts);
 590        diffcore_std(&diff_opts);
 591
 592        if (!diff_queued_diff.nr) {
 593                /* The path is the same as parent */
 594                porigin = get_origin(parent, origin->path);
 595                oidcpy(&porigin->blob_oid, &origin->blob_oid);
 596                porigin->mode = origin->mode;
 597        } else {
 598                /*
 599                 * Since origin->path is a pathspec, if the parent
 600                 * commit had it as a directory, we will see a whole
 601                 * bunch of deletion of files in the directory that we
 602                 * do not care about.
 603                 */
 604                int i;
 605                struct diff_filepair *p = NULL;
 606                for (i = 0; i < diff_queued_diff.nr; i++) {
 607                        const char *name;
 608                        p = diff_queued_diff.queue[i];
 609                        name = p->one->path ? p->one->path : p->two->path;
 610                        if (!strcmp(name, origin->path))
 611                                break;
 612                }
 613                if (!p)
 614                        die("internal error in blame::find_origin");
 615                switch (p->status) {
 616                default:
 617                        die("internal error in blame::find_origin (%c)",
 618                            p->status);
 619                case 'M':
 620                        porigin = get_origin(parent, origin->path);
 621                        oidcpy(&porigin->blob_oid, &p->one->oid);
 622                        porigin->mode = p->one->mode;
 623                        break;
 624                case 'A':
 625                case 'T':
 626                        /* Did not exist in parent, or type changed */
 627                        break;
 628                }
 629        }
 630        diff_flush(&diff_opts);
 631        clear_pathspec(&diff_opts.pathspec);
 632        return porigin;
 633}
 634
 635/*
 636 * We have an origin -- find the path that corresponds to it in its
 637 * parent and return an origin structure to represent it.
 638 */
 639static struct blame_origin *find_rename(struct repository *r,
 640                                        struct commit *parent,
 641                                        struct blame_origin *origin)
 642{
 643        struct blame_origin *porigin = NULL;
 644        struct diff_options diff_opts;
 645        int i;
 646
 647        repo_diff_setup(r, &diff_opts);
 648        diff_opts.flags.recursive = 1;
 649        diff_opts.detect_rename = DIFF_DETECT_RENAME;
 650        diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;
 651        diff_opts.single_follow = origin->path;
 652        diff_setup_done(&diff_opts);
 653
 654        if (is_null_oid(&origin->commit->object.oid))
 655                do_diff_cache(get_commit_tree_oid(parent), &diff_opts);
 656        else
 657                diff_tree_oid(get_commit_tree_oid(parent),
 658                              get_commit_tree_oid(origin->commit),
 659                              "", &diff_opts);
 660        diffcore_std(&diff_opts);
 661
 662        for (i = 0; i < diff_queued_diff.nr; i++) {
 663                struct diff_filepair *p = diff_queued_diff.queue[i];
 664                if ((p->status == 'R' || p->status == 'C') &&
 665                    !strcmp(p->two->path, origin->path)) {
 666                        porigin = get_origin(parent, p->one->path);
 667                        oidcpy(&porigin->blob_oid, &p->one->oid);
 668                        porigin->mode = p->one->mode;
 669                        break;
 670                }
 671        }
 672        diff_flush(&diff_opts);
 673        clear_pathspec(&diff_opts.pathspec);
 674        return porigin;
 675}
 676
 677/*
 678 * Append a new blame entry to a given output queue.
 679 */
 680static void add_blame_entry(struct blame_entry ***queue,
 681                            const struct blame_entry *src)
 682{
 683        struct blame_entry *e = xmalloc(sizeof(*e));
 684        memcpy(e, src, sizeof(*e));
 685        blame_origin_incref(e->suspect);
 686
 687        e->next = **queue;
 688        **queue = e;
 689        *queue = &e->next;
 690}
 691
 692/*
 693 * src typically is on-stack; we want to copy the information in it to
 694 * a malloced blame_entry that gets added to the given queue.  The
 695 * origin of dst loses a refcnt.
 696 */
 697static void dup_entry(struct blame_entry ***queue,
 698                      struct blame_entry *dst, struct blame_entry *src)
 699{
 700        blame_origin_incref(src->suspect);
 701        blame_origin_decref(dst->suspect);
 702        memcpy(dst, src, sizeof(*src));
 703        dst->next = **queue;
 704        **queue = dst;
 705        *queue = &dst->next;
 706}
 707
 708const char *blame_nth_line(struct blame_scoreboard *sb, long lno)
 709{
 710        return sb->final_buf + sb->lineno[lno];
 711}
 712
 713/*
 714 * It is known that lines between tlno to same came from parent, and e
 715 * has an overlap with that range.  it also is known that parent's
 716 * line plno corresponds to e's line tlno.
 717 *
 718 *                <---- e ----->
 719 *                   <------>
 720 *                   <------------>
 721 *             <------------>
 722 *             <------------------>
 723 *
 724 * Split e into potentially three parts; before this chunk, the chunk
 725 * to be blamed for the parent, and after that portion.
 726 */
 727static void split_overlap(struct blame_entry *split,
 728                          struct blame_entry *e,
 729                          int tlno, int plno, int same,
 730                          struct blame_origin *parent)
 731{
 732        int chunk_end_lno;
 733        memset(split, 0, sizeof(struct blame_entry [3]));
 734
 735        if (e->s_lno < tlno) {
 736                /* there is a pre-chunk part not blamed on parent */
 737                split[0].suspect = blame_origin_incref(e->suspect);
 738                split[0].lno = e->lno;
 739                split[0].s_lno = e->s_lno;
 740                split[0].num_lines = tlno - e->s_lno;
 741                split[1].lno = e->lno + tlno - e->s_lno;
 742                split[1].s_lno = plno;
 743        }
 744        else {
 745                split[1].lno = e->lno;
 746                split[1].s_lno = plno + (e->s_lno - tlno);
 747        }
 748
 749        if (same < e->s_lno + e->num_lines) {
 750                /* there is a post-chunk part not blamed on parent */
 751                split[2].suspect = blame_origin_incref(e->suspect);
 752                split[2].lno = e->lno + (same - e->s_lno);
 753                split[2].s_lno = e->s_lno + (same - e->s_lno);
 754                split[2].num_lines = e->s_lno + e->num_lines - same;
 755                chunk_end_lno = split[2].lno;
 756        }
 757        else
 758                chunk_end_lno = e->lno + e->num_lines;
 759        split[1].num_lines = chunk_end_lno - split[1].lno;
 760
 761        /*
 762         * if it turns out there is nothing to blame the parent for,
 763         * forget about the splitting.  !split[1].suspect signals this.
 764         */
 765        if (split[1].num_lines < 1)
 766                return;
 767        split[1].suspect = blame_origin_incref(parent);
 768}
 769
 770/*
 771 * split_overlap() divided an existing blame e into up to three parts
 772 * in split.  Any assigned blame is moved to queue to
 773 * reflect the split.
 774 */
 775static void split_blame(struct blame_entry ***blamed,
 776                        struct blame_entry ***unblamed,
 777                        struct blame_entry *split,
 778                        struct blame_entry *e)
 779{
 780        if (split[0].suspect && split[2].suspect) {
 781                /* The first part (reuse storage for the existing entry e) */
 782                dup_entry(unblamed, e, &split[0]);
 783
 784                /* The last part -- me */
 785                add_blame_entry(unblamed, &split[2]);
 786
 787                /* ... and the middle part -- parent */
 788                add_blame_entry(blamed, &split[1]);
 789        }
 790        else if (!split[0].suspect && !split[2].suspect)
 791                /*
 792                 * The parent covers the entire area; reuse storage for
 793                 * e and replace it with the parent.
 794                 */
 795                dup_entry(blamed, e, &split[1]);
 796        else if (split[0].suspect) {
 797                /* me and then parent */
 798                dup_entry(unblamed, e, &split[0]);
 799                add_blame_entry(blamed, &split[1]);
 800        }
 801        else {
 802                /* parent and then me */
 803                dup_entry(blamed, e, &split[1]);
 804                add_blame_entry(unblamed, &split[2]);
 805        }
 806}
 807
 808/*
 809 * After splitting the blame, the origins used by the
 810 * on-stack blame_entry should lose one refcnt each.
 811 */
 812static void decref_split(struct blame_entry *split)
 813{
 814        int i;
 815
 816        for (i = 0; i < 3; i++)
 817                blame_origin_decref(split[i].suspect);
 818}
 819
 820/*
 821 * reverse_blame reverses the list given in head, appending tail.
 822 * That allows us to build lists in reverse order, then reverse them
 823 * afterwards.  This can be faster than building the list in proper
 824 * order right away.  The reason is that building in proper order
 825 * requires writing a link in the _previous_ element, while building
 826 * in reverse order just requires placing the list head into the
 827 * _current_ element.
 828 */
 829
 830static struct blame_entry *reverse_blame(struct blame_entry *head,
 831                                         struct blame_entry *tail)
 832{
 833        while (head) {
 834                struct blame_entry *next = head->next;
 835                head->next = tail;
 836                tail = head;
 837                head = next;
 838        }
 839        return tail;
 840}
 841
 842/*
 843 * Process one hunk from the patch between the current suspect for
 844 * blame_entry e and its parent.  This first blames any unfinished
 845 * entries before the chunk (which is where target and parent start
 846 * differing) on the parent, and then splits blame entries at the
 847 * start and at the end of the difference region.  Since use of -M and
 848 * -C options may lead to overlapping/duplicate source line number
 849 * ranges, all we can rely on from sorting/merging is the order of the
 850 * first suspect line number.
 851 */
 852static void blame_chunk(struct blame_entry ***dstq, struct blame_entry ***srcq,
 853                        int tlno, int offset, int same,
 854                        struct blame_origin *parent)
 855{
 856        struct blame_entry *e = **srcq;
 857        struct blame_entry *samep = NULL, *diffp = NULL;
 858
 859        while (e && e->s_lno < tlno) {
 860                struct blame_entry *next = e->next;
 861                /*
 862                 * current record starts before differing portion.  If
 863                 * it reaches into it, we need to split it up and
 864                 * examine the second part separately.
 865                 */
 866                if (e->s_lno + e->num_lines > tlno) {
 867                        /* Move second half to a new record */
 868                        int len = tlno - e->s_lno;
 869                        struct blame_entry *n = xcalloc(1, sizeof (struct blame_entry));
 870                        n->suspect = e->suspect;
 871                        n->lno = e->lno + len;
 872                        n->s_lno = e->s_lno + len;
 873                        n->num_lines = e->num_lines - len;
 874                        e->num_lines = len;
 875                        e->score = 0;
 876                        /* Push new record to diffp */
 877                        n->next = diffp;
 878                        diffp = n;
 879                } else
 880                        blame_origin_decref(e->suspect);
 881                /* Pass blame for everything before the differing
 882                 * chunk to the parent */
 883                e->suspect = blame_origin_incref(parent);
 884                e->s_lno += offset;
 885                e->next = samep;
 886                samep = e;
 887                e = next;
 888        }
 889        /*
 890         * As we don't know how much of a common stretch after this
 891         * diff will occur, the currently blamed parts are all that we
 892         * can assign to the parent for now.
 893         */
 894
 895        if (samep) {
 896                **dstq = reverse_blame(samep, **dstq);
 897                *dstq = &samep->next;
 898        }
 899        /*
 900         * Prepend the split off portions: everything after e starts
 901         * after the blameable portion.
 902         */
 903        e = reverse_blame(diffp, e);
 904
 905        /*
 906         * Now retain records on the target while parts are different
 907         * from the parent.
 908         */
 909        samep = NULL;
 910        diffp = NULL;
 911        while (e && e->s_lno < same) {
 912                struct blame_entry *next = e->next;
 913
 914                /*
 915                 * If current record extends into sameness, need to split.
 916                 */
 917                if (e->s_lno + e->num_lines > same) {
 918                        /*
 919                         * Move second half to a new record to be
 920                         * processed by later chunks
 921                         */
 922                        int len = same - e->s_lno;
 923                        struct blame_entry *n = xcalloc(1, sizeof (struct blame_entry));
 924                        n->suspect = blame_origin_incref(e->suspect);
 925                        n->lno = e->lno + len;
 926                        n->s_lno = e->s_lno + len;
 927                        n->num_lines = e->num_lines - len;
 928                        e->num_lines = len;
 929                        e->score = 0;
 930                        /* Push new record to samep */
 931                        n->next = samep;
 932                        samep = n;
 933                }
 934                e->next = diffp;
 935                diffp = e;
 936                e = next;
 937        }
 938        **srcq = reverse_blame(diffp, reverse_blame(samep, e));
 939        /* Move across elements that are in the unblamable portion */
 940        if (diffp)
 941                *srcq = &diffp->next;
 942}
 943
 944struct blame_chunk_cb_data {
 945        struct blame_origin *parent;
 946        long offset;
 947        struct blame_entry **dstq;
 948        struct blame_entry **srcq;
 949};
 950
 951/* diff chunks are from parent to target */
 952static int blame_chunk_cb(long start_a, long count_a,
 953                          long start_b, long count_b, void *data)
 954{
 955        struct blame_chunk_cb_data *d = data;
 956        if (start_a - start_b != d->offset)
 957                die("internal error in blame::blame_chunk_cb");
 958        blame_chunk(&d->dstq, &d->srcq, start_b, start_a - start_b,
 959                    start_b + count_b, d->parent);
 960        d->offset = start_a + count_a - (start_b + count_b);
 961        return 0;
 962}
 963
 964/*
 965 * We are looking at the origin 'target' and aiming to pass blame
 966 * for the lines it is suspected to its parent.  Run diff to find
 967 * which lines came from parent and pass blame for them.
 968 */
 969static void pass_blame_to_parent(struct blame_scoreboard *sb,
 970                                 struct blame_origin *target,
 971                                 struct blame_origin *parent)
 972{
 973        mmfile_t file_p, file_o;
 974        struct blame_chunk_cb_data d;
 975        struct blame_entry *newdest = NULL;
 976
 977        if (!target->suspects)
 978                return; /* nothing remains for this target */
 979
 980        d.parent = parent;
 981        d.offset = 0;
 982        d.dstq = &newdest; d.srcq = &target->suspects;
 983
 984        fill_origin_blob(&sb->revs->diffopt, parent, &file_p, &sb->num_read_blob);
 985        fill_origin_blob(&sb->revs->diffopt, target, &file_o, &sb->num_read_blob);
 986        sb->num_get_patch++;
 987
 988        if (diff_hunks(&file_p, &file_o, blame_chunk_cb, &d, sb->xdl_opts))
 989                die("unable to generate diff (%s -> %s)",
 990                    oid_to_hex(&parent->commit->object.oid),
 991                    oid_to_hex(&target->commit->object.oid));
 992        /* The rest are the same as the parent */
 993        blame_chunk(&d.dstq, &d.srcq, INT_MAX, d.offset, INT_MAX, parent);
 994        *d.dstq = NULL;
 995        queue_blames(sb, parent, newdest);
 996
 997        return;
 998}
 999
1000/*
1001 * The lines in blame_entry after splitting blames many times can become
1002 * very small and trivial, and at some point it becomes pointless to
1003 * blame the parents.  E.g. "\t\t}\n\t}\n\n" appears everywhere in any
1004 * ordinary C program, and it is not worth to say it was copied from
1005 * totally unrelated file in the parent.
1006 *
1007 * Compute how trivial the lines in the blame_entry are.
1008 */
1009unsigned blame_entry_score(struct blame_scoreboard *sb, struct blame_entry *e)
1010{
1011        unsigned score;
1012        const char *cp, *ep;
1013
1014        if (e->score)
1015                return e->score;
1016
1017        score = 1;
1018        cp = blame_nth_line(sb, e->lno);
1019        ep = blame_nth_line(sb, e->lno + e->num_lines);
1020        while (cp < ep) {
1021                unsigned ch = *((unsigned char *)cp);
1022                if (isalnum(ch))
1023                        score++;
1024                cp++;
1025        }
1026        e->score = score;
1027        return score;
1028}
1029
1030/*
1031 * best_so_far[] and potential[] are both a split of an existing blame_entry
1032 * that passes blame to the parent.  Maintain best_so_far the best split so
1033 * far, by comparing potential and best_so_far and copying potential into
1034 * bst_so_far as needed.
1035 */
1036static void copy_split_if_better(struct blame_scoreboard *sb,
1037                                 struct blame_entry *best_so_far,
1038                                 struct blame_entry *potential)
1039{
1040        int i;
1041
1042        if (!potential[1].suspect)
1043                return;
1044        if (best_so_far[1].suspect) {
1045                if (blame_entry_score(sb, &potential[1]) <
1046                    blame_entry_score(sb, &best_so_far[1]))
1047                        return;
1048        }
1049
1050        for (i = 0; i < 3; i++)
1051                blame_origin_incref(potential[i].suspect);
1052        decref_split(best_so_far);
1053        memcpy(best_so_far, potential, sizeof(struct blame_entry[3]));
1054}
1055
1056/*
1057 * We are looking at a part of the final image represented by
1058 * ent (tlno and same are offset by ent->s_lno).
1059 * tlno is where we are looking at in the final image.
1060 * up to (but not including) same match preimage.
1061 * plno is where we are looking at in the preimage.
1062 *
1063 * <-------------- final image ---------------------->
1064 *       <------ent------>
1065 *         ^tlno ^same
1066 *    <---------preimage----->
1067 *         ^plno
1068 *
1069 * All line numbers are 0-based.
1070 */
1071static void handle_split(struct blame_scoreboard *sb,
1072                         struct blame_entry *ent,
1073                         int tlno, int plno, int same,
1074                         struct blame_origin *parent,
1075                         struct blame_entry *split)
1076{
1077        if (ent->num_lines <= tlno)
1078                return;
1079        if (tlno < same) {
1080                struct blame_entry potential[3];
1081                tlno += ent->s_lno;
1082                same += ent->s_lno;
1083                split_overlap(potential, ent, tlno, plno, same, parent);
1084                copy_split_if_better(sb, split, potential);
1085                decref_split(potential);
1086        }
1087}
1088
1089struct handle_split_cb_data {
1090        struct blame_scoreboard *sb;
1091        struct blame_entry *ent;
1092        struct blame_origin *parent;
1093        struct blame_entry *split;
1094        long plno;
1095        long tlno;
1096};
1097
1098static int handle_split_cb(long start_a, long count_a,
1099                           long start_b, long count_b, void *data)
1100{
1101        struct handle_split_cb_data *d = data;
1102        handle_split(d->sb, d->ent, d->tlno, d->plno, start_b, d->parent,
1103                     d->split);
1104        d->plno = start_a + count_a;
1105        d->tlno = start_b + count_b;
1106        return 0;
1107}
1108
1109/*
1110 * Find the lines from parent that are the same as ent so that
1111 * we can pass blames to it.  file_p has the blob contents for
1112 * the parent.
1113 */
1114static void find_copy_in_blob(struct blame_scoreboard *sb,
1115                              struct blame_entry *ent,
1116                              struct blame_origin *parent,
1117                              struct blame_entry *split,
1118                              mmfile_t *file_p)
1119{
1120        const char *cp;
1121        mmfile_t file_o;
1122        struct handle_split_cb_data d;
1123
1124        memset(&d, 0, sizeof(d));
1125        d.sb = sb; d.ent = ent; d.parent = parent; d.split = split;
1126        /*
1127         * Prepare mmfile that contains only the lines in ent.
1128         */
1129        cp = blame_nth_line(sb, ent->lno);
1130        file_o.ptr = (char *) cp;
1131        file_o.size = blame_nth_line(sb, ent->lno + ent->num_lines) - cp;
1132
1133        /*
1134         * file_o is a part of final image we are annotating.
1135         * file_p partially may match that image.
1136         */
1137        memset(split, 0, sizeof(struct blame_entry [3]));
1138        if (diff_hunks(file_p, &file_o, handle_split_cb, &d, sb->xdl_opts))
1139                die("unable to generate diff (%s)",
1140                    oid_to_hex(&parent->commit->object.oid));
1141        /* remainder, if any, all match the preimage */
1142        handle_split(sb, ent, d.tlno, d.plno, ent->num_lines, parent, split);
1143}
1144
1145/* Move all blame entries from list *source that have a score smaller
1146 * than score_min to the front of list *small.
1147 * Returns a pointer to the link pointing to the old head of the small list.
1148 */
1149
1150static struct blame_entry **filter_small(struct blame_scoreboard *sb,
1151                                         struct blame_entry **small,
1152                                         struct blame_entry **source,
1153                                         unsigned score_min)
1154{
1155        struct blame_entry *p = *source;
1156        struct blame_entry *oldsmall = *small;
1157        while (p) {
1158                if (blame_entry_score(sb, p) <= score_min) {
1159                        *small = p;
1160                        small = &p->next;
1161                        p = *small;
1162                } else {
1163                        *source = p;
1164                        source = &p->next;
1165                        p = *source;
1166                }
1167        }
1168        *small = oldsmall;
1169        *source = NULL;
1170        return small;
1171}
1172
1173/*
1174 * See if lines currently target is suspected for can be attributed to
1175 * parent.
1176 */
1177static void find_move_in_parent(struct blame_scoreboard *sb,
1178                                struct blame_entry ***blamed,
1179                                struct blame_entry **toosmall,
1180                                struct blame_origin *target,
1181                                struct blame_origin *parent)
1182{
1183        struct blame_entry *e, split[3];
1184        struct blame_entry *unblamed = target->suspects;
1185        struct blame_entry *leftover = NULL;
1186        mmfile_t file_p;
1187
1188        if (!unblamed)
1189                return; /* nothing remains for this target */
1190
1191        fill_origin_blob(&sb->revs->diffopt, parent, &file_p, &sb->num_read_blob);
1192        if (!file_p.ptr)
1193                return;
1194
1195        /* At each iteration, unblamed has a NULL-terminated list of
1196         * entries that have not yet been tested for blame.  leftover
1197         * contains the reversed list of entries that have been tested
1198         * without being assignable to the parent.
1199         */
1200        do {
1201                struct blame_entry **unblamedtail = &unblamed;
1202                struct blame_entry *next;
1203                for (e = unblamed; e; e = next) {
1204                        next = e->next;
1205                        find_copy_in_blob(sb, e, parent, split, &file_p);
1206                        if (split[1].suspect &&
1207                            sb->move_score < blame_entry_score(sb, &split[1])) {
1208                                split_blame(blamed, &unblamedtail, split, e);
1209                        } else {
1210                                e->next = leftover;
1211                                leftover = e;
1212                        }
1213                        decref_split(split);
1214                }
1215                *unblamedtail = NULL;
1216                toosmall = filter_small(sb, toosmall, &unblamed, sb->move_score);
1217        } while (unblamed);
1218        target->suspects = reverse_blame(leftover, NULL);
1219}
1220
1221struct blame_list {
1222        struct blame_entry *ent;
1223        struct blame_entry split[3];
1224};
1225
1226/*
1227 * Count the number of entries the target is suspected for,
1228 * and prepare a list of entry and the best split.
1229 */
1230static struct blame_list *setup_blame_list(struct blame_entry *unblamed,
1231                                           int *num_ents_p)
1232{
1233        struct blame_entry *e;
1234        int num_ents, i;
1235        struct blame_list *blame_list = NULL;
1236
1237        for (e = unblamed, num_ents = 0; e; e = e->next)
1238                num_ents++;
1239        if (num_ents) {
1240                blame_list = xcalloc(num_ents, sizeof(struct blame_list));
1241                for (e = unblamed, i = 0; e; e = e->next)
1242                        blame_list[i++].ent = e;
1243        }
1244        *num_ents_p = num_ents;
1245        return blame_list;
1246}
1247
1248/*
1249 * For lines target is suspected for, see if we can find code movement
1250 * across file boundary from the parent commit.  porigin is the path
1251 * in the parent we already tried.
1252 */
1253static void find_copy_in_parent(struct blame_scoreboard *sb,
1254                                struct blame_entry ***blamed,
1255                                struct blame_entry **toosmall,
1256                                struct blame_origin *target,
1257                                struct commit *parent,
1258                                struct blame_origin *porigin,
1259                                int opt)
1260{
1261        struct diff_options diff_opts;
1262        int i, j;
1263        struct blame_list *blame_list;
1264        int num_ents;
1265        struct blame_entry *unblamed = target->suspects;
1266        struct blame_entry *leftover = NULL;
1267
1268        if (!unblamed)
1269                return; /* nothing remains for this target */
1270
1271        repo_diff_setup(sb->repo, &diff_opts);
1272        diff_opts.flags.recursive = 1;
1273        diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;
1274
1275        diff_setup_done(&diff_opts);
1276
1277        /* Try "find copies harder" on new path if requested;
1278         * we do not want to use diffcore_rename() actually to
1279         * match things up; find_copies_harder is set only to
1280         * force diff_tree_oid() to feed all filepairs to diff_queue,
1281         * and this code needs to be after diff_setup_done(), which
1282         * usually makes find-copies-harder imply copy detection.
1283         */
1284        if ((opt & PICKAXE_BLAME_COPY_HARDEST)
1285            || ((opt & PICKAXE_BLAME_COPY_HARDER)
1286                && (!porigin || strcmp(target->path, porigin->path))))
1287                diff_opts.flags.find_copies_harder = 1;
1288
1289        if (is_null_oid(&target->commit->object.oid))
1290                do_diff_cache(get_commit_tree_oid(parent), &diff_opts);
1291        else
1292                diff_tree_oid(get_commit_tree_oid(parent),
1293                              get_commit_tree_oid(target->commit),
1294                              "", &diff_opts);
1295
1296        if (!diff_opts.flags.find_copies_harder)
1297                diffcore_std(&diff_opts);
1298
1299        do {
1300                struct blame_entry **unblamedtail = &unblamed;
1301                blame_list = setup_blame_list(unblamed, &num_ents);
1302
1303                for (i = 0; i < diff_queued_diff.nr; i++) {
1304                        struct diff_filepair *p = diff_queued_diff.queue[i];
1305                        struct blame_origin *norigin;
1306                        mmfile_t file_p;
1307                        struct blame_entry potential[3];
1308
1309                        if (!DIFF_FILE_VALID(p->one))
1310                                continue; /* does not exist in parent */
1311                        if (S_ISGITLINK(p->one->mode))
1312                                continue; /* ignore git links */
1313                        if (porigin && !strcmp(p->one->path, porigin->path))
1314                                /* find_move already dealt with this path */
1315                                continue;
1316
1317                        norigin = get_origin(parent, p->one->path);
1318                        oidcpy(&norigin->blob_oid, &p->one->oid);
1319                        norigin->mode = p->one->mode;
1320                        fill_origin_blob(&sb->revs->diffopt, norigin, &file_p, &sb->num_read_blob);
1321                        if (!file_p.ptr)
1322                                continue;
1323
1324                        for (j = 0; j < num_ents; j++) {
1325                                find_copy_in_blob(sb, blame_list[j].ent,
1326                                                  norigin, potential, &file_p);
1327                                copy_split_if_better(sb, blame_list[j].split,
1328                                                     potential);
1329                                decref_split(potential);
1330                        }
1331                        blame_origin_decref(norigin);
1332                }
1333
1334                for (j = 0; j < num_ents; j++) {
1335                        struct blame_entry *split = blame_list[j].split;
1336                        if (split[1].suspect &&
1337                            sb->copy_score < blame_entry_score(sb, &split[1])) {
1338                                split_blame(blamed, &unblamedtail, split,
1339                                            blame_list[j].ent);
1340                        } else {
1341                                blame_list[j].ent->next = leftover;
1342                                leftover = blame_list[j].ent;
1343                        }
1344                        decref_split(split);
1345                }
1346                free(blame_list);
1347                *unblamedtail = NULL;
1348                toosmall = filter_small(sb, toosmall, &unblamed, sb->copy_score);
1349        } while (unblamed);
1350        target->suspects = reverse_blame(leftover, NULL);
1351        diff_flush(&diff_opts);
1352        clear_pathspec(&diff_opts.pathspec);
1353}
1354
1355/*
1356 * The blobs of origin and porigin exactly match, so everything
1357 * origin is suspected for can be blamed on the parent.
1358 */
1359static void pass_whole_blame(struct blame_scoreboard *sb,
1360                             struct blame_origin *origin, struct blame_origin *porigin)
1361{
1362        struct blame_entry *e, *suspects;
1363
1364        if (!porigin->file.ptr && origin->file.ptr) {
1365                /* Steal its file */
1366                porigin->file = origin->file;
1367                origin->file.ptr = NULL;
1368        }
1369        suspects = origin->suspects;
1370        origin->suspects = NULL;
1371        for (e = suspects; e; e = e->next) {
1372                blame_origin_incref(porigin);
1373                blame_origin_decref(e->suspect);
1374                e->suspect = porigin;
1375        }
1376        queue_blames(sb, porigin, suspects);
1377}
1378
1379/*
1380 * We pass blame from the current commit to its parents.  We keep saying
1381 * "parent" (and "porigin"), but what we mean is to find scapegoat to
1382 * exonerate ourselves.
1383 */
1384static struct commit_list *first_scapegoat(struct rev_info *revs, struct commit *commit,
1385                                        int reverse)
1386{
1387        if (!reverse) {
1388                if (revs->first_parent_only &&
1389                    commit->parents &&
1390                    commit->parents->next) {
1391                        free_commit_list(commit->parents->next);
1392                        commit->parents->next = NULL;
1393                }
1394                return commit->parents;
1395        }
1396        return lookup_decoration(&revs->children, &commit->object);
1397}
1398
1399static int num_scapegoats(struct rev_info *revs, struct commit *commit, int reverse)
1400{
1401        struct commit_list *l = first_scapegoat(revs, commit, reverse);
1402        return commit_list_count(l);
1403}
1404
1405/* Distribute collected unsorted blames to the respected sorted lists
1406 * in the various origins.
1407 */
1408static void distribute_blame(struct blame_scoreboard *sb, struct blame_entry *blamed)
1409{
1410        blamed = llist_mergesort(blamed, get_next_blame, set_next_blame,
1411                                 compare_blame_suspect);
1412        while (blamed)
1413        {
1414                struct blame_origin *porigin = blamed->suspect;
1415                struct blame_entry *suspects = NULL;
1416                do {
1417                        struct blame_entry *next = blamed->next;
1418                        blamed->next = suspects;
1419                        suspects = blamed;
1420                        blamed = next;
1421                } while (blamed && blamed->suspect == porigin);
1422                suspects = reverse_blame(suspects, NULL);
1423                queue_blames(sb, porigin, suspects);
1424        }
1425}
1426
1427#define MAXSG 16
1428
1429static void pass_blame(struct blame_scoreboard *sb, struct blame_origin *origin, int opt)
1430{
1431        struct rev_info *revs = sb->revs;
1432        int i, pass, num_sg;
1433        struct commit *commit = origin->commit;
1434        struct commit_list *sg;
1435        struct blame_origin *sg_buf[MAXSG];
1436        struct blame_origin *porigin, **sg_origin = sg_buf;
1437        struct blame_entry *toosmall = NULL;
1438        struct blame_entry *blames, **blametail = &blames;
1439
1440        num_sg = num_scapegoats(revs, commit, sb->reverse);
1441        if (!num_sg)
1442                goto finish;
1443        else if (num_sg < ARRAY_SIZE(sg_buf))
1444                memset(sg_buf, 0, sizeof(sg_buf));
1445        else
1446                sg_origin = xcalloc(num_sg, sizeof(*sg_origin));
1447
1448        /*
1449         * The first pass looks for unrenamed path to optimize for
1450         * common cases, then we look for renames in the second pass.
1451         */
1452        for (pass = 0; pass < 2 - sb->no_whole_file_rename; pass++) {
1453                struct blame_origin *(*find)(struct repository *, struct commit *, struct blame_origin *);
1454                find = pass ? find_rename : find_origin;
1455
1456                for (i = 0, sg = first_scapegoat(revs, commit, sb->reverse);
1457                     i < num_sg && sg;
1458                     sg = sg->next, i++) {
1459                        struct commit *p = sg->item;
1460                        int j, same;
1461
1462                        if (sg_origin[i])
1463                                continue;
1464                        if (parse_commit(p))
1465                                continue;
1466                        porigin = find(sb->repo, p, origin);
1467                        if (!porigin)
1468                                continue;
1469                        if (oideq(&porigin->blob_oid, &origin->blob_oid)) {
1470                                pass_whole_blame(sb, origin, porigin);
1471                                blame_origin_decref(porigin);
1472                                goto finish;
1473                        }
1474                        for (j = same = 0; j < i; j++)
1475                                if (sg_origin[j] &&
1476                                    oideq(&sg_origin[j]->blob_oid, &porigin->blob_oid)) {
1477                                        same = 1;
1478                                        break;
1479                                }
1480                        if (!same)
1481                                sg_origin[i] = porigin;
1482                        else
1483                                blame_origin_decref(porigin);
1484                }
1485        }
1486
1487        sb->num_commits++;
1488        for (i = 0, sg = first_scapegoat(revs, commit, sb->reverse);
1489             i < num_sg && sg;
1490             sg = sg->next, i++) {
1491                struct blame_origin *porigin = sg_origin[i];
1492                if (!porigin)
1493                        continue;
1494                if (!origin->previous) {
1495                        blame_origin_incref(porigin);
1496                        origin->previous = porigin;
1497                }
1498                pass_blame_to_parent(sb, origin, porigin);
1499                if (!origin->suspects)
1500                        goto finish;
1501        }
1502
1503        /*
1504         * Optionally find moves in parents' files.
1505         */
1506        if (opt & PICKAXE_BLAME_MOVE) {
1507                filter_small(sb, &toosmall, &origin->suspects, sb->move_score);
1508                if (origin->suspects) {
1509                        for (i = 0, sg = first_scapegoat(revs, commit, sb->reverse);
1510                             i < num_sg && sg;
1511                             sg = sg->next, i++) {
1512                                struct blame_origin *porigin = sg_origin[i];
1513                                if (!porigin)
1514                                        continue;
1515                                find_move_in_parent(sb, &blametail, &toosmall, origin, porigin);
1516                                if (!origin->suspects)
1517                                        break;
1518                        }
1519                }
1520        }
1521
1522        /*
1523         * Optionally find copies from parents' files.
1524         */
1525        if (opt & PICKAXE_BLAME_COPY) {
1526                if (sb->copy_score > sb->move_score)
1527                        filter_small(sb, &toosmall, &origin->suspects, sb->copy_score);
1528                else if (sb->copy_score < sb->move_score) {
1529                        origin->suspects = blame_merge(origin->suspects, toosmall);
1530                        toosmall = NULL;
1531                        filter_small(sb, &toosmall, &origin->suspects, sb->copy_score);
1532                }
1533                if (!origin->suspects)
1534                        goto finish;
1535
1536                for (i = 0, sg = first_scapegoat(revs, commit, sb->reverse);
1537                     i < num_sg && sg;
1538                     sg = sg->next, i++) {
1539                        struct blame_origin *porigin = sg_origin[i];
1540                        find_copy_in_parent(sb, &blametail, &toosmall,
1541                                            origin, sg->item, porigin, opt);
1542                        if (!origin->suspects)
1543                                goto finish;
1544                }
1545        }
1546
1547finish:
1548        *blametail = NULL;
1549        distribute_blame(sb, blames);
1550        /*
1551         * prepend toosmall to origin->suspects
1552         *
1553         * There is no point in sorting: this ends up on a big
1554         * unsorted list in the caller anyway.
1555         */
1556        if (toosmall) {
1557                struct blame_entry **tail = &toosmall;
1558                while (*tail)
1559                        tail = &(*tail)->next;
1560                *tail = origin->suspects;
1561                origin->suspects = toosmall;
1562        }
1563        for (i = 0; i < num_sg; i++) {
1564                if (sg_origin[i]) {
1565                        if (!sg_origin[i]->suspects)
1566                                drop_origin_blob(sg_origin[i]);
1567                        blame_origin_decref(sg_origin[i]);
1568                }
1569        }
1570        drop_origin_blob(origin);
1571        if (sg_buf != sg_origin)
1572                free(sg_origin);
1573}
1574
1575/*
1576 * The main loop -- while we have blobs with lines whose true origin
1577 * is still unknown, pick one blob, and allow its lines to pass blames
1578 * to its parents. */
1579void assign_blame(struct blame_scoreboard *sb, int opt)
1580{
1581        struct rev_info *revs = sb->revs;
1582        struct commit *commit = prio_queue_get(&sb->commits);
1583
1584        while (commit) {
1585                struct blame_entry *ent;
1586                struct blame_origin *suspect = get_blame_suspects(commit);
1587
1588                /* find one suspect to break down */
1589                while (suspect && !suspect->suspects)
1590                        suspect = suspect->next;
1591
1592                if (!suspect) {
1593                        commit = prio_queue_get(&sb->commits);
1594                        continue;
1595                }
1596
1597                assert(commit == suspect->commit);
1598
1599                /*
1600                 * We will use this suspect later in the loop,
1601                 * so hold onto it in the meantime.
1602                 */
1603                blame_origin_incref(suspect);
1604                parse_commit(commit);
1605                if (sb->reverse ||
1606                    (!(commit->object.flags & UNINTERESTING) &&
1607                     !(revs->max_age != -1 && commit->date < revs->max_age)))
1608                        pass_blame(sb, suspect, opt);
1609                else {
1610                        commit->object.flags |= UNINTERESTING;
1611                        if (commit->object.parsed)
1612                                mark_parents_uninteresting(commit);
1613                }
1614                /* treat root commit as boundary */
1615                if (!commit->parents && !sb->show_root)
1616                        commit->object.flags |= UNINTERESTING;
1617
1618                /* Take responsibility for the remaining entries */
1619                ent = suspect->suspects;
1620                if (ent) {
1621                        suspect->guilty = 1;
1622                        for (;;) {
1623                                struct blame_entry *next = ent->next;
1624                                if (sb->found_guilty_entry)
1625                                        sb->found_guilty_entry(ent, sb->found_guilty_entry_data);
1626                                if (next) {
1627                                        ent = next;
1628                                        continue;
1629                                }
1630                                ent->next = sb->ent;
1631                                sb->ent = suspect->suspects;
1632                                suspect->suspects = NULL;
1633                                break;
1634                        }
1635                }
1636                blame_origin_decref(suspect);
1637
1638                if (sb->debug) /* sanity */
1639                        sanity_check_refcnt(sb);
1640        }
1641}
1642
1643static const char *get_next_line(const char *start, const char *end)
1644{
1645        const char *nl = memchr(start, '\n', end - start);
1646        return nl ? nl + 1 : end;
1647}
1648
1649/*
1650 * To allow quick access to the contents of nth line in the
1651 * final image, prepare an index in the scoreboard.
1652 */
1653static int prepare_lines(struct blame_scoreboard *sb)
1654{
1655        const char *buf = sb->final_buf;
1656        unsigned long len = sb->final_buf_size;
1657        const char *end = buf + len;
1658        const char *p;
1659        int *lineno;
1660        int num = 0;
1661
1662        for (p = buf; p < end; p = get_next_line(p, end))
1663                num++;
1664
1665        ALLOC_ARRAY(sb->lineno, num + 1);
1666        lineno = sb->lineno;
1667
1668        for (p = buf; p < end; p = get_next_line(p, end))
1669                *lineno++ = p - buf;
1670
1671        *lineno = len;
1672
1673        sb->num_lines = num;
1674        return sb->num_lines;
1675}
1676
1677static struct commit *find_single_final(struct rev_info *revs,
1678                                        const char **name_p)
1679{
1680        int i;
1681        struct commit *found = NULL;
1682        const char *name = NULL;
1683
1684        for (i = 0; i < revs->pending.nr; i++) {
1685                struct object *obj = revs->pending.objects[i].item;
1686                if (obj->flags & UNINTERESTING)
1687                        continue;
1688                obj = deref_tag(revs->repo, obj, NULL, 0);
1689                if (obj->type != OBJ_COMMIT)
1690                        die("Non commit %s?", revs->pending.objects[i].name);
1691                if (found)
1692                        die("More than one commit to dig from %s and %s?",
1693                            revs->pending.objects[i].name, name);
1694                found = (struct commit *)obj;
1695                name = revs->pending.objects[i].name;
1696        }
1697        if (name_p)
1698                *name_p = xstrdup_or_null(name);
1699        return found;
1700}
1701
1702static struct commit *dwim_reverse_initial(struct rev_info *revs,
1703                                           const char **name_p)
1704{
1705        /*
1706         * DWIM "git blame --reverse ONE -- PATH" as
1707         * "git blame --reverse ONE..HEAD -- PATH" but only do so
1708         * when it makes sense.
1709         */
1710        struct object *obj;
1711        struct commit *head_commit;
1712        struct object_id head_oid;
1713
1714        if (revs->pending.nr != 1)
1715                return NULL;
1716
1717        /* Is that sole rev a committish? */
1718        obj = revs->pending.objects[0].item;
1719        obj = deref_tag(revs->repo, obj, NULL, 0);
1720        if (obj->type != OBJ_COMMIT)
1721                return NULL;
1722
1723        /* Do we have HEAD? */
1724        if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, &head_oid, NULL))
1725                return NULL;
1726        head_commit = lookup_commit_reference_gently(revs->repo,
1727                                                     &head_oid, 1);
1728        if (!head_commit)
1729                return NULL;
1730
1731        /* Turn "ONE" into "ONE..HEAD" then */
1732        obj->flags |= UNINTERESTING;
1733        add_pending_object(revs, &head_commit->object, "HEAD");
1734
1735        if (name_p)
1736                *name_p = revs->pending.objects[0].name;
1737        return (struct commit *)obj;
1738}
1739
1740static struct commit *find_single_initial(struct rev_info *revs,
1741                                          const char **name_p)
1742{
1743        int i;
1744        struct commit *found = NULL;
1745        const char *name = NULL;
1746
1747        /*
1748         * There must be one and only one negative commit, and it must be
1749         * the boundary.
1750         */
1751        for (i = 0; i < revs->pending.nr; i++) {
1752                struct object *obj = revs->pending.objects[i].item;
1753                if (!(obj->flags & UNINTERESTING))
1754                        continue;
1755                obj = deref_tag(revs->repo, obj, NULL, 0);
1756                if (obj->type != OBJ_COMMIT)
1757                        die("Non commit %s?", revs->pending.objects[i].name);
1758                if (found)
1759                        die("More than one commit to dig up from, %s and %s?",
1760                            revs->pending.objects[i].name, name);
1761                found = (struct commit *) obj;
1762                name = revs->pending.objects[i].name;
1763        }
1764
1765        if (!name)
1766                found = dwim_reverse_initial(revs, &name);
1767        if (!name)
1768                die("No commit to dig up from?");
1769
1770        if (name_p)
1771                *name_p = xstrdup(name);
1772        return found;
1773}
1774
1775void init_scoreboard(struct blame_scoreboard *sb)
1776{
1777        memset(sb, 0, sizeof(struct blame_scoreboard));
1778        sb->move_score = BLAME_DEFAULT_MOVE_SCORE;
1779        sb->copy_score = BLAME_DEFAULT_COPY_SCORE;
1780}
1781
1782void setup_scoreboard(struct blame_scoreboard *sb,
1783                      const char *path,
1784                      struct blame_origin **orig)
1785{
1786        const char *final_commit_name = NULL;
1787        struct blame_origin *o;
1788        struct commit *final_commit = NULL;
1789        enum object_type type;
1790
1791        init_blame_suspects(&blame_suspects);
1792
1793        if (sb->reverse && sb->contents_from)
1794                die(_("--contents and --reverse do not blend well."));
1795
1796        if (!sb->repo)
1797                BUG("repo is NULL");
1798
1799        if (!sb->reverse) {
1800                sb->final = find_single_final(sb->revs, &final_commit_name);
1801                sb->commits.compare = compare_commits_by_commit_date;
1802        } else {
1803                sb->final = find_single_initial(sb->revs, &final_commit_name);
1804                sb->commits.compare = compare_commits_by_reverse_commit_date;
1805        }
1806
1807        if (sb->final && sb->contents_from)
1808                die(_("cannot use --contents with final commit object name"));
1809
1810        if (sb->reverse && sb->revs->first_parent_only)
1811                sb->revs->children.name = NULL;
1812
1813        if (!sb->final) {
1814                /*
1815                 * "--not A B -- path" without anything positive;
1816                 * do not default to HEAD, but use the working tree
1817                 * or "--contents".
1818                 */
1819                setup_work_tree();
1820                sb->final = fake_working_tree_commit(sb->repo,
1821                                                     &sb->revs->diffopt,
1822                                                     path, sb->contents_from);
1823                add_pending_object(sb->revs, &(sb->final->object), ":");
1824        }
1825
1826        if (sb->reverse && sb->revs->first_parent_only) {
1827                final_commit = find_single_final(sb->revs, NULL);
1828                if (!final_commit)
1829                        die(_("--reverse and --first-parent together require specified latest commit"));
1830        }
1831
1832        /*
1833         * If we have bottom, this will mark the ancestors of the
1834         * bottom commits we would reach while traversing as
1835         * uninteresting.
1836         */
1837        if (prepare_revision_walk(sb->revs))
1838                die(_("revision walk setup failed"));
1839
1840        if (sb->reverse && sb->revs->first_parent_only) {
1841                struct commit *c = final_commit;
1842
1843                sb->revs->children.name = "children";
1844                while (c->parents &&
1845                       !oideq(&c->object.oid, &sb->final->object.oid)) {
1846                        struct commit_list *l = xcalloc(1, sizeof(*l));
1847
1848                        l->item = c;
1849                        if (add_decoration(&sb->revs->children,
1850                                           &c->parents->item->object, l))
1851                                BUG("not unique item in first-parent chain");
1852                        c = c->parents->item;
1853                }
1854
1855                if (!oideq(&c->object.oid, &sb->final->object.oid))
1856                        die(_("--reverse --first-parent together require range along first-parent chain"));
1857        }
1858
1859        if (is_null_oid(&sb->final->object.oid)) {
1860                o = get_blame_suspects(sb->final);
1861                sb->final_buf = xmemdupz(o->file.ptr, o->file.size);
1862                sb->final_buf_size = o->file.size;
1863        }
1864        else {
1865                o = get_origin(sb->final, path);
1866                if (fill_blob_sha1_and_mode(sb->repo, o))
1867                        die(_("no such path %s in %s"), path, final_commit_name);
1868
1869                if (sb->revs->diffopt.flags.allow_textconv &&
1870                    textconv_object(sb->repo, path, o->mode, &o->blob_oid, 1, (char **) &sb->final_buf,
1871                                    &sb->final_buf_size))
1872                        ;
1873                else
1874                        sb->final_buf = read_object_file(&o->blob_oid, &type,
1875                                                         &sb->final_buf_size);
1876
1877                if (!sb->final_buf)
1878                        die(_("cannot read blob %s for path %s"),
1879                            oid_to_hex(&o->blob_oid),
1880                            path);
1881        }
1882        sb->num_read_blob++;
1883        prepare_lines(sb);
1884
1885        if (orig)
1886                *orig = o;
1887
1888        free((char *)final_commit_name);
1889}
1890
1891
1892
1893struct blame_entry *blame_entry_prepend(struct blame_entry *head,
1894                                        long start, long end,
1895                                        struct blame_origin *o)
1896{
1897        struct blame_entry *new_head = xcalloc(1, sizeof(struct blame_entry));
1898        new_head->lno = start;
1899        new_head->num_lines = end - start;
1900        new_head->suspect = o;
1901        new_head->s_lno = start;
1902        new_head->next = head;
1903        blame_origin_incref(o);
1904        return new_head;
1905}