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