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