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