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