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