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