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