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