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