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