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