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