builtin-blame.con commit blame: use xdi_diff_hunks(), get rid of struct patch (cdcab13)
   1/*
   2 * Pickaxe
   3 *
   4 * Copyright (c) 2006, Junio C Hamano
   5 */
   6
   7#include "cache.h"
   8#include "builtin.h"
   9#include "blob.h"
  10#include "commit.h"
  11#include "tag.h"
  12#include "tree-walk.h"
  13#include "diff.h"
  14#include "diffcore.h"
  15#include "revision.h"
  16#include "quote.h"
  17#include "xdiff-interface.h"
  18#include "cache-tree.h"
  19#include "string-list.h"
  20#include "mailmap.h"
  21#include "parse-options.h"
  22
  23static char blame_usage[] = "git blame [options] [rev-opts] [rev] [--] file";
  24
  25static const char *blame_opt_usage[] = {
  26        blame_usage,
  27        "",
  28        "[rev-opts] are documented in git-rev-list(1)",
  29        NULL
  30};
  31
  32static int longest_file;
  33static int longest_author;
  34static int max_orig_digits;
  35static int max_digits;
  36static int max_score_digits;
  37static int show_root;
  38static int reverse;
  39static int blank_boundary;
  40static int incremental;
  41static int xdl_opts = XDF_NEED_MINIMAL;
  42static struct string_list mailmap;
  43
  44#ifndef DEBUG
  45#define DEBUG 0
  46#endif
  47
  48/* stats */
  49static int num_read_blob;
  50static int num_get_patch;
  51static int num_commits;
  52
  53#define PICKAXE_BLAME_MOVE              01
  54#define PICKAXE_BLAME_COPY              02
  55#define PICKAXE_BLAME_COPY_HARDER       04
  56#define PICKAXE_BLAME_COPY_HARDEST      010
  57
  58/*
  59 * blame for a blame_entry with score lower than these thresholds
  60 * is not passed to the parent using move/copy logic.
  61 */
  62static unsigned blame_move_score;
  63static unsigned blame_copy_score;
  64#define BLAME_DEFAULT_MOVE_SCORE        20
  65#define BLAME_DEFAULT_COPY_SCORE        40
  66
  67/* bits #0..7 in revision.h, #8..11 used for merge_bases() in commit.c */
  68#define METAINFO_SHOWN          (1u<<12)
  69#define MORE_THAN_ONE_PATH      (1u<<13)
  70
  71/*
  72 * One blob in a commit that is being suspected
  73 */
  74struct origin {
  75        int refcnt;
  76        struct commit *commit;
  77        mmfile_t file;
  78        unsigned char blob_sha1[20];
  79        char path[FLEX_ARRAY];
  80};
  81
  82/*
  83 * Given an origin, prepare mmfile_t structure to be used by the
  84 * diff machinery
  85 */
  86static void fill_origin_blob(struct origin *o, mmfile_t *file)
  87{
  88        if (!o->file.ptr) {
  89                enum object_type type;
  90                num_read_blob++;
  91                file->ptr = read_sha1_file(o->blob_sha1, &type,
  92                                           (unsigned long *)(&(file->size)));
  93                if (!file->ptr)
  94                        die("Cannot read blob %s for path %s",
  95                            sha1_to_hex(o->blob_sha1),
  96                            o->path);
  97                o->file = *file;
  98        }
  99        else
 100                *file = o->file;
 101}
 102
 103/*
 104 * Origin is refcounted and usually we keep the blob contents to be
 105 * reused.
 106 */
 107static inline struct origin *origin_incref(struct origin *o)
 108{
 109        if (o)
 110                o->refcnt++;
 111        return o;
 112}
 113
 114static void origin_decref(struct origin *o)
 115{
 116        if (o && --o->refcnt <= 0) {
 117                free(o->file.ptr);
 118                free(o);
 119        }
 120}
 121
 122static void drop_origin_blob(struct origin *o)
 123{
 124        if (o->file.ptr) {
 125                free(o->file.ptr);
 126                o->file.ptr = NULL;
 127        }
 128}
 129
 130/*
 131 * Each group of lines is described by a blame_entry; it can be split
 132 * as we pass blame to the parents.  They form a linked list in the
 133 * scoreboard structure, sorted by the target line number.
 134 */
 135struct blame_entry {
 136        struct blame_entry *prev;
 137        struct blame_entry *next;
 138
 139        /* the first line of this group in the final image;
 140         * internally all line numbers are 0 based.
 141         */
 142        int lno;
 143
 144        /* how many lines this group has */
 145        int num_lines;
 146
 147        /* the commit that introduced this group into the final image */
 148        struct origin *suspect;
 149
 150        /* true if the suspect is truly guilty; false while we have not
 151         * checked if the group came from one of its parents.
 152         */
 153        char guilty;
 154
 155        /* true if the entry has been scanned for copies in the current parent
 156         */
 157        char scanned;
 158
 159        /* the line number of the first line of this group in the
 160         * suspect's file; internally all line numbers are 0 based.
 161         */
 162        int s_lno;
 163
 164        /* how significant this entry is -- cached to avoid
 165         * scanning the lines over and over.
 166         */
 167        unsigned score;
 168};
 169
 170/*
 171 * The current state of the blame assignment.
 172 */
 173struct scoreboard {
 174        /* the final commit (i.e. where we started digging from) */
 175        struct commit *final;
 176        struct rev_info *revs;
 177        const char *path;
 178
 179        /*
 180         * The contents in the final image.
 181         * Used by many functions to obtain contents of the nth line,
 182         * indexed with scoreboard.lineno[blame_entry.lno].
 183         */
 184        const char *final_buf;
 185        unsigned long final_buf_size;
 186
 187        /* linked list of blames */
 188        struct blame_entry *ent;
 189
 190        /* look-up a line in the final buffer */
 191        int num_lines;
 192        int *lineno;
 193};
 194
 195static inline int same_suspect(struct origin *a, struct origin *b)
 196{
 197        if (a == b)
 198                return 1;
 199        if (a->commit != b->commit)
 200                return 0;
 201        return !strcmp(a->path, b->path);
 202}
 203
 204static void sanity_check_refcnt(struct scoreboard *);
 205
 206/*
 207 * If two blame entries that are next to each other came from
 208 * contiguous lines in the same origin (i.e. <commit, path> pair),
 209 * merge them together.
 210 */
 211static void coalesce(struct scoreboard *sb)
 212{
 213        struct blame_entry *ent, *next;
 214
 215        for (ent = sb->ent; ent && (next = ent->next); ent = next) {
 216                if (same_suspect(ent->suspect, next->suspect) &&
 217                    ent->guilty == next->guilty &&
 218                    ent->s_lno + ent->num_lines == next->s_lno) {
 219                        ent->num_lines += next->num_lines;
 220                        ent->next = next->next;
 221                        if (ent->next)
 222                                ent->next->prev = ent;
 223                        origin_decref(next->suspect);
 224                        free(next);
 225                        ent->score = 0;
 226                        next = ent; /* again */
 227                }
 228        }
 229
 230        if (DEBUG) /* sanity */
 231                sanity_check_refcnt(sb);
 232}
 233
 234/*
 235 * Given a commit and a path in it, create a new origin structure.
 236 * The callers that add blame to the scoreboard should use
 237 * get_origin() to obtain shared, refcounted copy instead of calling
 238 * this function directly.
 239 */
 240static struct origin *make_origin(struct commit *commit, const char *path)
 241{
 242        struct origin *o;
 243        o = xcalloc(1, sizeof(*o) + strlen(path) + 1);
 244        o->commit = commit;
 245        o->refcnt = 1;
 246        strcpy(o->path, path);
 247        return o;
 248}
 249
 250/*
 251 * Locate an existing origin or create a new one.
 252 */
 253static struct origin *get_origin(struct scoreboard *sb,
 254                                 struct commit *commit,
 255                                 const char *path)
 256{
 257        struct blame_entry *e;
 258
 259        for (e = sb->ent; e; e = e->next) {
 260                if (e->suspect->commit == commit &&
 261                    !strcmp(e->suspect->path, path))
 262                        return origin_incref(e->suspect);
 263        }
 264        return make_origin(commit, path);
 265}
 266
 267/*
 268 * Fill the blob_sha1 field of an origin if it hasn't, so that later
 269 * call to fill_origin_blob() can use it to locate the data.  blob_sha1
 270 * for an origin is also used to pass the blame for the entire file to
 271 * the parent to detect the case where a child's blob is identical to
 272 * that of its parent's.
 273 */
 274static int fill_blob_sha1(struct origin *origin)
 275{
 276        unsigned mode;
 277
 278        if (!is_null_sha1(origin->blob_sha1))
 279                return 0;
 280        if (get_tree_entry(origin->commit->object.sha1,
 281                           origin->path,
 282                           origin->blob_sha1, &mode))
 283                goto error_out;
 284        if (sha1_object_info(origin->blob_sha1, NULL) != OBJ_BLOB)
 285                goto error_out;
 286        return 0;
 287 error_out:
 288        hashclr(origin->blob_sha1);
 289        return -1;
 290}
 291
 292/*
 293 * We have an origin -- check if the same path exists in the
 294 * parent and return an origin structure to represent it.
 295 */
 296static struct origin *find_origin(struct scoreboard *sb,
 297                                  struct commit *parent,
 298                                  struct origin *origin)
 299{
 300        struct origin *porigin = NULL;
 301        struct diff_options diff_opts;
 302        const char *paths[2];
 303
 304        if (parent->util) {
 305                /*
 306                 * Each commit object can cache one origin in that
 307                 * commit.  This is a freestanding copy of origin and
 308                 * not refcounted.
 309                 */
 310                struct origin *cached = parent->util;
 311                if (!strcmp(cached->path, origin->path)) {
 312                        /*
 313                         * The same path between origin and its parent
 314                         * without renaming -- the most common case.
 315                         */
 316                        porigin = get_origin(sb, parent, cached->path);
 317
 318                        /*
 319                         * If the origin was newly created (i.e. get_origin
 320                         * would call make_origin if none is found in the
 321                         * scoreboard), it does not know the blob_sha1,
 322                         * so copy it.  Otherwise porigin was in the
 323                         * scoreboard and already knows blob_sha1.
 324                         */
 325                        if (porigin->refcnt == 1)
 326                                hashcpy(porigin->blob_sha1, cached->blob_sha1);
 327                        return porigin;
 328                }
 329                /* otherwise it was not very useful; free it */
 330                free(parent->util);
 331                parent->util = NULL;
 332        }
 333
 334        /* See if the origin->path is different between parent
 335         * and origin first.  Most of the time they are the
 336         * same and diff-tree is fairly efficient about this.
 337         */
 338        diff_setup(&diff_opts);
 339        DIFF_OPT_SET(&diff_opts, RECURSIVE);
 340        diff_opts.detect_rename = 0;
 341        diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;
 342        paths[0] = origin->path;
 343        paths[1] = NULL;
 344
 345        diff_tree_setup_paths(paths, &diff_opts);
 346        if (diff_setup_done(&diff_opts) < 0)
 347                die("diff-setup");
 348
 349        if (is_null_sha1(origin->commit->object.sha1))
 350                do_diff_cache(parent->tree->object.sha1, &diff_opts);
 351        else
 352                diff_tree_sha1(parent->tree->object.sha1,
 353                               origin->commit->tree->object.sha1,
 354                               "", &diff_opts);
 355        diffcore_std(&diff_opts);
 356
 357        /* It is either one entry that says "modified", or "created",
 358         * or nothing.
 359         */
 360        if (!diff_queued_diff.nr) {
 361                /* The path is the same as parent */
 362                porigin = get_origin(sb, parent, origin->path);
 363                hashcpy(porigin->blob_sha1, origin->blob_sha1);
 364        }
 365        else if (diff_queued_diff.nr != 1)
 366                die("internal error in blame::find_origin");
 367        else {
 368                struct diff_filepair *p = diff_queued_diff.queue[0];
 369                switch (p->status) {
 370                default:
 371                        die("internal error in blame::find_origin (%c)",
 372                            p->status);
 373                case 'M':
 374                        porigin = get_origin(sb, parent, origin->path);
 375                        hashcpy(porigin->blob_sha1, p->one->sha1);
 376                        break;
 377                case 'A':
 378                case 'T':
 379                        /* Did not exist in parent, or type changed */
 380                        break;
 381                }
 382        }
 383        diff_flush(&diff_opts);
 384        diff_tree_release_paths(&diff_opts);
 385        if (porigin) {
 386                /*
 387                 * Create a freestanding copy that is not part of
 388                 * the refcounted origin found in the scoreboard, and
 389                 * cache it in the commit.
 390                 */
 391                struct origin *cached;
 392
 393                cached = make_origin(porigin->commit, porigin->path);
 394                hashcpy(cached->blob_sha1, porigin->blob_sha1);
 395                parent->util = cached;
 396        }
 397        return porigin;
 398}
 399
 400/*
 401 * We have an origin -- find the path that corresponds to it in its
 402 * parent and return an origin structure to represent it.
 403 */
 404static struct origin *find_rename(struct scoreboard *sb,
 405                                  struct commit *parent,
 406                                  struct origin *origin)
 407{
 408        struct origin *porigin = NULL;
 409        struct diff_options diff_opts;
 410        int i;
 411        const char *paths[2];
 412
 413        diff_setup(&diff_opts);
 414        DIFF_OPT_SET(&diff_opts, RECURSIVE);
 415        diff_opts.detect_rename = DIFF_DETECT_RENAME;
 416        diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;
 417        diff_opts.single_follow = origin->path;
 418        paths[0] = NULL;
 419        diff_tree_setup_paths(paths, &diff_opts);
 420        if (diff_setup_done(&diff_opts) < 0)
 421                die("diff-setup");
 422
 423        if (is_null_sha1(origin->commit->object.sha1))
 424                do_diff_cache(parent->tree->object.sha1, &diff_opts);
 425        else
 426                diff_tree_sha1(parent->tree->object.sha1,
 427                               origin->commit->tree->object.sha1,
 428                               "", &diff_opts);
 429        diffcore_std(&diff_opts);
 430
 431        for (i = 0; i < diff_queued_diff.nr; i++) {
 432                struct diff_filepair *p = diff_queued_diff.queue[i];
 433                if ((p->status == 'R' || p->status == 'C') &&
 434                    !strcmp(p->two->path, origin->path)) {
 435                        porigin = get_origin(sb, parent, p->one->path);
 436                        hashcpy(porigin->blob_sha1, p->one->sha1);
 437                        break;
 438                }
 439        }
 440        diff_flush(&diff_opts);
 441        diff_tree_release_paths(&diff_opts);
 442        return porigin;
 443}
 444
 445/*
 446 * Link in a new blame entry to the scoreboard.  Entries that cover the
 447 * same line range have been removed from the scoreboard previously.
 448 */
 449static void add_blame_entry(struct scoreboard *sb, struct blame_entry *e)
 450{
 451        struct blame_entry *ent, *prev = NULL;
 452
 453        origin_incref(e->suspect);
 454
 455        for (ent = sb->ent; ent && ent->lno < e->lno; ent = ent->next)
 456                prev = ent;
 457
 458        /* prev, if not NULL, is the last one that is below e */
 459        e->prev = prev;
 460        if (prev) {
 461                e->next = prev->next;
 462                prev->next = e;
 463        }
 464        else {
 465                e->next = sb->ent;
 466                sb->ent = e;
 467        }
 468        if (e->next)
 469                e->next->prev = e;
 470}
 471
 472/*
 473 * src typically is on-stack; we want to copy the information in it to
 474 * a malloced blame_entry that is already on the linked list of the
 475 * scoreboard.  The origin of dst loses a refcnt while the origin of src
 476 * gains one.
 477 */
 478static void dup_entry(struct blame_entry *dst, struct blame_entry *src)
 479{
 480        struct blame_entry *p, *n;
 481
 482        p = dst->prev;
 483        n = dst->next;
 484        origin_incref(src->suspect);
 485        origin_decref(dst->suspect);
 486        memcpy(dst, src, sizeof(*src));
 487        dst->prev = p;
 488        dst->next = n;
 489        dst->score = 0;
 490}
 491
 492static const char *nth_line(struct scoreboard *sb, int lno)
 493{
 494        return sb->final_buf + sb->lineno[lno];
 495}
 496
 497/*
 498 * It is known that lines between tlno to same came from parent, and e
 499 * has an overlap with that range.  it also is known that parent's
 500 * line plno corresponds to e's line tlno.
 501 *
 502 *                <---- e ----->
 503 *                   <------>
 504 *                   <------------>
 505 *             <------------>
 506 *             <------------------>
 507 *
 508 * Split e into potentially three parts; before this chunk, the chunk
 509 * to be blamed for the parent, and after that portion.
 510 */
 511static void split_overlap(struct blame_entry *split,
 512                          struct blame_entry *e,
 513                          int tlno, int plno, int same,
 514                          struct origin *parent)
 515{
 516        int chunk_end_lno;
 517        memset(split, 0, sizeof(struct blame_entry [3]));
 518
 519        if (e->s_lno < tlno) {
 520                /* there is a pre-chunk part not blamed on parent */
 521                split[0].suspect = origin_incref(e->suspect);
 522                split[0].lno = e->lno;
 523                split[0].s_lno = e->s_lno;
 524                split[0].num_lines = tlno - e->s_lno;
 525                split[1].lno = e->lno + tlno - e->s_lno;
 526                split[1].s_lno = plno;
 527        }
 528        else {
 529                split[1].lno = e->lno;
 530                split[1].s_lno = plno + (e->s_lno - tlno);
 531        }
 532
 533        if (same < e->s_lno + e->num_lines) {
 534                /* there is a post-chunk part not blamed on parent */
 535                split[2].suspect = origin_incref(e->suspect);
 536                split[2].lno = e->lno + (same - e->s_lno);
 537                split[2].s_lno = e->s_lno + (same - e->s_lno);
 538                split[2].num_lines = e->s_lno + e->num_lines - same;
 539                chunk_end_lno = split[2].lno;
 540        }
 541        else
 542                chunk_end_lno = e->lno + e->num_lines;
 543        split[1].num_lines = chunk_end_lno - split[1].lno;
 544
 545        /*
 546         * if it turns out there is nothing to blame the parent for,
 547         * forget about the splitting.  !split[1].suspect signals this.
 548         */
 549        if (split[1].num_lines < 1)
 550                return;
 551        split[1].suspect = origin_incref(parent);
 552}
 553
 554/*
 555 * split_overlap() divided an existing blame e into up to three parts
 556 * in split.  Adjust the linked list of blames in the scoreboard to
 557 * reflect the split.
 558 */
 559static void split_blame(struct scoreboard *sb,
 560                        struct blame_entry *split,
 561                        struct blame_entry *e)
 562{
 563        struct blame_entry *new_entry;
 564
 565        if (split[0].suspect && split[2].suspect) {
 566                /* The first part (reuse storage for the existing entry e) */
 567                dup_entry(e, &split[0]);
 568
 569                /* The last part -- me */
 570                new_entry = xmalloc(sizeof(*new_entry));
 571                memcpy(new_entry, &(split[2]), sizeof(struct blame_entry));
 572                add_blame_entry(sb, new_entry);
 573
 574                /* ... and the middle part -- parent */
 575                new_entry = xmalloc(sizeof(*new_entry));
 576                memcpy(new_entry, &(split[1]), sizeof(struct blame_entry));
 577                add_blame_entry(sb, new_entry);
 578        }
 579        else if (!split[0].suspect && !split[2].suspect)
 580                /*
 581                 * The parent covers the entire area; reuse storage for
 582                 * e and replace it with the parent.
 583                 */
 584                dup_entry(e, &split[1]);
 585        else if (split[0].suspect) {
 586                /* me and then parent */
 587                dup_entry(e, &split[0]);
 588
 589                new_entry = xmalloc(sizeof(*new_entry));
 590                memcpy(new_entry, &(split[1]), sizeof(struct blame_entry));
 591                add_blame_entry(sb, new_entry);
 592        }
 593        else {
 594                /* parent and then me */
 595                dup_entry(e, &split[1]);
 596
 597                new_entry = xmalloc(sizeof(*new_entry));
 598                memcpy(new_entry, &(split[2]), sizeof(struct blame_entry));
 599                add_blame_entry(sb, new_entry);
 600        }
 601
 602        if (DEBUG) { /* sanity */
 603                struct blame_entry *ent;
 604                int lno = sb->ent->lno, corrupt = 0;
 605
 606                for (ent = sb->ent; ent; ent = ent->next) {
 607                        if (lno != ent->lno)
 608                                corrupt = 1;
 609                        if (ent->s_lno < 0)
 610                                corrupt = 1;
 611                        lno += ent->num_lines;
 612                }
 613                if (corrupt) {
 614                        lno = sb->ent->lno;
 615                        for (ent = sb->ent; ent; ent = ent->next) {
 616                                printf("L %8d l %8d n %8d\n",
 617                                       lno, ent->lno, ent->num_lines);
 618                                lno = ent->lno + ent->num_lines;
 619                        }
 620                        die("oops");
 621                }
 622        }
 623}
 624
 625/*
 626 * After splitting the blame, the origins used by the
 627 * on-stack blame_entry should lose one refcnt each.
 628 */
 629static void decref_split(struct blame_entry *split)
 630{
 631        int i;
 632
 633        for (i = 0; i < 3; i++)
 634                origin_decref(split[i].suspect);
 635}
 636
 637/*
 638 * Helper for blame_chunk().  blame_entry e is known to overlap with
 639 * the patch hunk; split it and pass blame to the parent.
 640 */
 641static void blame_overlap(struct scoreboard *sb, struct blame_entry *e,
 642                          int tlno, int plno, int same,
 643                          struct origin *parent)
 644{
 645        struct blame_entry split[3];
 646
 647        split_overlap(split, e, tlno, plno, same, parent);
 648        if (split[1].suspect)
 649                split_blame(sb, split, e);
 650        decref_split(split);
 651}
 652
 653/*
 654 * Find the line number of the last line the target is suspected for.
 655 */
 656static int find_last_in_target(struct scoreboard *sb, struct origin *target)
 657{
 658        struct blame_entry *e;
 659        int last_in_target = -1;
 660
 661        for (e = sb->ent; e; e = e->next) {
 662                if (e->guilty || !same_suspect(e->suspect, target))
 663                        continue;
 664                if (last_in_target < e->s_lno + e->num_lines)
 665                        last_in_target = e->s_lno + e->num_lines;
 666        }
 667        return last_in_target;
 668}
 669
 670/*
 671 * Process one hunk from the patch between the current suspect for
 672 * blame_entry e and its parent.  Find and split the overlap, and
 673 * pass blame to the overlapping part to the parent.
 674 */
 675static void blame_chunk(struct scoreboard *sb,
 676                        int tlno, int plno, int same,
 677                        struct origin *target, struct origin *parent)
 678{
 679        struct blame_entry *e;
 680
 681        for (e = sb->ent; e; e = e->next) {
 682                if (e->guilty || !same_suspect(e->suspect, target))
 683                        continue;
 684                if (same <= e->s_lno)
 685                        continue;
 686                if (tlno < e->s_lno + e->num_lines)
 687                        blame_overlap(sb, e, tlno, plno, same, parent);
 688        }
 689}
 690
 691struct blame_chunk_cb_data {
 692        struct scoreboard *sb;
 693        struct origin *target;
 694        struct origin *parent;
 695        long plno;
 696        long tlno;
 697};
 698
 699static void blame_chunk_cb(void *data, long same, long p_next, long t_next)
 700{
 701        struct blame_chunk_cb_data *d = data;
 702        blame_chunk(d->sb, d->tlno, d->plno, same, d->target, d->parent);
 703        d->plno = p_next;
 704        d->tlno = t_next;
 705}
 706
 707/*
 708 * We are looking at the origin 'target' and aiming to pass blame
 709 * for the lines it is suspected to its parent.  Run diff to find
 710 * which lines came from parent and pass blame for them.
 711 */
 712static int pass_blame_to_parent(struct scoreboard *sb,
 713                                struct origin *target,
 714                                struct origin *parent)
 715{
 716        int last_in_target;
 717        mmfile_t file_p, file_o;
 718        struct blame_chunk_cb_data d = { sb, target, parent, 0, 0 };
 719        xpparam_t xpp;
 720        xdemitconf_t xecfg;
 721
 722        last_in_target = find_last_in_target(sb, target);
 723        if (last_in_target < 0)
 724                return 1; /* nothing remains for this target */
 725
 726        fill_origin_blob(parent, &file_p);
 727        fill_origin_blob(target, &file_o);
 728        num_get_patch++;
 729
 730        memset(&xpp, 0, sizeof(xpp));
 731        xpp.flags = xdl_opts;
 732        memset(&xecfg, 0, sizeof(xecfg));
 733        xecfg.ctxlen = 0;
 734        xdi_diff_hunks(&file_p, &file_o, blame_chunk_cb, &d, &xpp, &xecfg);
 735        /* The rest (i.e. anything after tlno) are the same as the parent */
 736        blame_chunk(sb, d.tlno, d.plno, last_in_target, target, parent);
 737
 738        return 0;
 739}
 740
 741/*
 742 * The lines in blame_entry after splitting blames many times can become
 743 * very small and trivial, and at some point it becomes pointless to
 744 * blame the parents.  E.g. "\t\t}\n\t}\n\n" appears everywhere in any
 745 * ordinary C program, and it is not worth to say it was copied from
 746 * totally unrelated file in the parent.
 747 *
 748 * Compute how trivial the lines in the blame_entry are.
 749 */
 750static unsigned ent_score(struct scoreboard *sb, struct blame_entry *e)
 751{
 752        unsigned score;
 753        const char *cp, *ep;
 754
 755        if (e->score)
 756                return e->score;
 757
 758        score = 1;
 759        cp = nth_line(sb, e->lno);
 760        ep = nth_line(sb, e->lno + e->num_lines);
 761        while (cp < ep) {
 762                unsigned ch = *((unsigned char *)cp);
 763                if (isalnum(ch))
 764                        score++;
 765                cp++;
 766        }
 767        e->score = score;
 768        return score;
 769}
 770
 771/*
 772 * best_so_far[] and this[] are both a split of an existing blame_entry
 773 * that passes blame to the parent.  Maintain best_so_far the best split
 774 * so far, by comparing this and best_so_far and copying this into
 775 * bst_so_far as needed.
 776 */
 777static void copy_split_if_better(struct scoreboard *sb,
 778                                 struct blame_entry *best_so_far,
 779                                 struct blame_entry *this)
 780{
 781        int i;
 782
 783        if (!this[1].suspect)
 784                return;
 785        if (best_so_far[1].suspect) {
 786                if (ent_score(sb, &this[1]) < ent_score(sb, &best_so_far[1]))
 787                        return;
 788        }
 789
 790        for (i = 0; i < 3; i++)
 791                origin_incref(this[i].suspect);
 792        decref_split(best_so_far);
 793        memcpy(best_so_far, this, sizeof(struct blame_entry [3]));
 794}
 795
 796/*
 797 * We are looking at a part of the final image represented by
 798 * ent (tlno and same are offset by ent->s_lno).
 799 * tlno is where we are looking at in the final image.
 800 * up to (but not including) same match preimage.
 801 * plno is where we are looking at in the preimage.
 802 *
 803 * <-------------- final image ---------------------->
 804 *       <------ent------>
 805 *         ^tlno ^same
 806 *    <---------preimage----->
 807 *         ^plno
 808 *
 809 * All line numbers are 0-based.
 810 */
 811static void handle_split(struct scoreboard *sb,
 812                         struct blame_entry *ent,
 813                         int tlno, int plno, int same,
 814                         struct origin *parent,
 815                         struct blame_entry *split)
 816{
 817        if (ent->num_lines <= tlno)
 818                return;
 819        if (tlno < same) {
 820                struct blame_entry this[3];
 821                tlno += ent->s_lno;
 822                same += ent->s_lno;
 823                split_overlap(this, ent, tlno, plno, same, parent);
 824                copy_split_if_better(sb, split, this);
 825                decref_split(this);
 826        }
 827}
 828
 829struct handle_split_cb_data {
 830        struct scoreboard *sb;
 831        struct blame_entry *ent;
 832        struct origin *parent;
 833        struct blame_entry *split;
 834        long plno;
 835        long tlno;
 836};
 837
 838static void handle_split_cb(void *data, long same, long p_next, long t_next)
 839{
 840        struct handle_split_cb_data *d = data;
 841        handle_split(d->sb, d->ent, d->tlno, d->plno, same, d->parent, d->split);
 842        d->plno = p_next;
 843        d->tlno = t_next;
 844}
 845
 846/*
 847 * Find the lines from parent that are the same as ent so that
 848 * we can pass blames to it.  file_p has the blob contents for
 849 * the parent.
 850 */
 851static void find_copy_in_blob(struct scoreboard *sb,
 852                              struct blame_entry *ent,
 853                              struct origin *parent,
 854                              struct blame_entry *split,
 855                              mmfile_t *file_p)
 856{
 857        const char *cp;
 858        int cnt;
 859        mmfile_t file_o;
 860        struct handle_split_cb_data d = { sb, ent, parent, split, 0, 0 };
 861        xpparam_t xpp;
 862        xdemitconf_t xecfg;
 863
 864        /*
 865         * Prepare mmfile that contains only the lines in ent.
 866         */
 867        cp = nth_line(sb, ent->lno);
 868        file_o.ptr = (char*) cp;
 869        cnt = ent->num_lines;
 870
 871        while (cnt && cp < sb->final_buf + sb->final_buf_size) {
 872                if (*cp++ == '\n')
 873                        cnt--;
 874        }
 875        file_o.size = cp - file_o.ptr;
 876
 877        /*
 878         * file_o is a part of final image we are annotating.
 879         * file_p partially may match that image.
 880         */
 881        memset(&xpp, 0, sizeof(xpp));
 882        xpp.flags = xdl_opts;
 883        memset(&xecfg, 0, sizeof(xecfg));
 884        xecfg.ctxlen = 1;
 885        memset(split, 0, sizeof(struct blame_entry [3]));
 886        xdi_diff_hunks(file_p, &file_o, handle_split_cb, &d, &xpp, &xecfg);
 887        /* remainder, if any, all match the preimage */
 888        handle_split(sb, ent, d.tlno, d.plno, ent->num_lines, parent, split);
 889}
 890
 891/*
 892 * See if lines currently target is suspected for can be attributed to
 893 * parent.
 894 */
 895static int find_move_in_parent(struct scoreboard *sb,
 896                               struct origin *target,
 897                               struct origin *parent)
 898{
 899        int last_in_target, made_progress;
 900        struct blame_entry *e, split[3];
 901        mmfile_t file_p;
 902
 903        last_in_target = find_last_in_target(sb, target);
 904        if (last_in_target < 0)
 905                return 1; /* nothing remains for this target */
 906
 907        fill_origin_blob(parent, &file_p);
 908        if (!file_p.ptr)
 909                return 0;
 910
 911        made_progress = 1;
 912        while (made_progress) {
 913                made_progress = 0;
 914                for (e = sb->ent; e; e = e->next) {
 915                        if (e->guilty || !same_suspect(e->suspect, target) ||
 916                            ent_score(sb, e) < blame_move_score)
 917                                continue;
 918                        find_copy_in_blob(sb, e, parent, split, &file_p);
 919                        if (split[1].suspect &&
 920                            blame_move_score < ent_score(sb, &split[1])) {
 921                                split_blame(sb, split, e);
 922                                made_progress = 1;
 923                        }
 924                        decref_split(split);
 925                }
 926        }
 927        return 0;
 928}
 929
 930struct blame_list {
 931        struct blame_entry *ent;
 932        struct blame_entry split[3];
 933};
 934
 935/*
 936 * Count the number of entries the target is suspected for,
 937 * and prepare a list of entry and the best split.
 938 */
 939static struct blame_list *setup_blame_list(struct scoreboard *sb,
 940                                           struct origin *target,
 941                                           int min_score,
 942                                           int *num_ents_p)
 943{
 944        struct blame_entry *e;
 945        int num_ents, i;
 946        struct blame_list *blame_list = NULL;
 947
 948        for (e = sb->ent, num_ents = 0; e; e = e->next)
 949                if (!e->scanned && !e->guilty &&
 950                    same_suspect(e->suspect, target) &&
 951                    min_score < ent_score(sb, e))
 952                        num_ents++;
 953        if (num_ents) {
 954                blame_list = xcalloc(num_ents, sizeof(struct blame_list));
 955                for (e = sb->ent, i = 0; e; e = e->next)
 956                        if (!e->scanned && !e->guilty &&
 957                            same_suspect(e->suspect, target) &&
 958                            min_score < ent_score(sb, e))
 959                                blame_list[i++].ent = e;
 960        }
 961        *num_ents_p = num_ents;
 962        return blame_list;
 963}
 964
 965/*
 966 * Reset the scanned status on all entries.
 967 */
 968static void reset_scanned_flag(struct scoreboard *sb)
 969{
 970        struct blame_entry *e;
 971        for (e = sb->ent; e; e = e->next)
 972                e->scanned = 0;
 973}
 974
 975/*
 976 * For lines target is suspected for, see if we can find code movement
 977 * across file boundary from the parent commit.  porigin is the path
 978 * in the parent we already tried.
 979 */
 980static int find_copy_in_parent(struct scoreboard *sb,
 981                               struct origin *target,
 982                               struct commit *parent,
 983                               struct origin *porigin,
 984                               int opt)
 985{
 986        struct diff_options diff_opts;
 987        const char *paths[1];
 988        int i, j;
 989        int retval;
 990        struct blame_list *blame_list;
 991        int num_ents;
 992
 993        blame_list = setup_blame_list(sb, target, blame_copy_score, &num_ents);
 994        if (!blame_list)
 995                return 1; /* nothing remains for this target */
 996
 997        diff_setup(&diff_opts);
 998        DIFF_OPT_SET(&diff_opts, RECURSIVE);
 999        diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;
1000
1001        paths[0] = NULL;
1002        diff_tree_setup_paths(paths, &diff_opts);
1003        if (diff_setup_done(&diff_opts) < 0)
1004                die("diff-setup");
1005
1006        /* Try "find copies harder" on new path if requested;
1007         * we do not want to use diffcore_rename() actually to
1008         * match things up; find_copies_harder is set only to
1009         * force diff_tree_sha1() to feed all filepairs to diff_queue,
1010         * and this code needs to be after diff_setup_done(), which
1011         * usually makes find-copies-harder imply copy detection.
1012         */
1013        if ((opt & PICKAXE_BLAME_COPY_HARDEST)
1014            || ((opt & PICKAXE_BLAME_COPY_HARDER)
1015                && (!porigin || strcmp(target->path, porigin->path))))
1016                DIFF_OPT_SET(&diff_opts, FIND_COPIES_HARDER);
1017
1018        if (is_null_sha1(target->commit->object.sha1))
1019                do_diff_cache(parent->tree->object.sha1, &diff_opts);
1020        else
1021                diff_tree_sha1(parent->tree->object.sha1,
1022                               target->commit->tree->object.sha1,
1023                               "", &diff_opts);
1024
1025        if (!DIFF_OPT_TST(&diff_opts, FIND_COPIES_HARDER))
1026                diffcore_std(&diff_opts);
1027
1028        retval = 0;
1029        while (1) {
1030                int made_progress = 0;
1031
1032                for (i = 0; i < diff_queued_diff.nr; i++) {
1033                        struct diff_filepair *p = diff_queued_diff.queue[i];
1034                        struct origin *norigin;
1035                        mmfile_t file_p;
1036                        struct blame_entry this[3];
1037
1038                        if (!DIFF_FILE_VALID(p->one))
1039                                continue; /* does not exist in parent */
1040                        if (S_ISGITLINK(p->one->mode))
1041                                continue; /* ignore git links */
1042                        if (porigin && !strcmp(p->one->path, porigin->path))
1043                                /* find_move already dealt with this path */
1044                                continue;
1045
1046                        norigin = get_origin(sb, parent, p->one->path);
1047                        hashcpy(norigin->blob_sha1, p->one->sha1);
1048                        fill_origin_blob(norigin, &file_p);
1049                        if (!file_p.ptr)
1050                                continue;
1051
1052                        for (j = 0; j < num_ents; j++) {
1053                                find_copy_in_blob(sb, blame_list[j].ent,
1054                                                  norigin, this, &file_p);
1055                                copy_split_if_better(sb, blame_list[j].split,
1056                                                     this);
1057                                decref_split(this);
1058                        }
1059                        origin_decref(norigin);
1060                }
1061
1062                for (j = 0; j < num_ents; j++) {
1063                        struct blame_entry *split = blame_list[j].split;
1064                        if (split[1].suspect &&
1065                            blame_copy_score < ent_score(sb, &split[1])) {
1066                                split_blame(sb, split, blame_list[j].ent);
1067                                made_progress = 1;
1068                        }
1069                        else
1070                                blame_list[j].ent->scanned = 1;
1071                        decref_split(split);
1072                }
1073                free(blame_list);
1074
1075                if (!made_progress)
1076                        break;
1077                blame_list = setup_blame_list(sb, target, blame_copy_score, &num_ents);
1078                if (!blame_list) {
1079                        retval = 1;
1080                        break;
1081                }
1082        }
1083        reset_scanned_flag(sb);
1084        diff_flush(&diff_opts);
1085        diff_tree_release_paths(&diff_opts);
1086        return retval;
1087}
1088
1089/*
1090 * The blobs of origin and porigin exactly match, so everything
1091 * origin is suspected for can be blamed on the parent.
1092 */
1093static void pass_whole_blame(struct scoreboard *sb,
1094                             struct origin *origin, struct origin *porigin)
1095{
1096        struct blame_entry *e;
1097
1098        if (!porigin->file.ptr && origin->file.ptr) {
1099                /* Steal its file */
1100                porigin->file = origin->file;
1101                origin->file.ptr = NULL;
1102        }
1103        for (e = sb->ent; e; e = e->next) {
1104                if (!same_suspect(e->suspect, origin))
1105                        continue;
1106                origin_incref(porigin);
1107                origin_decref(e->suspect);
1108                e->suspect = porigin;
1109        }
1110}
1111
1112/*
1113 * We pass blame from the current commit to its parents.  We keep saying
1114 * "parent" (and "porigin"), but what we mean is to find scapegoat to
1115 * exonerate ourselves.
1116 */
1117static struct commit_list *first_scapegoat(struct rev_info *revs, struct commit *commit)
1118{
1119        if (!reverse)
1120                return commit->parents;
1121        return lookup_decoration(&revs->children, &commit->object);
1122}
1123
1124static int num_scapegoats(struct rev_info *revs, struct commit *commit)
1125{
1126        int cnt;
1127        struct commit_list *l = first_scapegoat(revs, commit);
1128        for (cnt = 0; l; l = l->next)
1129                cnt++;
1130        return cnt;
1131}
1132
1133#define MAXSG 16
1134
1135static void pass_blame(struct scoreboard *sb, struct origin *origin, int opt)
1136{
1137        struct rev_info *revs = sb->revs;
1138        int i, pass, num_sg;
1139        struct commit *commit = origin->commit;
1140        struct commit_list *sg;
1141        struct origin *sg_buf[MAXSG];
1142        struct origin *porigin, **sg_origin = sg_buf;
1143
1144        num_sg = num_scapegoats(revs, commit);
1145        if (!num_sg)
1146                goto finish;
1147        else if (num_sg < ARRAY_SIZE(sg_buf))
1148                memset(sg_buf, 0, sizeof(sg_buf));
1149        else
1150                sg_origin = xcalloc(num_sg, sizeof(*sg_origin));
1151
1152        /*
1153         * The first pass looks for unrenamed path to optimize for
1154         * common cases, then we look for renames in the second pass.
1155         */
1156        for (pass = 0; pass < 2; pass++) {
1157                struct origin *(*find)(struct scoreboard *,
1158                                       struct commit *, struct origin *);
1159                find = pass ? find_rename : find_origin;
1160
1161                for (i = 0, sg = first_scapegoat(revs, commit);
1162                     i < num_sg && sg;
1163                     sg = sg->next, i++) {
1164                        struct commit *p = sg->item;
1165                        int j, same;
1166
1167                        if (sg_origin[i])
1168                                continue;
1169                        if (parse_commit(p))
1170                                continue;
1171                        porigin = find(sb, p, origin);
1172                        if (!porigin)
1173                                continue;
1174                        if (!hashcmp(porigin->blob_sha1, origin->blob_sha1)) {
1175                                pass_whole_blame(sb, origin, porigin);
1176                                origin_decref(porigin);
1177                                goto finish;
1178                        }
1179                        for (j = same = 0; j < i; j++)
1180                                if (sg_origin[j] &&
1181                                    !hashcmp(sg_origin[j]->blob_sha1,
1182                                             porigin->blob_sha1)) {
1183                                        same = 1;
1184                                        break;
1185                                }
1186                        if (!same)
1187                                sg_origin[i] = porigin;
1188                        else
1189                                origin_decref(porigin);
1190                }
1191        }
1192
1193        num_commits++;
1194        for (i = 0, sg = first_scapegoat(revs, commit);
1195             i < num_sg && sg;
1196             sg = sg->next, i++) {
1197                struct origin *porigin = sg_origin[i];
1198                if (!porigin)
1199                        continue;
1200                if (pass_blame_to_parent(sb, origin, porigin))
1201                        goto finish;
1202        }
1203
1204        /*
1205         * Optionally find moves in parents' files.
1206         */
1207        if (opt & PICKAXE_BLAME_MOVE)
1208                for (i = 0, sg = first_scapegoat(revs, commit);
1209                     i < num_sg && sg;
1210                     sg = sg->next, i++) {
1211                        struct origin *porigin = sg_origin[i];
1212                        if (!porigin)
1213                                continue;
1214                        if (find_move_in_parent(sb, origin, porigin))
1215                                goto finish;
1216                }
1217
1218        /*
1219         * Optionally find copies from parents' files.
1220         */
1221        if (opt & PICKAXE_BLAME_COPY)
1222                for (i = 0, sg = first_scapegoat(revs, commit);
1223                     i < num_sg && sg;
1224                     sg = sg->next, i++) {
1225                        struct origin *porigin = sg_origin[i];
1226                        if (find_copy_in_parent(sb, origin, sg->item,
1227                                                porigin, opt))
1228                                goto finish;
1229                }
1230
1231 finish:
1232        for (i = 0; i < num_sg; i++) {
1233                if (sg_origin[i]) {
1234                        drop_origin_blob(sg_origin[i]);
1235                        origin_decref(sg_origin[i]);
1236                }
1237        }
1238        drop_origin_blob(origin);
1239        if (sg_buf != sg_origin)
1240                free(sg_origin);
1241}
1242
1243/*
1244 * Information on commits, used for output.
1245 */
1246struct commit_info
1247{
1248        const char *author;
1249        const char *author_mail;
1250        unsigned long author_time;
1251        const char *author_tz;
1252
1253        /* filled only when asked for details */
1254        const char *committer;
1255        const char *committer_mail;
1256        unsigned long committer_time;
1257        const char *committer_tz;
1258
1259        const char *summary;
1260};
1261
1262/*
1263 * Parse author/committer line in the commit object buffer
1264 */
1265static void get_ac_line(const char *inbuf, const char *what,
1266                        int bufsz, char *person, const char **mail,
1267                        unsigned long *time, const char **tz)
1268{
1269        int len, tzlen, maillen;
1270        char *tmp, *endp, *timepos;
1271
1272        tmp = strstr(inbuf, what);
1273        if (!tmp)
1274                goto error_out;
1275        tmp += strlen(what);
1276        endp = strchr(tmp, '\n');
1277        if (!endp)
1278                len = strlen(tmp);
1279        else
1280                len = endp - tmp;
1281        if (bufsz <= len) {
1282        error_out:
1283                /* Ugh */
1284                *mail = *tz = "(unknown)";
1285                *time = 0;
1286                return;
1287        }
1288        memcpy(person, tmp, len);
1289
1290        tmp = person;
1291        tmp += len;
1292        *tmp = 0;
1293        while (*tmp != ' ')
1294                tmp--;
1295        *tz = tmp+1;
1296        tzlen = (person+len)-(tmp+1);
1297
1298        *tmp = 0;
1299        while (*tmp != ' ')
1300                tmp--;
1301        *time = strtoul(tmp, NULL, 10);
1302        timepos = tmp;
1303
1304        *tmp = 0;
1305        while (*tmp != ' ')
1306                tmp--;
1307        *mail = tmp + 1;
1308        *tmp = 0;
1309        maillen = timepos - tmp;
1310
1311        if (!mailmap.nr)
1312                return;
1313
1314        /*
1315         * mailmap expansion may make the name longer.
1316         * make room by pushing stuff down.
1317         */
1318        tmp = person + bufsz - (tzlen + 1);
1319        memmove(tmp, *tz, tzlen);
1320        tmp[tzlen] = 0;
1321        *tz = tmp;
1322
1323        tmp = tmp - (maillen + 1);
1324        memmove(tmp, *mail, maillen);
1325        tmp[maillen] = 0;
1326        *mail = tmp;
1327
1328        /*
1329         * Now, convert e-mail using mailmap
1330         */
1331        map_email(&mailmap, tmp + 1, person, tmp-person-1);
1332}
1333
1334static void get_commit_info(struct commit *commit,
1335                            struct commit_info *ret,
1336                            int detailed)
1337{
1338        int len;
1339        char *tmp, *endp;
1340        static char author_buf[1024];
1341        static char committer_buf[1024];
1342        static char summary_buf[1024];
1343
1344        /*
1345         * We've operated without save_commit_buffer, so
1346         * we now need to populate them for output.
1347         */
1348        if (!commit->buffer) {
1349                enum object_type type;
1350                unsigned long size;
1351                commit->buffer =
1352                        read_sha1_file(commit->object.sha1, &type, &size);
1353                if (!commit->buffer)
1354                        die("Cannot read commit %s",
1355                            sha1_to_hex(commit->object.sha1));
1356        }
1357        ret->author = author_buf;
1358        get_ac_line(commit->buffer, "\nauthor ",
1359                    sizeof(author_buf), author_buf, &ret->author_mail,
1360                    &ret->author_time, &ret->author_tz);
1361
1362        if (!detailed)
1363                return;
1364
1365        ret->committer = committer_buf;
1366        get_ac_line(commit->buffer, "\ncommitter ",
1367                    sizeof(committer_buf), committer_buf, &ret->committer_mail,
1368                    &ret->committer_time, &ret->committer_tz);
1369
1370        ret->summary = summary_buf;
1371        tmp = strstr(commit->buffer, "\n\n");
1372        if (!tmp) {
1373        error_out:
1374                sprintf(summary_buf, "(%s)", sha1_to_hex(commit->object.sha1));
1375                return;
1376        }
1377        tmp += 2;
1378        endp = strchr(tmp, '\n');
1379        if (!endp)
1380                endp = tmp + strlen(tmp);
1381        len = endp - tmp;
1382        if (len >= sizeof(summary_buf) || len == 0)
1383                goto error_out;
1384        memcpy(summary_buf, tmp, len);
1385        summary_buf[len] = 0;
1386}
1387
1388/*
1389 * To allow LF and other nonportable characters in pathnames,
1390 * they are c-style quoted as needed.
1391 */
1392static void write_filename_info(const char *path)
1393{
1394        printf("filename ");
1395        write_name_quoted(path, stdout, '\n');
1396}
1397
1398/*
1399 * The blame_entry is found to be guilty for the range.  Mark it
1400 * as such, and show it in incremental output.
1401 */
1402static void found_guilty_entry(struct blame_entry *ent)
1403{
1404        if (ent->guilty)
1405                return;
1406        ent->guilty = 1;
1407        if (incremental) {
1408                struct origin *suspect = ent->suspect;
1409
1410                printf("%s %d %d %d\n",
1411                       sha1_to_hex(suspect->commit->object.sha1),
1412                       ent->s_lno + 1, ent->lno + 1, ent->num_lines);
1413                if (!(suspect->commit->object.flags & METAINFO_SHOWN)) {
1414                        struct commit_info ci;
1415                        suspect->commit->object.flags |= METAINFO_SHOWN;
1416                        get_commit_info(suspect->commit, &ci, 1);
1417                        printf("author %s\n", ci.author);
1418                        printf("author-mail %s\n", ci.author_mail);
1419                        printf("author-time %lu\n", ci.author_time);
1420                        printf("author-tz %s\n", ci.author_tz);
1421                        printf("committer %s\n", ci.committer);
1422                        printf("committer-mail %s\n", ci.committer_mail);
1423                        printf("committer-time %lu\n", ci.committer_time);
1424                        printf("committer-tz %s\n", ci.committer_tz);
1425                        printf("summary %s\n", ci.summary);
1426                        if (suspect->commit->object.flags & UNINTERESTING)
1427                                printf("boundary\n");
1428                }
1429                write_filename_info(suspect->path);
1430                maybe_flush_or_die(stdout, "stdout");
1431        }
1432}
1433
1434/*
1435 * The main loop -- while the scoreboard has lines whose true origin
1436 * is still unknown, pick one blame_entry, and allow its current
1437 * suspect to pass blames to its parents.
1438 */
1439static void assign_blame(struct scoreboard *sb, int opt)
1440{
1441        struct rev_info *revs = sb->revs;
1442
1443        while (1) {
1444                struct blame_entry *ent;
1445                struct commit *commit;
1446                struct origin *suspect = NULL;
1447
1448                /* find one suspect to break down */
1449                for (ent = sb->ent; !suspect && ent; ent = ent->next)
1450                        if (!ent->guilty)
1451                                suspect = ent->suspect;
1452                if (!suspect)
1453                        return; /* all done */
1454
1455                /*
1456                 * We will use this suspect later in the loop,
1457                 * so hold onto it in the meantime.
1458                 */
1459                origin_incref(suspect);
1460                commit = suspect->commit;
1461                if (!commit->object.parsed)
1462                        parse_commit(commit);
1463                if (reverse ||
1464                    (!(commit->object.flags & UNINTERESTING) &&
1465                     !(revs->max_age != -1 && commit->date < revs->max_age)))
1466                        pass_blame(sb, suspect, opt);
1467                else {
1468                        commit->object.flags |= UNINTERESTING;
1469                        if (commit->object.parsed)
1470                                mark_parents_uninteresting(commit);
1471                }
1472                /* treat root commit as boundary */
1473                if (!commit->parents && !show_root)
1474                        commit->object.flags |= UNINTERESTING;
1475
1476                /* Take responsibility for the remaining entries */
1477                for (ent = sb->ent; ent; ent = ent->next)
1478                        if (same_suspect(ent->suspect, suspect))
1479                                found_guilty_entry(ent);
1480                origin_decref(suspect);
1481
1482                if (DEBUG) /* sanity */
1483                        sanity_check_refcnt(sb);
1484        }
1485}
1486
1487static const char *format_time(unsigned long time, const char *tz_str,
1488                               int show_raw_time)
1489{
1490        static char time_buf[128];
1491        time_t t = time;
1492        int minutes, tz;
1493        struct tm *tm;
1494
1495        if (show_raw_time) {
1496                sprintf(time_buf, "%lu %s", time, tz_str);
1497                return time_buf;
1498        }
1499
1500        tz = atoi(tz_str);
1501        minutes = tz < 0 ? -tz : tz;
1502        minutes = (minutes / 100)*60 + (minutes % 100);
1503        minutes = tz < 0 ? -minutes : minutes;
1504        t = time + minutes * 60;
1505        tm = gmtime(&t);
1506
1507        strftime(time_buf, sizeof(time_buf), "%Y-%m-%d %H:%M:%S ", tm);
1508        strcat(time_buf, tz_str);
1509        return time_buf;
1510}
1511
1512#define OUTPUT_ANNOTATE_COMPAT  001
1513#define OUTPUT_LONG_OBJECT_NAME 002
1514#define OUTPUT_RAW_TIMESTAMP    004
1515#define OUTPUT_PORCELAIN        010
1516#define OUTPUT_SHOW_NAME        020
1517#define OUTPUT_SHOW_NUMBER      040
1518#define OUTPUT_SHOW_SCORE      0100
1519#define OUTPUT_NO_AUTHOR       0200
1520
1521static void emit_porcelain(struct scoreboard *sb, struct blame_entry *ent)
1522{
1523        int cnt;
1524        const char *cp;
1525        struct origin *suspect = ent->suspect;
1526        char hex[41];
1527
1528        strcpy(hex, sha1_to_hex(suspect->commit->object.sha1));
1529        printf("%s%c%d %d %d\n",
1530               hex,
1531               ent->guilty ? ' ' : '*', // purely for debugging
1532               ent->s_lno + 1,
1533               ent->lno + 1,
1534               ent->num_lines);
1535        if (!(suspect->commit->object.flags & METAINFO_SHOWN)) {
1536                struct commit_info ci;
1537                suspect->commit->object.flags |= METAINFO_SHOWN;
1538                get_commit_info(suspect->commit, &ci, 1);
1539                printf("author %s\n", ci.author);
1540                printf("author-mail %s\n", ci.author_mail);
1541                printf("author-time %lu\n", ci.author_time);
1542                printf("author-tz %s\n", ci.author_tz);
1543                printf("committer %s\n", ci.committer);
1544                printf("committer-mail %s\n", ci.committer_mail);
1545                printf("committer-time %lu\n", ci.committer_time);
1546                printf("committer-tz %s\n", ci.committer_tz);
1547                write_filename_info(suspect->path);
1548                printf("summary %s\n", ci.summary);
1549                if (suspect->commit->object.flags & UNINTERESTING)
1550                        printf("boundary\n");
1551        }
1552        else if (suspect->commit->object.flags & MORE_THAN_ONE_PATH)
1553                write_filename_info(suspect->path);
1554
1555        cp = nth_line(sb, ent->lno);
1556        for (cnt = 0; cnt < ent->num_lines; cnt++) {
1557                char ch;
1558                if (cnt)
1559                        printf("%s %d %d\n", hex,
1560                               ent->s_lno + 1 + cnt,
1561                               ent->lno + 1 + cnt);
1562                putchar('\t');
1563                do {
1564                        ch = *cp++;
1565                        putchar(ch);
1566                } while (ch != '\n' &&
1567                         cp < sb->final_buf + sb->final_buf_size);
1568        }
1569}
1570
1571static void emit_other(struct scoreboard *sb, struct blame_entry *ent, int opt)
1572{
1573        int cnt;
1574        const char *cp;
1575        struct origin *suspect = ent->suspect;
1576        struct commit_info ci;
1577        char hex[41];
1578        int show_raw_time = !!(opt & OUTPUT_RAW_TIMESTAMP);
1579
1580        get_commit_info(suspect->commit, &ci, 1);
1581        strcpy(hex, sha1_to_hex(suspect->commit->object.sha1));
1582
1583        cp = nth_line(sb, ent->lno);
1584        for (cnt = 0; cnt < ent->num_lines; cnt++) {
1585                char ch;
1586                int length = (opt & OUTPUT_LONG_OBJECT_NAME) ? 40 : 8;
1587
1588                if (suspect->commit->object.flags & UNINTERESTING) {
1589                        if (blank_boundary)
1590                                memset(hex, ' ', length);
1591                        else if (!(opt & OUTPUT_ANNOTATE_COMPAT)) {
1592                                length--;
1593                                putchar('^');
1594                        }
1595                }
1596
1597                printf("%.*s", length, hex);
1598                if (opt & OUTPUT_ANNOTATE_COMPAT)
1599                        printf("\t(%10s\t%10s\t%d)", ci.author,
1600                               format_time(ci.author_time, ci.author_tz,
1601                                           show_raw_time),
1602                               ent->lno + 1 + cnt);
1603                else {
1604                        if (opt & OUTPUT_SHOW_SCORE)
1605                                printf(" %*d %02d",
1606                                       max_score_digits, ent->score,
1607                                       ent->suspect->refcnt);
1608                        if (opt & OUTPUT_SHOW_NAME)
1609                                printf(" %-*.*s", longest_file, longest_file,
1610                                       suspect->path);
1611                        if (opt & OUTPUT_SHOW_NUMBER)
1612                                printf(" %*d", max_orig_digits,
1613                                       ent->s_lno + 1 + cnt);
1614
1615                        if (!(opt & OUTPUT_NO_AUTHOR))
1616                                printf(" (%-*.*s %10s",
1617                                       longest_author, longest_author,
1618                                       ci.author,
1619                                       format_time(ci.author_time,
1620                                                   ci.author_tz,
1621                                                   show_raw_time));
1622                        printf(" %*d) ",
1623                               max_digits, ent->lno + 1 + cnt);
1624                }
1625                do {
1626                        ch = *cp++;
1627                        putchar(ch);
1628                } while (ch != '\n' &&
1629                         cp < sb->final_buf + sb->final_buf_size);
1630        }
1631}
1632
1633static void output(struct scoreboard *sb, int option)
1634{
1635        struct blame_entry *ent;
1636
1637        if (option & OUTPUT_PORCELAIN) {
1638                for (ent = sb->ent; ent; ent = ent->next) {
1639                        struct blame_entry *oth;
1640                        struct origin *suspect = ent->suspect;
1641                        struct commit *commit = suspect->commit;
1642                        if (commit->object.flags & MORE_THAN_ONE_PATH)
1643                                continue;
1644                        for (oth = ent->next; oth; oth = oth->next) {
1645                                if ((oth->suspect->commit != commit) ||
1646                                    !strcmp(oth->suspect->path, suspect->path))
1647                                        continue;
1648                                commit->object.flags |= MORE_THAN_ONE_PATH;
1649                                break;
1650                        }
1651                }
1652        }
1653
1654        for (ent = sb->ent; ent; ent = ent->next) {
1655                if (option & OUTPUT_PORCELAIN)
1656                        emit_porcelain(sb, ent);
1657                else {
1658                        emit_other(sb, ent, option);
1659                }
1660        }
1661}
1662
1663/*
1664 * To allow quick access to the contents of nth line in the
1665 * final image, prepare an index in the scoreboard.
1666 */
1667static int prepare_lines(struct scoreboard *sb)
1668{
1669        const char *buf = sb->final_buf;
1670        unsigned long len = sb->final_buf_size;
1671        int num = 0, incomplete = 0, bol = 1;
1672
1673        if (len && buf[len-1] != '\n')
1674                incomplete++; /* incomplete line at the end */
1675        while (len--) {
1676                if (bol) {
1677                        sb->lineno = xrealloc(sb->lineno,
1678                                              sizeof(int* ) * (num + 1));
1679                        sb->lineno[num] = buf - sb->final_buf;
1680                        bol = 0;
1681                }
1682                if (*buf++ == '\n') {
1683                        num++;
1684                        bol = 1;
1685                }
1686        }
1687        sb->lineno = xrealloc(sb->lineno,
1688                              sizeof(int* ) * (num + incomplete + 1));
1689        sb->lineno[num + incomplete] = buf - sb->final_buf;
1690        sb->num_lines = num + incomplete;
1691        return sb->num_lines;
1692}
1693
1694/*
1695 * Add phony grafts for use with -S; this is primarily to
1696 * support git's cvsserver that wants to give a linear history
1697 * to its clients.
1698 */
1699static int read_ancestry(const char *graft_file)
1700{
1701        FILE *fp = fopen(graft_file, "r");
1702        char buf[1024];
1703        if (!fp)
1704                return -1;
1705        while (fgets(buf, sizeof(buf), fp)) {
1706                /* The format is just "Commit Parent1 Parent2 ...\n" */
1707                int len = strlen(buf);
1708                struct commit_graft *graft = read_graft_line(buf, len);
1709                if (graft)
1710                        register_commit_graft(graft, 0);
1711        }
1712        fclose(fp);
1713        return 0;
1714}
1715
1716/*
1717 * How many columns do we need to show line numbers in decimal?
1718 */
1719static int lineno_width(int lines)
1720{
1721        int i, width;
1722
1723        for (width = 1, i = 10; i <= lines + 1; width++)
1724                i *= 10;
1725        return width;
1726}
1727
1728/*
1729 * How many columns do we need to show line numbers, authors,
1730 * and filenames?
1731 */
1732static void find_alignment(struct scoreboard *sb, int *option)
1733{
1734        int longest_src_lines = 0;
1735        int longest_dst_lines = 0;
1736        unsigned largest_score = 0;
1737        struct blame_entry *e;
1738
1739        for (e = sb->ent; e; e = e->next) {
1740                struct origin *suspect = e->suspect;
1741                struct commit_info ci;
1742                int num;
1743
1744                if (strcmp(suspect->path, sb->path))
1745                        *option |= OUTPUT_SHOW_NAME;
1746                num = strlen(suspect->path);
1747                if (longest_file < num)
1748                        longest_file = num;
1749                if (!(suspect->commit->object.flags & METAINFO_SHOWN)) {
1750                        suspect->commit->object.flags |= METAINFO_SHOWN;
1751                        get_commit_info(suspect->commit, &ci, 1);
1752                        num = strlen(ci.author);
1753                        if (longest_author < num)
1754                                longest_author = num;
1755                }
1756                num = e->s_lno + e->num_lines;
1757                if (longest_src_lines < num)
1758                        longest_src_lines = num;
1759                num = e->lno + e->num_lines;
1760                if (longest_dst_lines < num)
1761                        longest_dst_lines = num;
1762                if (largest_score < ent_score(sb, e))
1763                        largest_score = ent_score(sb, e);
1764        }
1765        max_orig_digits = lineno_width(longest_src_lines);
1766        max_digits = lineno_width(longest_dst_lines);
1767        max_score_digits = lineno_width(largest_score);
1768}
1769
1770/*
1771 * For debugging -- origin is refcounted, and this asserts that
1772 * we do not underflow.
1773 */
1774static void sanity_check_refcnt(struct scoreboard *sb)
1775{
1776        int baa = 0;
1777        struct blame_entry *ent;
1778
1779        for (ent = sb->ent; ent; ent = ent->next) {
1780                /* Nobody should have zero or negative refcnt */
1781                if (ent->suspect->refcnt <= 0) {
1782                        fprintf(stderr, "%s in %s has negative refcnt %d\n",
1783                                ent->suspect->path,
1784                                sha1_to_hex(ent->suspect->commit->object.sha1),
1785                                ent->suspect->refcnt);
1786                        baa = 1;
1787                }
1788        }
1789        for (ent = sb->ent; ent; ent = ent->next) {
1790                /* Mark the ones that haven't been checked */
1791                if (0 < ent->suspect->refcnt)
1792                        ent->suspect->refcnt = -ent->suspect->refcnt;
1793        }
1794        for (ent = sb->ent; ent; ent = ent->next) {
1795                /*
1796                 * ... then pick each and see if they have the the
1797                 * correct refcnt.
1798                 */
1799                int found;
1800                struct blame_entry *e;
1801                struct origin *suspect = ent->suspect;
1802
1803                if (0 < suspect->refcnt)
1804                        continue;
1805                suspect->refcnt = -suspect->refcnt; /* Unmark */
1806                for (found = 0, e = sb->ent; e; e = e->next) {
1807                        if (e->suspect != suspect)
1808                                continue;
1809                        found++;
1810                }
1811                if (suspect->refcnt != found) {
1812                        fprintf(stderr, "%s in %s has refcnt %d, not %d\n",
1813                                ent->suspect->path,
1814                                sha1_to_hex(ent->suspect->commit->object.sha1),
1815                                ent->suspect->refcnt, found);
1816                        baa = 2;
1817                }
1818        }
1819        if (baa) {
1820                int opt = 0160;
1821                find_alignment(sb, &opt);
1822                output(sb, opt);
1823                die("Baa %d!", baa);
1824        }
1825}
1826
1827/*
1828 * Used for the command line parsing; check if the path exists
1829 * in the working tree.
1830 */
1831static int has_string_in_work_tree(const char *path)
1832{
1833        struct stat st;
1834        return !lstat(path, &st);
1835}
1836
1837static unsigned parse_score(const char *arg)
1838{
1839        char *end;
1840        unsigned long score = strtoul(arg, &end, 10);
1841        if (*end)
1842                return 0;
1843        return score;
1844}
1845
1846static const char *add_prefix(const char *prefix, const char *path)
1847{
1848        return prefix_path(prefix, prefix ? strlen(prefix) : 0, path);
1849}
1850
1851/*
1852 * Parsing of (comma separated) one item in the -L option
1853 */
1854static const char *parse_loc(const char *spec,
1855                             struct scoreboard *sb, long lno,
1856                             long begin, long *ret)
1857{
1858        char *term;
1859        const char *line;
1860        long num;
1861        int reg_error;
1862        regex_t regexp;
1863        regmatch_t match[1];
1864
1865        /* Allow "-L <something>,+20" to mean starting at <something>
1866         * for 20 lines, or "-L <something>,-5" for 5 lines ending at
1867         * <something>.
1868         */
1869        if (1 < begin && (spec[0] == '+' || spec[0] == '-')) {
1870                num = strtol(spec + 1, &term, 10);
1871                if (term != spec + 1) {
1872                        if (spec[0] == '-')
1873                                num = 0 - num;
1874                        if (0 < num)
1875                                *ret = begin + num - 2;
1876                        else if (!num)
1877                                *ret = begin;
1878                        else
1879                                *ret = begin + num;
1880                        return term;
1881                }
1882                return spec;
1883        }
1884        num = strtol(spec, &term, 10);
1885        if (term != spec) {
1886                *ret = num;
1887                return term;
1888        }
1889        if (spec[0] != '/')
1890                return spec;
1891
1892        /* it could be a regexp of form /.../ */
1893        for (term = (char*) spec + 1; *term && *term != '/'; term++) {
1894                if (*term == '\\')
1895                        term++;
1896        }
1897        if (*term != '/')
1898                return spec;
1899
1900        /* try [spec+1 .. term-1] as regexp */
1901        *term = 0;
1902        begin--; /* input is in human terms */
1903        line = nth_line(sb, begin);
1904
1905        if (!(reg_error = regcomp(&regexp, spec + 1, REG_NEWLINE)) &&
1906            !(reg_error = regexec(&regexp, line, 1, match, 0))) {
1907                const char *cp = line + match[0].rm_so;
1908                const char *nline;
1909
1910                while (begin++ < lno) {
1911                        nline = nth_line(sb, begin);
1912                        if (line <= cp && cp < nline)
1913                                break;
1914                        line = nline;
1915                }
1916                *ret = begin;
1917                regfree(&regexp);
1918                *term++ = '/';
1919                return term;
1920        }
1921        else {
1922                char errbuf[1024];
1923                regerror(reg_error, &regexp, errbuf, 1024);
1924                die("-L parameter '%s': %s", spec + 1, errbuf);
1925        }
1926}
1927
1928/*
1929 * Parsing of -L option
1930 */
1931static void prepare_blame_range(struct scoreboard *sb,
1932                                const char *bottomtop,
1933                                long lno,
1934                                long *bottom, long *top)
1935{
1936        const char *term;
1937
1938        term = parse_loc(bottomtop, sb, lno, 1, bottom);
1939        if (*term == ',') {
1940                term = parse_loc(term + 1, sb, lno, *bottom + 1, top);
1941                if (*term)
1942                        usage(blame_usage);
1943        }
1944        if (*term)
1945                usage(blame_usage);
1946}
1947
1948static int git_blame_config(const char *var, const char *value, void *cb)
1949{
1950        if (!strcmp(var, "blame.showroot")) {
1951                show_root = git_config_bool(var, value);
1952                return 0;
1953        }
1954        if (!strcmp(var, "blame.blankboundary")) {
1955                blank_boundary = git_config_bool(var, value);
1956                return 0;
1957        }
1958        return git_default_config(var, value, cb);
1959}
1960
1961/*
1962 * Prepare a dummy commit that represents the work tree (or staged) item.
1963 * Note that annotating work tree item never works in the reverse.
1964 */
1965static struct commit *fake_working_tree_commit(const char *path, const char *contents_from)
1966{
1967        struct commit *commit;
1968        struct origin *origin;
1969        unsigned char head_sha1[20];
1970        struct strbuf buf = STRBUF_INIT;
1971        const char *ident;
1972        time_t now;
1973        int size, len;
1974        struct cache_entry *ce;
1975        unsigned mode;
1976
1977        if (get_sha1("HEAD", head_sha1))
1978                die("No such ref: HEAD");
1979
1980        time(&now);
1981        commit = xcalloc(1, sizeof(*commit));
1982        commit->parents = xcalloc(1, sizeof(*commit->parents));
1983        commit->parents->item = lookup_commit_reference(head_sha1);
1984        commit->object.parsed = 1;
1985        commit->date = now;
1986        commit->object.type = OBJ_COMMIT;
1987
1988        origin = make_origin(commit, path);
1989
1990        if (!contents_from || strcmp("-", contents_from)) {
1991                struct stat st;
1992                const char *read_from;
1993                unsigned long fin_size;
1994
1995                if (contents_from) {
1996                        if (stat(contents_from, &st) < 0)
1997                                die("Cannot stat %s", contents_from);
1998                        read_from = contents_from;
1999                }
2000                else {
2001                        if (lstat(path, &st) < 0)
2002                                die("Cannot lstat %s", path);
2003                        read_from = path;
2004                }
2005                fin_size = xsize_t(st.st_size);
2006                mode = canon_mode(st.st_mode);
2007                switch (st.st_mode & S_IFMT) {
2008                case S_IFREG:
2009                        if (strbuf_read_file(&buf, read_from, st.st_size) != st.st_size)
2010                                die("cannot open or read %s", read_from);
2011                        break;
2012                case S_IFLNK:
2013                        if (readlink(read_from, buf.buf, buf.alloc) != fin_size)
2014                                die("cannot readlink %s", read_from);
2015                        buf.len = fin_size;
2016                        break;
2017                default:
2018                        die("unsupported file type %s", read_from);
2019                }
2020        }
2021        else {
2022                /* Reading from stdin */
2023                contents_from = "standard input";
2024                mode = 0;
2025                if (strbuf_read(&buf, 0, 0) < 0)
2026                        die("read error %s from stdin", strerror(errno));
2027        }
2028        convert_to_git(path, buf.buf, buf.len, &buf, 0);
2029        origin->file.ptr = buf.buf;
2030        origin->file.size = buf.len;
2031        pretend_sha1_file(buf.buf, buf.len, OBJ_BLOB, origin->blob_sha1);
2032        commit->util = origin;
2033
2034        /*
2035         * Read the current index, replace the path entry with
2036         * origin->blob_sha1 without mucking with its mode or type
2037         * bits; we are not going to write this index out -- we just
2038         * want to run "diff-index --cached".
2039         */
2040        discard_cache();
2041        read_cache();
2042
2043        len = strlen(path);
2044        if (!mode) {
2045                int pos = cache_name_pos(path, len);
2046                if (0 <= pos)
2047                        mode = active_cache[pos]->ce_mode;
2048                else
2049                        /* Let's not bother reading from HEAD tree */
2050                        mode = S_IFREG | 0644;
2051        }
2052        size = cache_entry_size(len);
2053        ce = xcalloc(1, size);
2054        hashcpy(ce->sha1, origin->blob_sha1);
2055        memcpy(ce->name, path, len);
2056        ce->ce_flags = create_ce_flags(len, 0);
2057        ce->ce_mode = create_ce_mode(mode);
2058        add_cache_entry(ce, ADD_CACHE_OK_TO_ADD|ADD_CACHE_OK_TO_REPLACE);
2059
2060        /*
2061         * We are not going to write this out, so this does not matter
2062         * right now, but someday we might optimize diff-index --cached
2063         * with cache-tree information.
2064         */
2065        cache_tree_invalidate_path(active_cache_tree, path);
2066
2067        commit->buffer = xmalloc(400);
2068        ident = fmt_ident("Not Committed Yet", "not.committed.yet", NULL, 0);
2069        snprintf(commit->buffer, 400,
2070                "tree 0000000000000000000000000000000000000000\n"
2071                "parent %s\n"
2072                "author %s\n"
2073                "committer %s\n\n"
2074                "Version of %s from %s\n",
2075                sha1_to_hex(head_sha1),
2076                ident, ident, path, contents_from ? contents_from : path);
2077        return commit;
2078}
2079
2080static const char *prepare_final(struct scoreboard *sb)
2081{
2082        int i;
2083        const char *final_commit_name = NULL;
2084        struct rev_info *revs = sb->revs;
2085
2086        /*
2087         * There must be one and only one positive commit in the
2088         * revs->pending array.
2089         */
2090        for (i = 0; i < revs->pending.nr; i++) {
2091                struct object *obj = revs->pending.objects[i].item;
2092                if (obj->flags & UNINTERESTING)
2093                        continue;
2094                while (obj->type == OBJ_TAG)
2095                        obj = deref_tag(obj, NULL, 0);
2096                if (obj->type != OBJ_COMMIT)
2097                        die("Non commit %s?", revs->pending.objects[i].name);
2098                if (sb->final)
2099                        die("More than one commit to dig from %s and %s?",
2100                            revs->pending.objects[i].name,
2101                            final_commit_name);
2102                sb->final = (struct commit *) obj;
2103                final_commit_name = revs->pending.objects[i].name;
2104        }
2105        return final_commit_name;
2106}
2107
2108static const char *prepare_initial(struct scoreboard *sb)
2109{
2110        int i;
2111        const char *final_commit_name = NULL;
2112        struct rev_info *revs = sb->revs;
2113
2114        /*
2115         * There must be one and only one negative commit, and it must be
2116         * the boundary.
2117         */
2118        for (i = 0; i < revs->pending.nr; i++) {
2119                struct object *obj = revs->pending.objects[i].item;
2120                if (!(obj->flags & UNINTERESTING))
2121                        continue;
2122                while (obj->type == OBJ_TAG)
2123                        obj = deref_tag(obj, NULL, 0);
2124                if (obj->type != OBJ_COMMIT)
2125                        die("Non commit %s?", revs->pending.objects[i].name);
2126                if (sb->final)
2127                        die("More than one commit to dig down to %s and %s?",
2128                            revs->pending.objects[i].name,
2129                            final_commit_name);
2130                sb->final = (struct commit *) obj;
2131                final_commit_name = revs->pending.objects[i].name;
2132        }
2133        if (!final_commit_name)
2134                die("No commit to dig down to?");
2135        return final_commit_name;
2136}
2137
2138static int blame_copy_callback(const struct option *option, const char *arg, int unset)
2139{
2140        int *opt = option->value;
2141
2142        /*
2143         * -C enables copy from removed files;
2144         * -C -C enables copy from existing files, but only
2145         *       when blaming a new file;
2146         * -C -C -C enables copy from existing files for
2147         *          everybody
2148         */
2149        if (*opt & PICKAXE_BLAME_COPY_HARDER)
2150                *opt |= PICKAXE_BLAME_COPY_HARDEST;
2151        if (*opt & PICKAXE_BLAME_COPY)
2152                *opt |= PICKAXE_BLAME_COPY_HARDER;
2153        *opt |= PICKAXE_BLAME_COPY | PICKAXE_BLAME_MOVE;
2154
2155        if (arg)
2156                blame_copy_score = parse_score(arg);
2157        return 0;
2158}
2159
2160static int blame_move_callback(const struct option *option, const char *arg, int unset)
2161{
2162        int *opt = option->value;
2163
2164        *opt |= PICKAXE_BLAME_MOVE;
2165
2166        if (arg)
2167                blame_move_score = parse_score(arg);
2168        return 0;
2169}
2170
2171static int blame_bottomtop_callback(const struct option *option, const char *arg, int unset)
2172{
2173        const char **bottomtop = option->value;
2174        if (!arg)
2175                return -1;
2176        if (*bottomtop)
2177                die("More than one '-L n,m' option given");
2178        *bottomtop = arg;
2179        return 0;
2180}
2181
2182int cmd_blame(int argc, const char **argv, const char *prefix)
2183{
2184        struct rev_info revs;
2185        const char *path;
2186        struct scoreboard sb;
2187        struct origin *o;
2188        struct blame_entry *ent;
2189        long dashdash_pos, bottom, top, lno;
2190        const char *final_commit_name = NULL;
2191        enum object_type type;
2192
2193        static const char *bottomtop = NULL;
2194        static int output_option = 0, opt = 0;
2195        static int show_stats = 0;
2196        static const char *revs_file = NULL;
2197        static const char *contents_from = NULL;
2198        static const struct option options[] = {
2199                OPT_BOOLEAN(0, "incremental", &incremental, "Show blame entries as we find them, incrementally"),
2200                OPT_BOOLEAN('b', NULL, &blank_boundary, "Show blank SHA-1 for boundary commits (Default: off)"),
2201                OPT_BOOLEAN(0, "root", &show_root, "Do not treat root commits as boundaries (Default: off)"),
2202                OPT_BOOLEAN(0, "show-stats", &show_stats, "Show work cost statistics"),
2203                OPT_BIT(0, "score-debug", &output_option, "Show output score for blame entries", OUTPUT_SHOW_SCORE),
2204                OPT_BIT('f', "show-name", &output_option, "Show original filename (Default: auto)", OUTPUT_SHOW_NAME),
2205                OPT_BIT('n', "show-number", &output_option, "Show original linenumber (Default: off)", OUTPUT_SHOW_NUMBER),
2206                OPT_BIT('p', "porcelain", &output_option, "Show in a format designed for machine consumption", OUTPUT_PORCELAIN),
2207                OPT_BIT('c', NULL, &output_option, "Use the same output mode as git-annotate (Default: off)", OUTPUT_ANNOTATE_COMPAT),
2208                OPT_BIT('t', NULL, &output_option, "Show raw timestamp (Default: off)", OUTPUT_RAW_TIMESTAMP),
2209                OPT_BIT('l', NULL, &output_option, "Show long commit SHA1 (Default: off)", OUTPUT_LONG_OBJECT_NAME),
2210                OPT_BIT('s', NULL, &output_option, "Suppress author name and timestamp (Default: off)", OUTPUT_NO_AUTHOR),
2211                OPT_BIT('w', NULL, &xdl_opts, "Ignore whitespace differences", XDF_IGNORE_WHITESPACE),
2212                OPT_STRING('S', NULL, &revs_file, "file", "Use revisions from <file> instead of calling git-rev-list"),
2213                OPT_STRING(0, "contents", &contents_from, "file", "Use <file>'s contents as the final image"),
2214                { OPTION_CALLBACK, 'C', NULL, &opt, "score", "Find line copies within and across files", PARSE_OPT_OPTARG, blame_copy_callback },
2215                { OPTION_CALLBACK, 'M', NULL, &opt, "score", "Find line movements within and across files", PARSE_OPT_OPTARG, blame_move_callback },
2216                OPT_CALLBACK('L', NULL, &bottomtop, "n,m", "Process only line range n,m, counting from 1", blame_bottomtop_callback),
2217                OPT_END()
2218        };
2219
2220        struct parse_opt_ctx_t ctx;
2221        int cmd_is_annotate = !strcmp(argv[0], "annotate");
2222
2223        git_config(git_blame_config, NULL);
2224        init_revisions(&revs, NULL);
2225        save_commit_buffer = 0;
2226        dashdash_pos = 0;
2227
2228        parse_options_start(&ctx, argc, argv, PARSE_OPT_KEEP_DASHDASH |
2229                            PARSE_OPT_KEEP_ARGV0);
2230        for (;;) {
2231                switch (parse_options_step(&ctx, options, blame_opt_usage)) {
2232                case PARSE_OPT_HELP:
2233                        exit(129);
2234                case PARSE_OPT_DONE:
2235                        if (ctx.argv[0])
2236                                dashdash_pos = ctx.cpidx;
2237                        goto parse_done;
2238                }
2239
2240                if (!strcmp(ctx.argv[0], "--reverse")) {
2241                        ctx.argv[0] = "--children";
2242                        reverse = 1;
2243                }
2244                parse_revision_opt(&revs, &ctx, options, blame_opt_usage);
2245        }
2246parse_done:
2247        argc = parse_options_end(&ctx);
2248
2249        if (cmd_is_annotate)
2250                output_option |= OUTPUT_ANNOTATE_COMPAT;
2251
2252        if (DIFF_OPT_TST(&revs.diffopt, FIND_COPIES_HARDER))
2253                opt |= (PICKAXE_BLAME_COPY | PICKAXE_BLAME_MOVE |
2254                        PICKAXE_BLAME_COPY_HARDER);
2255
2256        if (!blame_move_score)
2257                blame_move_score = BLAME_DEFAULT_MOVE_SCORE;
2258        if (!blame_copy_score)
2259                blame_copy_score = BLAME_DEFAULT_COPY_SCORE;
2260
2261        /*
2262         * We have collected options unknown to us in argv[1..unk]
2263         * which are to be passed to revision machinery if we are
2264         * going to do the "bottom" processing.
2265         *
2266         * The remaining are:
2267         *
2268         * (1) if dashdash_pos != 0, its either
2269         *     "blame [revisions] -- <path>" or
2270         *     "blame -- <path> <rev>"
2271         *
2272         * (2) otherwise, its one of the two:
2273         *     "blame [revisions] <path>"
2274         *     "blame <path> <rev>"
2275         *
2276         * Note that we must strip out <path> from the arguments: we do not
2277         * want the path pruning but we may want "bottom" processing.
2278         */
2279        if (dashdash_pos) {
2280                switch (argc - dashdash_pos - 1) {
2281                case 2: /* (1b) */
2282                        if (argc != 4)
2283                                usage_with_options(blame_opt_usage, options);
2284                        /* reorder for the new way: <rev> -- <path> */
2285                        argv[1] = argv[3];
2286                        argv[3] = argv[2];
2287                        argv[2] = "--";
2288                        /* FALLTHROUGH */
2289                case 1: /* (1a) */
2290                        path = add_prefix(prefix, argv[--argc]);
2291                        argv[argc] = NULL;
2292                        break;
2293                default:
2294                        usage_with_options(blame_opt_usage, options);
2295                }
2296        } else {
2297                if (argc < 2)
2298                        usage_with_options(blame_opt_usage, options);
2299                path = add_prefix(prefix, argv[argc - 1]);
2300                if (argc == 3 && !has_string_in_work_tree(path)) { /* (2b) */
2301                        path = add_prefix(prefix, argv[1]);
2302                        argv[1] = argv[2];
2303                }
2304                argv[argc - 1] = "--";
2305
2306                setup_work_tree();
2307                if (!has_string_in_work_tree(path))
2308                        die("cannot stat path %s: %s", path, strerror(errno));
2309        }
2310
2311        setup_revisions(argc, argv, &revs, NULL);
2312        memset(&sb, 0, sizeof(sb));
2313
2314        sb.revs = &revs;
2315        if (!reverse)
2316                final_commit_name = prepare_final(&sb);
2317        else if (contents_from)
2318                die("--contents and --children do not blend well.");
2319        else
2320                final_commit_name = prepare_initial(&sb);
2321
2322        if (!sb.final) {
2323                /*
2324                 * "--not A B -- path" without anything positive;
2325                 * do not default to HEAD, but use the working tree
2326                 * or "--contents".
2327                 */
2328                setup_work_tree();
2329                sb.final = fake_working_tree_commit(path, contents_from);
2330                add_pending_object(&revs, &(sb.final->object), ":");
2331        }
2332        else if (contents_from)
2333                die("Cannot use --contents with final commit object name");
2334
2335        /*
2336         * If we have bottom, this will mark the ancestors of the
2337         * bottom commits we would reach while traversing as
2338         * uninteresting.
2339         */
2340        if (prepare_revision_walk(&revs))
2341                die("revision walk setup failed");
2342
2343        if (is_null_sha1(sb.final->object.sha1)) {
2344                char *buf;
2345                o = sb.final->util;
2346                buf = xmalloc(o->file.size + 1);
2347                memcpy(buf, o->file.ptr, o->file.size + 1);
2348                sb.final_buf = buf;
2349                sb.final_buf_size = o->file.size;
2350        }
2351        else {
2352                o = get_origin(&sb, sb.final, path);
2353                if (fill_blob_sha1(o))
2354                        die("no such path %s in %s", path, final_commit_name);
2355
2356                sb.final_buf = read_sha1_file(o->blob_sha1, &type,
2357                                              &sb.final_buf_size);
2358                if (!sb.final_buf)
2359                        die("Cannot read blob %s for path %s",
2360                            sha1_to_hex(o->blob_sha1),
2361                            path);
2362        }
2363        num_read_blob++;
2364        lno = prepare_lines(&sb);
2365
2366        bottom = top = 0;
2367        if (bottomtop)
2368                prepare_blame_range(&sb, bottomtop, lno, &bottom, &top);
2369        if (bottom && top && top < bottom) {
2370                long tmp;
2371                tmp = top; top = bottom; bottom = tmp;
2372        }
2373        if (bottom < 1)
2374                bottom = 1;
2375        if (top < 1)
2376                top = lno;
2377        bottom--;
2378        if (lno < top)
2379                die("file %s has only %lu lines", path, lno);
2380
2381        ent = xcalloc(1, sizeof(*ent));
2382        ent->lno = bottom;
2383        ent->num_lines = top - bottom;
2384        ent->suspect = o;
2385        ent->s_lno = bottom;
2386
2387        sb.ent = ent;
2388        sb.path = path;
2389
2390        if (revs_file && read_ancestry(revs_file))
2391                die("reading graft file %s failed: %s",
2392                    revs_file, strerror(errno));
2393
2394        read_mailmap(&mailmap, ".mailmap", NULL);
2395
2396        if (!incremental)
2397                setup_pager();
2398
2399        assign_blame(&sb, opt);
2400
2401        if (incremental)
2402                return 0;
2403
2404        coalesce(&sb);
2405
2406        if (!(output_option & OUTPUT_PORCELAIN))
2407                find_alignment(&sb, &output_option);
2408
2409        output(&sb, output_option);
2410        free((void *)sb.final_buf);
2411        for (ent = sb.ent; ent; ) {
2412                struct blame_entry *e = ent->next;
2413                free(ent);
2414                ent = e;
2415        }
2416
2417        if (show_stats) {
2418                printf("num read blob: %d\n", num_read_blob);
2419                printf("num get patch: %d\n", num_get_patch);
2420                printf("num commits: %d\n", num_commits);
2421        }
2422        return 0;
2423}