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