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