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