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