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