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