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