082ff45fe84d9b6cfa08f85ac05ee2860b0d64b2
   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 "xdiff-interface.h"
  17
  18#include <time.h>
  19#include <sys/time.h>
  20
  21static char pickaxe_usage[] =
  22"git-pickaxe [-c] [-l] [-t] [-f] [-n] [-p] [-L n,m] [-S <revs-file>] [-M] [-C] [-C] [commit] [--] file\n"
  23"  -c, --compatibility Use the same output mode as git-annotate (Default: off)\n"
  24"  -l, --long          Show long commit SHA1 (Default: off)\n"
  25"  -t, --time          Show raw timestamp (Default: off)\n"
  26"  -f, --show-name     Show original filename (Default: auto)\n"
  27"  -n, --show-number   Show original linenumber (Default: off)\n"
  28"  -p, --porcelain     Show in a format designed for machine consumption\n"
  29"  -L n,m              Process only line range n,m, counting from 1\n"
  30"  -M, -C              Find line movements within and across files\n"
  31"  -S revs-file        Use revisions from revs-file instead of calling git-rev-list\n";
  32
  33static int longest_file;
  34static int longest_author;
  35static int max_orig_digits;
  36static int max_digits;
  37static int max_score_digits;
  38
  39#ifndef DEBUG
  40#define DEBUG 0
  41#endif
  42
  43#define PICKAXE_BLAME_MOVE              01
  44#define PICKAXE_BLAME_COPY              02
  45#define PICKAXE_BLAME_COPY_HARDER       04
  46
  47/*
  48 * blame for a blame_entry with score lower than these thresholds
  49 * is not passed to the parent using move/copy logic.
  50 */
  51static unsigned blame_move_score;
  52static unsigned blame_copy_score;
  53#define BLAME_DEFAULT_MOVE_SCORE        20
  54#define BLAME_DEFAULT_COPY_SCORE        40
  55
  56/* bits #0..7 in revision.h, #8..11 used for merge_bases() in commit.c */
  57#define METAINFO_SHOWN          (1u<<12)
  58#define MORE_THAN_ONE_PATH      (1u<<13)
  59
  60/*
  61 * One blob in a commit that is being suspected
  62 */
  63struct origin {
  64        int refcnt;
  65        struct commit *commit;
  66        unsigned char blob_sha1[20];
  67        char path[FLEX_ARRAY];
  68};
  69
  70static inline struct origin *origin_incref(struct origin *o)
  71{
  72        if (o)
  73                o->refcnt++;
  74        return o;
  75}
  76
  77static void origin_decref(struct origin *o)
  78{
  79        if (o && --o->refcnt <= 0) {
  80                memset(o, 0, sizeof(*o));
  81                free(o);
  82        }
  83}
  84
  85struct blame_entry {
  86        struct blame_entry *prev;
  87        struct blame_entry *next;
  88
  89        /* the first line of this group in the final image;
  90         * internally all line numbers are 0 based.
  91         */
  92        int lno;
  93
  94        /* how many lines this group has */
  95        int num_lines;
  96
  97        /* the commit that introduced this group into the final image */
  98        struct origin *suspect;
  99
 100        /* true if the suspect is truly guilty; false while we have not
 101         * checked if the group came from one of its parents.
 102         */
 103        char guilty;
 104
 105        /* the line number of the first line of this group in the
 106         * suspect's file; internally all line numbers are 0 based.
 107         */
 108        int s_lno;
 109
 110        /* how significant this entry is -- cached to avoid
 111         * scanning the lines over and over
 112         */
 113        unsigned score;
 114};
 115
 116struct scoreboard {
 117        /* the final commit (i.e. where we started digging from) */
 118        struct commit *final;
 119
 120        const char *path;
 121
 122        /* the contents in the final; pointed into by buf pointers of
 123         * blame_entries
 124         */
 125        const char *final_buf;
 126        unsigned long final_buf_size;
 127
 128        /* linked list of blames */
 129        struct blame_entry *ent;
 130
 131        /* look-up a line in the final buffer */
 132        int num_lines;
 133        int *lineno;
 134};
 135
 136static int cmp_suspect(struct origin *a, struct origin *b)
 137{
 138        int cmp = hashcmp(a->commit->object.sha1, b->commit->object.sha1);
 139        if (cmp)
 140                return cmp;
 141        return strcmp(a->path, b->path);
 142}
 143
 144#define cmp_suspect(a, b) ( ((a)==(b)) ? 0 : cmp_suspect(a,b) )
 145
 146static void sanity_check_refcnt(struct scoreboard *);
 147
 148static void coalesce(struct scoreboard *sb)
 149{
 150        struct blame_entry *ent, *next;
 151
 152        for (ent = sb->ent; ent && (next = ent->next); ent = next) {
 153                if (!cmp_suspect(ent->suspect, next->suspect) &&
 154                    ent->guilty == next->guilty &&
 155                    ent->s_lno + ent->num_lines == next->s_lno) {
 156                        ent->num_lines += next->num_lines;
 157                        ent->next = next->next;
 158                        if (ent->next)
 159                                ent->next->prev = ent;
 160                        origin_decref(next->suspect);
 161                        free(next);
 162                        ent->score = 0;
 163                        next = ent; /* again */
 164                }
 165        }
 166
 167        if (DEBUG) /* sanity */
 168                sanity_check_refcnt(sb);
 169}
 170
 171static struct origin *get_origin(struct scoreboard *sb,
 172                                 struct commit *commit,
 173                                 const char *path)
 174{
 175        struct blame_entry *e;
 176        struct origin *o;
 177
 178        for (e = sb->ent; e; e = e->next) {
 179                if (e->suspect->commit == commit &&
 180                    !strcmp(e->suspect->path, path))
 181                        return origin_incref(e->suspect);
 182        }
 183        o = xcalloc(1, sizeof(*o) + strlen(path) + 1);
 184        o->commit = commit;
 185        o->refcnt = 1;
 186        strcpy(o->path, path);
 187        return o;
 188}
 189
 190static int fill_blob_sha1(struct origin *origin)
 191{
 192        unsigned mode;
 193        char type[10];
 194
 195        if (!is_null_sha1(origin->blob_sha1))
 196                return 0;
 197        if (get_tree_entry(origin->commit->object.sha1,
 198                           origin->path,
 199                           origin->blob_sha1, &mode))
 200                goto error_out;
 201        if (sha1_object_info(origin->blob_sha1, type, NULL) ||
 202            strcmp(type, blob_type))
 203                goto error_out;
 204        return 0;
 205 error_out:
 206        hashclr(origin->blob_sha1);
 207        return -1;
 208}
 209
 210static struct origin *find_origin(struct scoreboard *sb,
 211                                  struct commit *parent,
 212                                  struct origin *origin)
 213{
 214        struct origin *porigin = NULL;
 215        struct diff_options diff_opts;
 216        const char *paths[2];
 217
 218        if (parent->util) {
 219                struct origin *cached = parent->util;
 220                if (!strcmp(cached->path, origin->path))
 221                        return origin_incref(cached);
 222        }
 223
 224        /* See if the origin->path is different between parent
 225         * and origin first.  Most of the time they are the
 226         * same and diff-tree is fairly efficient about this.
 227         */
 228        diff_setup(&diff_opts);
 229        diff_opts.recursive = 1;
 230        diff_opts.detect_rename = 0;
 231        diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;
 232        paths[0] = origin->path;
 233        paths[1] = NULL;
 234
 235        diff_tree_setup_paths(paths, &diff_opts);
 236        if (diff_setup_done(&diff_opts) < 0)
 237                die("diff-setup");
 238        diff_tree_sha1(parent->tree->object.sha1,
 239                       origin->commit->tree->object.sha1,
 240                       "", &diff_opts);
 241        diffcore_std(&diff_opts);
 242
 243        /* It is either one entry that says "modified", or "created",
 244         * or nothing.
 245         */
 246        if (!diff_queued_diff.nr) {
 247                /* The path is the same as parent */
 248                porigin = get_origin(sb, parent, origin->path);
 249                hashcpy(porigin->blob_sha1, origin->blob_sha1);
 250        }
 251        else if (diff_queued_diff.nr != 1)
 252                die("internal error in pickaxe::find_origin");
 253        else {
 254                struct diff_filepair *p = diff_queued_diff.queue[0];
 255                switch (p->status) {
 256                default:
 257                        die("internal error in pickaxe::find_origin (%c)",
 258                            p->status);
 259                case 'M':
 260                        porigin = get_origin(sb, parent, origin->path);
 261                        hashcpy(porigin->blob_sha1, p->one->sha1);
 262                        break;
 263                case 'A':
 264                case 'T':
 265                        /* Did not exist in parent, or type changed */
 266                        break;
 267                }
 268        }
 269        diff_flush(&diff_opts);
 270        if (porigin) {
 271                origin_incref(porigin);
 272                if (parent->util)
 273                        origin_decref(parent->util);
 274                parent->util = porigin;
 275        }
 276        return porigin;
 277}
 278
 279static struct origin *find_rename(struct scoreboard *sb,
 280                                  struct commit *parent,
 281                                  struct origin *origin)
 282{
 283        struct origin *porigin = NULL;
 284        struct diff_options diff_opts;
 285        int i;
 286        const char *paths[2];
 287
 288        diff_setup(&diff_opts);
 289        diff_opts.recursive = 1;
 290        diff_opts.detect_rename = DIFF_DETECT_RENAME;
 291        diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;
 292        diff_opts.single_follow = origin->path;
 293        paths[0] = NULL;
 294        diff_tree_setup_paths(paths, &diff_opts);
 295        if (diff_setup_done(&diff_opts) < 0)
 296                die("diff-setup");
 297        diff_tree_sha1(parent->tree->object.sha1,
 298                       origin->commit->tree->object.sha1,
 299                       "", &diff_opts);
 300        diffcore_std(&diff_opts);
 301
 302        for (i = 0; i < diff_queued_diff.nr; i++) {
 303                struct diff_filepair *p = diff_queued_diff.queue[i];
 304                if ((p->status == 'R' || p->status == 'C') &&
 305                    !strcmp(p->two->path, origin->path)) {
 306                        porigin = get_origin(sb, parent, p->one->path);
 307                        hashcpy(porigin->blob_sha1, p->one->sha1);
 308                        break;
 309                }
 310        }
 311        diff_flush(&diff_opts);
 312        return porigin;
 313}
 314
 315struct chunk {
 316        /* line number in postimage; up to but not including this
 317         * line is the same as preimage
 318         */
 319        int same;
 320
 321        /* preimage line number after this chunk */
 322        int p_next;
 323
 324        /* postimage line number after this chunk */
 325        int t_next;
 326};
 327
 328struct patch {
 329        struct chunk *chunks;
 330        int num;
 331};
 332
 333struct blame_diff_state {
 334        struct xdiff_emit_state xm;
 335        struct patch *ret;
 336        unsigned hunk_post_context;
 337        unsigned hunk_in_pre_context : 1;
 338};
 339
 340static void process_u_diff(void *state_, char *line, unsigned long len)
 341{
 342        struct blame_diff_state *state = state_;
 343        struct chunk *chunk;
 344        int off1, off2, len1, len2, num;
 345
 346        num = state->ret->num;
 347        if (len < 4 || line[0] != '@' || line[1] != '@') {
 348                if (state->hunk_in_pre_context && line[0] == ' ')
 349                        state->ret->chunks[num - 1].same++;
 350                else {
 351                        state->hunk_in_pre_context = 0;
 352                        if (line[0] == ' ')
 353                                state->hunk_post_context++;
 354                        else
 355                                state->hunk_post_context = 0;
 356                }
 357                return;
 358        }
 359
 360        if (num && state->hunk_post_context) {
 361                chunk = &state->ret->chunks[num - 1];
 362                chunk->p_next -= state->hunk_post_context;
 363                chunk->t_next -= state->hunk_post_context;
 364        }
 365        state->ret->num = ++num;
 366        state->ret->chunks = xrealloc(state->ret->chunks,
 367                                      sizeof(struct chunk) * num);
 368        chunk = &state->ret->chunks[num - 1];
 369        if (parse_hunk_header(line, len, &off1, &len1, &off2, &len2)) {
 370                state->ret->num--;
 371                return;
 372        }
 373
 374        /* Line numbers in patch output are one based. */
 375        off1--;
 376        off2--;
 377
 378        chunk->same = len2 ? off2 : (off2 + 1);
 379
 380        chunk->p_next = off1 + (len1 ? len1 : 1);
 381        chunk->t_next = chunk->same + len2;
 382        state->hunk_in_pre_context = 1;
 383        state->hunk_post_context = 0;
 384}
 385
 386static struct patch *compare_buffer(mmfile_t *file_p, mmfile_t *file_o,
 387                                    int context)
 388{
 389        struct blame_diff_state state;
 390        xpparam_t xpp;
 391        xdemitconf_t xecfg;
 392        xdemitcb_t ecb;
 393
 394        xpp.flags = XDF_NEED_MINIMAL;
 395        xecfg.ctxlen = context;
 396        xecfg.flags = 0;
 397        ecb.outf = xdiff_outf;
 398        ecb.priv = &state;
 399        memset(&state, 0, sizeof(state));
 400        state.xm.consume = process_u_diff;
 401        state.ret = xmalloc(sizeof(struct patch));
 402        state.ret->chunks = NULL;
 403        state.ret->num = 0;
 404
 405        xdl_diff(file_p, file_o, &xpp, &xecfg, &ecb);
 406
 407        if (state.ret->num) {
 408                struct chunk *chunk;
 409                chunk = &state.ret->chunks[state.ret->num - 1];
 410                chunk->p_next -= state.hunk_post_context;
 411                chunk->t_next -= state.hunk_post_context;
 412        }
 413        return state.ret;
 414}
 415
 416static struct patch *get_patch(struct origin *parent, struct origin *origin)
 417{
 418        mmfile_t file_p, file_o;
 419        char type[10];
 420        char *blob_p, *blob_o;
 421        struct patch *patch;
 422
 423        blob_p = read_sha1_file(parent->blob_sha1, type,
 424                                (unsigned long *) &file_p.size);
 425        blob_o = read_sha1_file(origin->blob_sha1, type,
 426                                (unsigned long *) &file_o.size);
 427        file_p.ptr = blob_p;
 428        file_o.ptr = blob_o;
 429        if (!file_p.ptr || !file_o.ptr) {
 430                free(blob_p);
 431                free(blob_o);
 432                return NULL;
 433        }
 434
 435        patch = compare_buffer(&file_p, &file_o, 0);
 436        free(blob_p);
 437        free(blob_o);
 438        return patch;
 439}
 440
 441static void free_patch(struct patch *p)
 442{
 443        free(p->chunks);
 444        free(p);
 445}
 446
 447static void add_blame_entry(struct scoreboard *sb, struct blame_entry *e)
 448{
 449        struct blame_entry *ent, *prev = NULL;
 450
 451        origin_incref(e->suspect);
 452
 453        for (ent = sb->ent; ent && ent->lno < e->lno; ent = ent->next)
 454                prev = ent;
 455
 456        /* prev, if not NULL, is the last one that is below e */
 457        e->prev = prev;
 458        if (prev) {
 459                e->next = prev->next;
 460                prev->next = e;
 461        }
 462        else {
 463                e->next = sb->ent;
 464                sb->ent = e;
 465        }
 466        if (e->next)
 467                e->next->prev = e;
 468}
 469
 470static void dup_entry(struct blame_entry *dst, struct blame_entry *src)
 471{
 472        struct blame_entry *p, *n;
 473
 474        p = dst->prev;
 475        n = dst->next;
 476        origin_incref(src->suspect);
 477        origin_decref(dst->suspect);
 478        memcpy(dst, src, sizeof(*src));
 479        dst->prev = p;
 480        dst->next = n;
 481        dst->score = 0;
 482}
 483
 484static const char *nth_line(struct scoreboard *sb, int lno)
 485{
 486        return sb->final_buf + sb->lineno[lno];
 487}
 488
 489static void split_overlap(struct blame_entry *split,
 490                          struct blame_entry *e,
 491                          int tlno, int plno, int same,
 492                          struct origin *parent)
 493{
 494        /* it is known that lines between tlno to same came from
 495         * parent, and e has an overlap with that range.  it also is
 496         * known that parent's line plno corresponds to e's line tlno.
 497         *
 498         *                <---- e ----->
 499         *                   <------>
 500         *                   <------------>
 501         *             <------------>
 502         *             <------------------>
 503         *
 504         * Potentially we need to split e into three parts; before
 505         * this chunk, the chunk to be blamed for parent, and after
 506         * that portion.
 507         */
 508        int chunk_end_lno;
 509        memset(split, 0, sizeof(struct blame_entry [3]));
 510
 511        if (e->s_lno < tlno) {
 512                /* there is a pre-chunk part not blamed on parent */
 513                split[0].suspect = origin_incref(e->suspect);
 514                split[0].lno = e->lno;
 515                split[0].s_lno = e->s_lno;
 516                split[0].num_lines = tlno - e->s_lno;
 517                split[1].lno = e->lno + tlno - e->s_lno;
 518                split[1].s_lno = plno;
 519        }
 520        else {
 521                split[1].lno = e->lno;
 522                split[1].s_lno = plno + (e->s_lno - tlno);
 523        }
 524
 525        if (same < e->s_lno + e->num_lines) {
 526                /* there is a post-chunk part not blamed on parent */
 527                split[2].suspect = origin_incref(e->suspect);
 528                split[2].lno = e->lno + (same - e->s_lno);
 529                split[2].s_lno = e->s_lno + (same - e->s_lno);
 530                split[2].num_lines = e->s_lno + e->num_lines - same;
 531                chunk_end_lno = split[2].lno;
 532        }
 533        else
 534                chunk_end_lno = e->lno + e->num_lines;
 535        split[1].num_lines = chunk_end_lno - split[1].lno;
 536
 537        if (split[1].num_lines < 1)
 538                return;
 539        split[1].suspect = origin_incref(parent);
 540}
 541
 542static void split_blame(struct scoreboard *sb,
 543                        struct blame_entry *split,
 544                        struct blame_entry *e)
 545{
 546        struct blame_entry *new_entry;
 547
 548        if (split[0].suspect && split[2].suspect) {
 549                /* we need to split e into two and add another for parent */
 550                dup_entry(e, &split[0]);
 551
 552                new_entry = xmalloc(sizeof(*new_entry));
 553                memcpy(new_entry, &(split[2]), sizeof(struct blame_entry));
 554                add_blame_entry(sb, new_entry);
 555
 556                new_entry = xmalloc(sizeof(*new_entry));
 557                memcpy(new_entry, &(split[1]), sizeof(struct blame_entry));
 558                add_blame_entry(sb, new_entry);
 559        }
 560        else if (!split[0].suspect && !split[2].suspect)
 561                /* parent covers the entire area */
 562                dup_entry(e, &split[1]);
 563        else if (split[0].suspect) {
 564                dup_entry(e, &split[0]);
 565
 566                new_entry = xmalloc(sizeof(*new_entry));
 567                memcpy(new_entry, &(split[1]), sizeof(struct blame_entry));
 568                add_blame_entry(sb, new_entry);
 569        }
 570        else {
 571                dup_entry(e, &split[1]);
 572
 573                new_entry = xmalloc(sizeof(*new_entry));
 574                memcpy(new_entry, &(split[2]), sizeof(struct blame_entry));
 575                add_blame_entry(sb, new_entry);
 576        }
 577
 578        if (DEBUG) { /* sanity */
 579                struct blame_entry *ent;
 580                int lno = sb->ent->lno, corrupt = 0;
 581
 582                for (ent = sb->ent; ent; ent = ent->next) {
 583                        if (lno != ent->lno)
 584                                corrupt = 1;
 585                        if (ent->s_lno < 0)
 586                                corrupt = 1;
 587                        lno += ent->num_lines;
 588                }
 589                if (corrupt) {
 590                        lno = sb->ent->lno;
 591                        for (ent = sb->ent; ent; ent = ent->next) {
 592                                printf("L %8d l %8d n %8d\n",
 593                                       lno, ent->lno, ent->num_lines);
 594                                lno = ent->lno + ent->num_lines;
 595                        }
 596                        die("oops");
 597                }
 598        }
 599}
 600
 601static void decref_split(struct blame_entry *split)
 602{
 603        int i;
 604
 605        for (i = 0; i < 3; i++)
 606                origin_decref(split[i].suspect);
 607}
 608
 609static void blame_overlap(struct scoreboard *sb, struct blame_entry *e,
 610                          int tlno, int plno, int same,
 611                          struct origin *parent)
 612{
 613        struct blame_entry split[3];
 614
 615        split_overlap(split, e, tlno, plno, same, parent);
 616        if (split[1].suspect)
 617                split_blame(sb, split, e);
 618        decref_split(split);
 619}
 620
 621static int find_last_in_target(struct scoreboard *sb, struct origin *target)
 622{
 623        struct blame_entry *e;
 624        int last_in_target = -1;
 625
 626        for (e = sb->ent; e; e = e->next) {
 627                if (e->guilty || cmp_suspect(e->suspect, target))
 628                        continue;
 629                if (last_in_target < e->s_lno + e->num_lines)
 630                        last_in_target = e->s_lno + e->num_lines;
 631        }
 632        return last_in_target;
 633}
 634
 635static void blame_chunk(struct scoreboard *sb,
 636                        int tlno, int plno, int same,
 637                        struct origin *target, struct origin *parent)
 638{
 639        struct blame_entry *e;
 640
 641        for (e = sb->ent; e; e = e->next) {
 642                if (e->guilty || cmp_suspect(e->suspect, target))
 643                        continue;
 644                if (same <= e->s_lno)
 645                        continue;
 646                if (tlno < e->s_lno + e->num_lines)
 647                        blame_overlap(sb, e, tlno, plno, same, parent);
 648        }
 649}
 650
 651static int pass_blame_to_parent(struct scoreboard *sb,
 652                                struct origin *target,
 653                                struct origin *parent)
 654{
 655        int i, last_in_target, plno, tlno;
 656        struct patch *patch;
 657
 658        last_in_target = find_last_in_target(sb, target);
 659        if (last_in_target < 0)
 660                return 1; /* nothing remains for this target */
 661
 662        patch = get_patch(parent, target);
 663        plno = tlno = 0;
 664        for (i = 0; i < patch->num; i++) {
 665                struct chunk *chunk = &patch->chunks[i];
 666
 667                blame_chunk(sb, tlno, plno, chunk->same, target, parent);
 668                plno = chunk->p_next;
 669                tlno = chunk->t_next;
 670        }
 671        /* rest (i.e. anything above tlno) are the same as parent */
 672        blame_chunk(sb, tlno, plno, last_in_target, target, parent);
 673
 674        free_patch(patch);
 675        return 0;
 676}
 677
 678static unsigned ent_score(struct scoreboard *sb, struct blame_entry *e)
 679{
 680        unsigned score;
 681        const char *cp, *ep;
 682
 683        if (e->score)
 684                return e->score;
 685
 686        score = 1;
 687        cp = nth_line(sb, e->lno);
 688        ep = nth_line(sb, e->lno + e->num_lines);
 689        while (cp < ep) {
 690                unsigned ch = *((unsigned char *)cp);
 691                if (isalnum(ch))
 692                        score++;
 693                cp++;
 694        }
 695        e->score = score;
 696        return score;
 697}
 698
 699static void copy_split_if_better(struct scoreboard *sb,
 700                                 struct blame_entry *best_so_far,
 701                                 struct blame_entry *this)
 702{
 703        int i;
 704
 705        if (!this[1].suspect)
 706                return;
 707        if (best_so_far[1].suspect) {
 708                if (ent_score(sb, &this[1]) < ent_score(sb, &best_so_far[1]))
 709                        return;
 710        }
 711
 712        for (i = 0; i < 3; i++)
 713                origin_incref(this[i].suspect);
 714        decref_split(best_so_far);
 715        memcpy(best_so_far, this, sizeof(struct blame_entry [3]));
 716}
 717
 718static void find_copy_in_blob(struct scoreboard *sb,
 719                              struct blame_entry *ent,
 720                              struct origin *parent,
 721                              struct blame_entry *split,
 722                              mmfile_t *file_p)
 723{
 724        const char *cp;
 725        int cnt;
 726        mmfile_t file_o;
 727        struct patch *patch;
 728        int i, plno, tlno;
 729
 730        cp = nth_line(sb, ent->lno);
 731        file_o.ptr = (char*) cp;
 732        cnt = ent->num_lines;
 733
 734        while (cnt && cp < sb->final_buf + sb->final_buf_size) {
 735                if (*cp++ == '\n')
 736                        cnt--;
 737        }
 738        file_o.size = cp - file_o.ptr;
 739
 740        patch = compare_buffer(file_p, &file_o, 1);
 741
 742        memset(split, 0, sizeof(struct blame_entry [3]));
 743        plno = tlno = 0;
 744        for (i = 0; i < patch->num; i++) {
 745                struct chunk *chunk = &patch->chunks[i];
 746
 747                /* tlno to chunk->same are the same as ent */
 748                if (ent->num_lines <= tlno)
 749                        break;
 750                if (tlno < chunk->same) {
 751                        struct blame_entry this[3];
 752                        split_overlap(this, ent,
 753                                      tlno + ent->s_lno, plno,
 754                                      chunk->same + ent->s_lno,
 755                                      parent);
 756                        copy_split_if_better(sb, split, this);
 757                        decref_split(this);
 758                }
 759                plno = chunk->p_next;
 760                tlno = chunk->t_next;
 761        }
 762        free_patch(patch);
 763}
 764
 765static int find_move_in_parent(struct scoreboard *sb,
 766                               struct origin *target,
 767                               struct origin *parent)
 768{
 769        int last_in_target;
 770        struct blame_entry *e, split[3];
 771        mmfile_t file_p;
 772        char type[10];
 773        char *blob_p;
 774
 775        last_in_target = find_last_in_target(sb, target);
 776        if (last_in_target < 0)
 777                return 1; /* nothing remains for this target */
 778
 779        blob_p = read_sha1_file(parent->blob_sha1, type,
 780                                (unsigned long *) &file_p.size);
 781        file_p.ptr = blob_p;
 782        if (!file_p.ptr) {
 783                free(blob_p);
 784                return 0;
 785        }
 786
 787        for (e = sb->ent; e; e = e->next) {
 788                if (e->guilty || cmp_suspect(e->suspect, target))
 789                        continue;
 790                find_copy_in_blob(sb, e, parent, split, &file_p);
 791                if (split[1].suspect &&
 792                    blame_move_score < ent_score(sb, &split[1]))
 793                        split_blame(sb, split, e);
 794                decref_split(split);
 795        }
 796        free(blob_p);
 797        return 0;
 798}
 799
 800static int find_copy_in_parent(struct scoreboard *sb,
 801                               struct origin *target,
 802                               struct commit *parent,
 803                               struct origin *porigin,
 804                               int opt)
 805{
 806        struct diff_options diff_opts;
 807        const char *paths[1];
 808        struct blame_entry *e;
 809        int i, j;
 810        struct blame_list {
 811                struct blame_entry *ent;
 812                struct blame_entry split[3];
 813        } *blame_list;
 814        int num_ents;
 815
 816        /* Count the number of entries the target is suspected for,
 817         * and prepare a list of entry and the best split.
 818         */
 819        for (e = sb->ent, num_ents = 0; e; e = e->next)
 820                if (!e->guilty && !cmp_suspect(e->suspect, target))
 821                        num_ents++;
 822        if (!num_ents)
 823                return 1; /* nothing remains for this target */
 824
 825        blame_list = xcalloc(num_ents, sizeof(struct blame_list));
 826        for (e = sb->ent, i = 0; e; e = e->next)
 827                if (!e->guilty && !cmp_suspect(e->suspect, target))
 828                        blame_list[i++].ent = e;
 829
 830        diff_setup(&diff_opts);
 831        diff_opts.recursive = 1;
 832        diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;
 833
 834        /* Try "find copies harder" on new path */
 835        if ((opt & PICKAXE_BLAME_COPY_HARDER) &&
 836            (!porigin || strcmp(target->path, porigin->path))) {
 837                diff_opts.detect_rename = DIFF_DETECT_COPY;
 838                diff_opts.find_copies_harder = 1;
 839        }
 840        paths[0] = NULL;
 841        diff_tree_setup_paths(paths, &diff_opts);
 842        if (diff_setup_done(&diff_opts) < 0)
 843                die("diff-setup");
 844        diff_tree_sha1(parent->tree->object.sha1,
 845                       target->commit->tree->object.sha1,
 846                       "", &diff_opts);
 847        diffcore_std(&diff_opts);
 848
 849        for (i = 0; i < diff_queued_diff.nr; i++) {
 850                struct diff_filepair *p = diff_queued_diff.queue[i];
 851                struct origin *norigin;
 852                mmfile_t file_p;
 853                char type[10];
 854                char *blob;
 855                struct blame_entry this[3];
 856
 857                if (!DIFF_FILE_VALID(p->one))
 858                        continue; /* does not exist in parent */
 859                if (porigin && !strcmp(p->one->path, porigin->path))
 860                        /* find_move already dealt with this path */
 861                        continue;
 862
 863                norigin = get_origin(sb, parent, p->one->path);
 864                hashcpy(norigin->blob_sha1, p->one->sha1);
 865                blob = read_sha1_file(norigin->blob_sha1, type,
 866                                      (unsigned long *) &file_p.size);
 867                file_p.ptr = blob;
 868                if (!file_p.ptr)
 869                        continue;
 870
 871                for (j = 0; j < num_ents; j++) {
 872                        find_copy_in_blob(sb, blame_list[j].ent, norigin,
 873                                          this, &file_p);
 874                        copy_split_if_better(sb, blame_list[j].split,
 875                                             this);
 876                        decref_split(this);
 877                }
 878                free(blob);
 879                origin_decref(norigin);
 880        }
 881        diff_flush(&diff_opts);
 882
 883        for (j = 0; j < num_ents; j++) {
 884                struct blame_entry *split = blame_list[j].split;
 885                if (split[1].suspect &&
 886                    blame_copy_score < ent_score(sb, &split[1]))
 887                        split_blame(sb, split, blame_list[j].ent);
 888                decref_split(split);
 889        }
 890        free(blame_list);
 891
 892        return 0;
 893}
 894
 895#define MAXPARENT 16
 896
 897static void pass_blame(struct scoreboard *sb, struct origin *origin, int opt)
 898{
 899        int i, pass;
 900        struct commit *commit = origin->commit;
 901        struct commit_list *parent;
 902        struct origin *parent_origin[MAXPARENT], *porigin;
 903
 904        memset(parent_origin, 0, sizeof(parent_origin));
 905
 906        /* The first pass looks for unrenamed path to optimize for
 907         * common cases, then we look for renames in the second pass.
 908         */
 909        for (pass = 0; pass < 2; pass++) {
 910                struct origin *(*find)(struct scoreboard *,
 911                                       struct commit *, struct origin *);
 912                find = pass ? find_rename : find_origin;
 913
 914                for (i = 0, parent = commit->parents;
 915                     i < MAXPARENT && parent;
 916                     parent = parent->next, i++) {
 917                        struct commit *p = parent->item;
 918                        int j, same;
 919
 920                        if (parent_origin[i])
 921                                continue;
 922                        if (parse_commit(p))
 923                                continue;
 924                        porigin = find(sb, p, origin);
 925                        if (!porigin)
 926                                continue;
 927                        if (!hashcmp(porigin->blob_sha1, origin->blob_sha1)) {
 928                                struct blame_entry *e;
 929                                for (e = sb->ent; e; e = e->next)
 930                                        if (e->suspect == origin) {
 931                                                origin_incref(porigin);
 932                                                origin_decref(e->suspect);
 933                                                e->suspect = porigin;
 934                                        }
 935                                origin_decref(porigin);
 936                                goto finish;
 937                        }
 938                        for (j = same = 0; j < i; j++)
 939                                if (!hashcmp(parent_origin[j]->blob_sha1,
 940                                             porigin->blob_sha1)) {
 941                                        same = 1;
 942                                        break;
 943                                }
 944                        if (!same)
 945                                parent_origin[i] = porigin;
 946                        else
 947                                origin_decref(porigin);
 948                }
 949        }
 950
 951        for (i = 0, parent = commit->parents;
 952             i < MAXPARENT && parent;
 953             parent = parent->next, i++) {
 954                struct origin *porigin = parent_origin[i];
 955                if (!porigin)
 956                        continue;
 957                if (pass_blame_to_parent(sb, origin, porigin))
 958                        goto finish;
 959        }
 960
 961        /*
 962         * Optionally run "miff" to find moves in parents' files here.
 963         */
 964        if (opt & PICKAXE_BLAME_MOVE)
 965                for (i = 0, parent = commit->parents;
 966                     i < MAXPARENT && parent;
 967                     parent = parent->next, i++) {
 968                        struct origin *porigin = parent_origin[i];
 969                        if (!porigin)
 970                                continue;
 971                        if (find_move_in_parent(sb, origin, porigin))
 972                                goto finish;
 973                }
 974
 975        /*
 976         * Optionally run "ciff" to find copies from parents' files here.
 977         */
 978        if (opt & PICKAXE_BLAME_COPY)
 979                for (i = 0, parent = commit->parents;
 980                     i < MAXPARENT && parent;
 981                     parent = parent->next, i++) {
 982                        struct origin *porigin = parent_origin[i];
 983                        if (find_copy_in_parent(sb, origin, parent->item,
 984                                                porigin, opt))
 985                                goto finish;
 986                }
 987
 988 finish:
 989        for (i = 0; i < MAXPARENT; i++)
 990                origin_decref(parent_origin[i]);
 991}
 992
 993static void assign_blame(struct scoreboard *sb, struct rev_info *revs, int opt)
 994{
 995        while (1) {
 996                struct blame_entry *ent;
 997                struct commit *commit;
 998                struct origin *suspect = NULL;
 999
1000                /* find one suspect to break down */
1001                for (ent = sb->ent; !suspect && ent; ent = ent->next)
1002                        if (!ent->guilty)
1003                                suspect = ent->suspect;
1004                if (!suspect)
1005                        return; /* all done */
1006
1007                origin_incref(suspect);
1008                commit = suspect->commit;
1009                parse_commit(commit);
1010                if (!(commit->object.flags & UNINTERESTING) &&
1011                    !(revs->max_age != -1 && commit->date  < revs->max_age))
1012                        pass_blame(sb, suspect, opt);
1013
1014                /* Take responsibility for the remaining entries */
1015                for (ent = sb->ent; ent; ent = ent->next)
1016                        if (!cmp_suspect(ent->suspect, suspect))
1017                                ent->guilty = 1;
1018                origin_decref(suspect);
1019
1020                if (DEBUG) /* sanity */
1021                        sanity_check_refcnt(sb);
1022        }
1023}
1024
1025static const char *format_time(unsigned long time, const char *tz_str,
1026                               int show_raw_time)
1027{
1028        static char time_buf[128];
1029        time_t t = time;
1030        int minutes, tz;
1031        struct tm *tm;
1032
1033        if (show_raw_time) {
1034                sprintf(time_buf, "%lu %s", time, tz_str);
1035                return time_buf;
1036        }
1037
1038        tz = atoi(tz_str);
1039        minutes = tz < 0 ? -tz : tz;
1040        minutes = (minutes / 100)*60 + (minutes % 100);
1041        minutes = tz < 0 ? -minutes : minutes;
1042        t = time + minutes * 60;
1043        tm = gmtime(&t);
1044
1045        strftime(time_buf, sizeof(time_buf), "%Y-%m-%d %H:%M:%S ", tm);
1046        strcat(time_buf, tz_str);
1047        return time_buf;
1048}
1049
1050struct commit_info
1051{
1052        char *author;
1053        char *author_mail;
1054        unsigned long author_time;
1055        char *author_tz;
1056
1057        /* filled only when asked for details */
1058        char *committer;
1059        char *committer_mail;
1060        unsigned long committer_time;
1061        char *committer_tz;
1062
1063        char *summary;
1064};
1065
1066static void get_ac_line(const char *inbuf, const char *what,
1067                        int bufsz, char *person, char **mail,
1068                        unsigned long *time, char **tz)
1069{
1070        int len;
1071        char *tmp, *endp;
1072
1073        tmp = strstr(inbuf, what);
1074        if (!tmp)
1075                goto error_out;
1076        tmp += strlen(what);
1077        endp = strchr(tmp, '\n');
1078        if (!endp)
1079                len = strlen(tmp);
1080        else
1081                len = endp - tmp;
1082        if (bufsz <= len) {
1083        error_out:
1084                /* Ugh */
1085                person = *mail = *tz = "(unknown)";
1086                *time = 0;
1087                return;
1088        }
1089        memcpy(person, tmp, len);
1090
1091        tmp = person;
1092        tmp += len;
1093        *tmp = 0;
1094        while (*tmp != ' ')
1095                tmp--;
1096        *tz = tmp+1;
1097
1098        *tmp = 0;
1099        while (*tmp != ' ')
1100                tmp--;
1101        *time = strtoul(tmp, NULL, 10);
1102
1103        *tmp = 0;
1104        while (*tmp != ' ')
1105                tmp--;
1106        *mail = tmp + 1;
1107        *tmp = 0;
1108}
1109
1110static void get_commit_info(struct commit *commit,
1111                            struct commit_info *ret,
1112                            int detailed)
1113{
1114        int len;
1115        char *tmp, *endp;
1116        static char author_buf[1024];
1117        static char committer_buf[1024];
1118        static char summary_buf[1024];
1119
1120        /* We've operated without save_commit_buffer, so
1121         * we now need to populate them for output.
1122         */
1123        if (!commit->buffer) {
1124                char type[20];
1125                unsigned long size;
1126                commit->buffer =
1127                        read_sha1_file(commit->object.sha1, type, &size);
1128        }
1129        ret->author = author_buf;
1130        get_ac_line(commit->buffer, "\nauthor ",
1131                    sizeof(author_buf), author_buf, &ret->author_mail,
1132                    &ret->author_time, &ret->author_tz);
1133
1134        if (!detailed)
1135                return;
1136
1137        ret->committer = committer_buf;
1138        get_ac_line(commit->buffer, "\ncommitter ",
1139                    sizeof(committer_buf), committer_buf, &ret->committer_mail,
1140                    &ret->committer_time, &ret->committer_tz);
1141
1142        ret->summary = summary_buf;
1143        tmp = strstr(commit->buffer, "\n\n");
1144        if (!tmp) {
1145        error_out:
1146                sprintf(summary_buf, "(%s)", sha1_to_hex(commit->object.sha1));
1147                return;
1148        }
1149        tmp += 2;
1150        endp = strchr(tmp, '\n');
1151        if (!endp)
1152                goto error_out;
1153        len = endp - tmp;
1154        if (len >= sizeof(summary_buf))
1155                goto error_out;
1156        memcpy(summary_buf, tmp, len);
1157        summary_buf[len] = 0;
1158}
1159
1160#define OUTPUT_ANNOTATE_COMPAT  001
1161#define OUTPUT_LONG_OBJECT_NAME 002
1162#define OUTPUT_RAW_TIMESTAMP    004
1163#define OUTPUT_PORCELAIN        010
1164#define OUTPUT_SHOW_NAME        020
1165#define OUTPUT_SHOW_NUMBER      040
1166#define OUTPUT_SHOW_SCORE      0100
1167
1168static void emit_porcelain(struct scoreboard *sb, struct blame_entry *ent)
1169{
1170        int cnt;
1171        const char *cp;
1172        struct origin *suspect = ent->suspect;
1173        char hex[41];
1174
1175        strcpy(hex, sha1_to_hex(suspect->commit->object.sha1));
1176        printf("%s%c%d %d %d\n",
1177               hex,
1178               ent->guilty ? ' ' : '*', // purely for debugging
1179               ent->s_lno + 1,
1180               ent->lno + 1,
1181               ent->num_lines);
1182        if (!(suspect->commit->object.flags & METAINFO_SHOWN)) {
1183                struct commit_info ci;
1184                suspect->commit->object.flags |= METAINFO_SHOWN;
1185                get_commit_info(suspect->commit, &ci, 1);
1186                printf("author %s\n", ci.author);
1187                printf("author-mail %s\n", ci.author_mail);
1188                printf("author-time %lu\n", ci.author_time);
1189                printf("author-tz %s\n", ci.author_tz);
1190                printf("committer %s\n", ci.committer);
1191                printf("committer-mail %s\n", ci.committer_mail);
1192                printf("committer-time %lu\n", ci.committer_time);
1193                printf("committer-tz %s\n", ci.committer_tz);
1194                printf("filename %s\n", suspect->path);
1195                printf("summary %s\n", ci.summary);
1196        }
1197        else if (suspect->commit->object.flags & MORE_THAN_ONE_PATH)
1198                printf("filename %s\n", suspect->path);
1199
1200        cp = nth_line(sb, ent->lno);
1201        for (cnt = 0; cnt < ent->num_lines; cnt++) {
1202                char ch;
1203                if (cnt)
1204                        printf("%s %d %d\n", hex,
1205                               ent->s_lno + 1 + cnt,
1206                               ent->lno + 1 + cnt);
1207                putchar('\t');
1208                do {
1209                        ch = *cp++;
1210                        putchar(ch);
1211                } while (ch != '\n' &&
1212                         cp < sb->final_buf + sb->final_buf_size);
1213        }
1214}
1215
1216static void emit_other(struct scoreboard *sb, struct blame_entry *ent, int opt)
1217{
1218        int cnt;
1219        const char *cp;
1220        struct origin *suspect = ent->suspect;
1221        struct commit_info ci;
1222        char hex[41];
1223        int show_raw_time = !!(opt & OUTPUT_RAW_TIMESTAMP);
1224
1225        get_commit_info(suspect->commit, &ci, 1);
1226        strcpy(hex, sha1_to_hex(suspect->commit->object.sha1));
1227
1228        cp = nth_line(sb, ent->lno);
1229        for (cnt = 0; cnt < ent->num_lines; cnt++) {
1230                char ch;
1231
1232                printf("%.*s", (opt & OUTPUT_LONG_OBJECT_NAME) ? 40 : 8, hex);
1233                if (opt & OUTPUT_ANNOTATE_COMPAT)
1234                        printf("\t(%10s\t%10s\t%d)", ci.author,
1235                               format_time(ci.author_time, ci.author_tz,
1236                                           show_raw_time),
1237                               ent->lno + 1 + cnt);
1238                else {
1239                        if (opt & OUTPUT_SHOW_SCORE)
1240                                printf(" %*d %02d",
1241                                       max_score_digits, ent->score,
1242                                       ent->suspect->refcnt);
1243                        if (opt & OUTPUT_SHOW_NAME)
1244                                printf(" %-*.*s", longest_file, longest_file,
1245                                       suspect->path);
1246                        if (opt & OUTPUT_SHOW_NUMBER)
1247                                printf(" %*d", max_orig_digits,
1248                                       ent->s_lno + 1 + cnt);
1249                        printf(" (%-*.*s %10s %*d) ",
1250                               longest_author, longest_author, ci.author,
1251                               format_time(ci.author_time, ci.author_tz,
1252                                           show_raw_time),
1253                               max_digits, ent->lno + 1 + cnt);
1254                }
1255                do {
1256                        ch = *cp++;
1257                        putchar(ch);
1258                } while (ch != '\n' &&
1259                         cp < sb->final_buf + sb->final_buf_size);
1260        }
1261}
1262
1263static void output(struct scoreboard *sb, int option)
1264{
1265        struct blame_entry *ent;
1266
1267        if (option & OUTPUT_PORCELAIN) {
1268                for (ent = sb->ent; ent; ent = ent->next) {
1269                        struct blame_entry *oth;
1270                        struct origin *suspect = ent->suspect;
1271                        struct commit *commit = suspect->commit;
1272                        if (commit->object.flags & MORE_THAN_ONE_PATH)
1273                                continue;
1274                        for (oth = ent->next; oth; oth = oth->next) {
1275                                if ((oth->suspect->commit != commit) ||
1276                                    !strcmp(oth->suspect->path, suspect->path))
1277                                        continue;
1278                                commit->object.flags |= MORE_THAN_ONE_PATH;
1279                                break;
1280                        }
1281                }
1282        }
1283
1284        for (ent = sb->ent; ent; ent = ent->next) {
1285                if (option & OUTPUT_PORCELAIN)
1286                        emit_porcelain(sb, ent);
1287                else {
1288                        emit_other(sb, ent, option);
1289                }
1290        }
1291}
1292
1293static int prepare_lines(struct scoreboard *sb)
1294{
1295        const char *buf = sb->final_buf;
1296        unsigned long len = sb->final_buf_size;
1297        int num = 0, incomplete = 0, bol = 1;
1298
1299        if (len && buf[len-1] != '\n')
1300                incomplete++; /* incomplete line at the end */
1301        while (len--) {
1302                if (bol) {
1303                        sb->lineno = xrealloc(sb->lineno,
1304                                              sizeof(int* ) * (num + 1));
1305                        sb->lineno[num] = buf - sb->final_buf;
1306                        bol = 0;
1307                }
1308                if (*buf++ == '\n') {
1309                        num++;
1310                        bol = 1;
1311                }
1312        }
1313        sb->lineno = xrealloc(sb->lineno,
1314                              sizeof(int* ) * (num + incomplete + 1));
1315        sb->lineno[num + incomplete] = buf - sb->final_buf;
1316        sb->num_lines = num + incomplete;
1317        return sb->num_lines;
1318}
1319
1320static int read_ancestry(const char *graft_file)
1321{
1322        FILE *fp = fopen(graft_file, "r");
1323        char buf[1024];
1324        if (!fp)
1325                return -1;
1326        while (fgets(buf, sizeof(buf), fp)) {
1327                /* The format is just "Commit Parent1 Parent2 ...\n" */
1328                int len = strlen(buf);
1329                struct commit_graft *graft = read_graft_line(buf, len);
1330                register_commit_graft(graft, 0);
1331        }
1332        fclose(fp);
1333        return 0;
1334}
1335
1336static int lineno_width(int lines)
1337{
1338        int i, width;
1339
1340        for (width = 1, i = 10; i <= lines + 1; width++)
1341                i *= 10;
1342        return width;
1343}
1344
1345static void find_alignment(struct scoreboard *sb, int *option)
1346{
1347        int longest_src_lines = 0;
1348        int longest_dst_lines = 0;
1349        unsigned largest_score = 0;
1350        struct blame_entry *e;
1351
1352        for (e = sb->ent; e; e = e->next) {
1353                struct origin *suspect = e->suspect;
1354                struct commit_info ci;
1355                int num;
1356
1357                if (!(suspect->commit->object.flags & METAINFO_SHOWN)) {
1358                        suspect->commit->object.flags |= METAINFO_SHOWN;
1359                        get_commit_info(suspect->commit, &ci, 1);
1360                        if (strcmp(suspect->path, sb->path))
1361                                *option |= OUTPUT_SHOW_NAME;
1362                        num = strlen(suspect->path);
1363                        if (longest_file < num)
1364                                longest_file = num;
1365                        num = strlen(ci.author);
1366                        if (longest_author < num)
1367                                longest_author = num;
1368                }
1369                num = e->s_lno + e->num_lines;
1370                if (longest_src_lines < num)
1371                        longest_src_lines = num;
1372                num = e->lno + e->num_lines;
1373                if (longest_dst_lines < num)
1374                        longest_dst_lines = num;
1375                if (largest_score < ent_score(sb, e))
1376                        largest_score = ent_score(sb, e);
1377        }
1378        max_orig_digits = lineno_width(longest_src_lines);
1379        max_digits = lineno_width(longest_dst_lines);
1380        max_score_digits = lineno_width(largest_score);
1381}
1382
1383static void sanity_check_refcnt(struct scoreboard *sb)
1384{
1385        int baa = 0;
1386        struct blame_entry *ent;
1387
1388        for (ent = sb->ent; ent; ent = ent->next) {
1389                /* Nobody should have zero or negative refcnt */
1390                if (ent->suspect->refcnt <= 0)
1391                        baa = 1;
1392        }
1393        for (ent = sb->ent; ent; ent = ent->next) {
1394                /* Mark the ones that haven't been checked */
1395                if (0 < ent->suspect->refcnt)
1396                        ent->suspect->refcnt = -ent->suspect->refcnt;
1397        }
1398        for (ent = sb->ent; ent; ent = ent->next) {
1399                /* then pick each and see if they have the the correct
1400                 * refcnt; note that ->util caching means origin's refcnt
1401                 * may well be greater than the number of blame entries
1402                 * that use it.
1403                 */
1404                int found;
1405                struct blame_entry *e;
1406                struct origin *suspect = ent->suspect;
1407
1408                if (0 < suspect->refcnt)
1409                        continue;
1410                suspect->refcnt = -suspect->refcnt; /* Unmark */
1411                for (found = 0, e = sb->ent; e; e = e->next) {
1412                        if (e->suspect != suspect)
1413                                continue;
1414                        found++;
1415                }
1416                if (suspect->refcnt < found)
1417                        baa = 1;
1418        }
1419        if (baa) {
1420                int opt = 0160;
1421                find_alignment(sb, &opt);
1422                output(sb, opt);
1423                die("Baa!");
1424        }
1425}
1426
1427static int has_path_in_work_tree(const char *path)
1428{
1429        struct stat st;
1430        return !lstat(path, &st);
1431}
1432
1433static unsigned parse_score(const char *arg)
1434{
1435        char *end;
1436        unsigned long score = strtoul(arg, &end, 10);
1437        if (*end)
1438                return 0;
1439        return score;
1440}
1441
1442static const char *add_prefix(const char *prefix, const char *path)
1443{
1444        if (!prefix || !prefix[0])
1445                return path;
1446        return prefix_path(prefix, strlen(prefix), path);
1447}
1448
1449int cmd_pickaxe(int argc, const char **argv, const char *prefix)
1450{
1451        struct rev_info revs;
1452        const char *path;
1453        struct scoreboard sb;
1454        struct origin *o;
1455        struct blame_entry *ent;
1456        int i, seen_dashdash, unk, opt;
1457        long bottom, top, lno;
1458        int output_option = 0;
1459        const char *revs_file = NULL;
1460        const char *final_commit_name = NULL;
1461        char type[10];
1462
1463        save_commit_buffer = 0;
1464
1465        opt = 0;
1466        bottom = top = 0;
1467        seen_dashdash = 0;
1468        for (unk = i = 1; i < argc; i++) {
1469                const char *arg = argv[i];
1470                if (*arg != '-')
1471                        break;
1472                else if (!strcmp("-c", arg))
1473                        output_option |= OUTPUT_ANNOTATE_COMPAT;
1474                else if (!strcmp("-t", arg))
1475                        output_option |= OUTPUT_RAW_TIMESTAMP;
1476                else if (!strcmp("-l", arg))
1477                        output_option |= OUTPUT_LONG_OBJECT_NAME;
1478                else if (!strcmp("-S", arg) && ++i < argc)
1479                        revs_file = argv[i];
1480                else if (!strncmp("-M", arg, 2)) {
1481                        opt |= PICKAXE_BLAME_MOVE;
1482                        blame_move_score = parse_score(arg+2);
1483                }
1484                else if (!strncmp("-C", arg, 2)) {
1485                        if (opt & PICKAXE_BLAME_COPY)
1486                                opt |= PICKAXE_BLAME_COPY_HARDER;
1487                        opt |= PICKAXE_BLAME_COPY | PICKAXE_BLAME_MOVE;
1488                        blame_copy_score = parse_score(arg+2);
1489                }
1490                else if (!strncmp("-L", arg, 2)) {
1491                        char *term;
1492                        if (!arg[2]) {
1493                                if (++i >= argc)
1494                                        usage(pickaxe_usage);
1495                                arg = argv[i];
1496                        }
1497                        else
1498                                arg += 2;
1499                        if (bottom || top)
1500                                die("More than one '-L n,m' option given");
1501                        bottom = strtol(arg, &term, 10);
1502                        if (*term == ',') {
1503                                top = strtol(term + 1, &term, 10);
1504                                if (*term)
1505                                        usage(pickaxe_usage);
1506                        }
1507                        if (bottom && top && top < bottom) {
1508                                unsigned long tmp;
1509                                tmp = top; top = bottom; bottom = tmp;
1510                        }
1511                }
1512                else if (!strcmp("--score-debug", arg))
1513                        output_option |= OUTPUT_SHOW_SCORE;
1514                else if (!strcmp("-f", arg) ||
1515                         !strcmp("--show-name", arg))
1516                        output_option |= OUTPUT_SHOW_NAME;
1517                else if (!strcmp("-n", arg) ||
1518                         !strcmp("--show-number", arg))
1519                        output_option |= OUTPUT_SHOW_NUMBER;
1520                else if (!strcmp("-p", arg) ||
1521                         !strcmp("--porcelain", arg))
1522                        output_option |= OUTPUT_PORCELAIN;
1523                else if (!strcmp("--", arg)) {
1524                        seen_dashdash = 1;
1525                        i++;
1526                        break;
1527                }
1528                else
1529                        argv[unk++] = arg;
1530        }
1531
1532        if (!blame_move_score)
1533                blame_move_score = BLAME_DEFAULT_MOVE_SCORE;
1534        if (!blame_copy_score)
1535                blame_copy_score = BLAME_DEFAULT_COPY_SCORE;
1536
1537        /* We have collected options unknown to us in argv[1..unk]
1538         * which are to be passed to revision machinery if we are
1539         * going to do the "bottom" procesing.
1540         *
1541         * The remaining are:
1542         *
1543         * (1) if seen_dashdash, its either
1544         *     "-options -- <path>" or
1545         *     "-options -- <path> <rev>".
1546         *     but the latter is allowed only if there is no
1547         *     options that we passed to revision machinery.
1548         *
1549         * (2) otherwise, we may have "--" somewhere later and
1550         *     might be looking at the first one of multiple 'rev'
1551         *     parameters (e.g. " master ^next ^maint -- path").
1552         *     See if there is a dashdash first, and give the
1553         *     arguments before that to revision machinery.
1554         *     After that there must be one 'path'.
1555         *
1556         * (3) otherwise, its one of the three:
1557         *     "-options <path> <rev>"
1558         *     "-options <rev> <path>"
1559         *     "-options <path>"
1560         *     but again the first one is allowed only if
1561         *     there is no options that we passed to revision
1562         *     machinery.
1563         */
1564
1565        if (seen_dashdash) {
1566                /* (1) */
1567                if (argc <= i)
1568                        usage(pickaxe_usage);
1569                path = add_prefix(prefix, argv[i]);
1570                if (i + 1 == argc - 1) {
1571                        if (unk != 1)
1572                                usage(pickaxe_usage);
1573                        argv[unk++] = argv[i + 1];
1574                }
1575                else if (i + 1 != argc)
1576                        /* garbage at end */
1577                        usage(pickaxe_usage);
1578        }
1579        else {
1580                int j;
1581                for (j = i; !seen_dashdash && j < argc; j++)
1582                        if (!strcmp(argv[j], "--"))
1583                                seen_dashdash = j;
1584                if (seen_dashdash) {
1585                        if (seen_dashdash + 1 != argc - 1)
1586                                usage(pickaxe_usage);
1587                        path = add_prefix(prefix, argv[seen_dashdash + 1]);
1588                        for (j = i; j < seen_dashdash; j++)
1589                                argv[unk++] = argv[j];
1590                }
1591                else {
1592                        /* (3) */
1593                        path = add_prefix(prefix, argv[i]);
1594                        if (i + 1 == argc - 1) {
1595                                final_commit_name = argv[i + 1];
1596
1597                                /* if (unk == 1) we could be getting
1598                                 * old-style
1599                                 */
1600                                if (unk == 1 && !has_path_in_work_tree(path)) {
1601                                        path = add_prefix(prefix, argv[i + 1]);
1602                                        final_commit_name = argv[i];
1603                                }
1604                        }
1605                        else if (i != argc - 1)
1606                                usage(pickaxe_usage); /* garbage at end */
1607
1608                        if (!has_path_in_work_tree(path))
1609                                die("cannot stat path %s: %s",
1610                                    path, strerror(errno));
1611                }
1612        }
1613
1614        if (final_commit_name)
1615                argv[unk++] = final_commit_name;
1616
1617        /* Now we got rev and path.  We do not want the path pruning
1618         * but we may want "bottom" processing.
1619         */
1620        argv[unk] = NULL;
1621
1622        init_revisions(&revs, NULL);
1623        setup_revisions(unk, argv, &revs, "HEAD");
1624        memset(&sb, 0, sizeof(sb));
1625
1626        /* There must be one and only one positive commit in the
1627         * revs->pending array.
1628         */
1629        for (i = 0; i < revs.pending.nr; i++) {
1630                struct object *obj = revs.pending.objects[i].item;
1631                if (obj->flags & UNINTERESTING)
1632                        continue;
1633                while (obj->type == OBJ_TAG)
1634                        obj = deref_tag(obj, NULL, 0);
1635                if (obj->type != OBJ_COMMIT)
1636                        die("Non commit %s?",
1637                            revs.pending.objects[i].name);
1638                if (sb.final)
1639                        die("More than one commit to dig from %s and %s?",
1640                            revs.pending.objects[i].name,
1641                            final_commit_name);
1642                sb.final = (struct commit *) obj;
1643                final_commit_name = revs.pending.objects[i].name;
1644        }
1645
1646        if (!sb.final) {
1647                /* "--not A B -- path" without anything positive */
1648                unsigned char head_sha1[20];
1649
1650                final_commit_name = "HEAD";
1651                if (get_sha1(final_commit_name, head_sha1))
1652                        die("No such ref: HEAD");
1653                sb.final = lookup_commit_reference(head_sha1);
1654                add_pending_object(&revs, &(sb.final->object), "HEAD");
1655        }
1656
1657        /* If we have bottom, this will mark the ancestors of the
1658         * bottom commits we would reach while traversing as
1659         * uninteresting.
1660         */
1661        prepare_revision_walk(&revs);
1662
1663        o = get_origin(&sb, sb.final, path);
1664        if (fill_blob_sha1(o))
1665                die("no such path %s in %s", path, final_commit_name);
1666
1667        sb.final_buf = read_sha1_file(o->blob_sha1, type, &sb.final_buf_size);
1668        lno = prepare_lines(&sb);
1669
1670        if (bottom < 1)
1671                bottom = 1;
1672        if (top < 1)
1673                top = lno;
1674        bottom--;
1675        if (lno < top)
1676                die("file %s has only %lu lines", path, lno);
1677
1678        ent = xcalloc(1, sizeof(*ent));
1679        ent->lno = bottom;
1680        ent->num_lines = top - bottom;
1681        ent->suspect = o;
1682        ent->s_lno = bottom;
1683
1684        sb.ent = ent;
1685        sb.path = path;
1686
1687        if (revs_file && read_ancestry(revs_file))
1688                die("reading graft file %s failed: %s",
1689                    revs_file, strerror(errno));
1690
1691        assign_blame(&sb, &revs, opt);
1692
1693        coalesce(&sb);
1694
1695        if (!(output_option & OUTPUT_PORCELAIN))
1696                find_alignment(&sb, &output_option);
1697
1698        output(&sb, output_option);
1699        free((void *)sb.final_buf);
1700        for (ent = sb.ent; ent; ) {
1701                struct blame_entry *e = ent->next;
1702                free(ent);
1703                ent = e;
1704        }
1705        return 0;
1706}