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