blame: output porcelain "previous" header for each file
[git] / builtin / blame.c
1 /*
2  * Blame
3  *
4  * Copyright (c) 2006, 2014 by its authors
5  * See COPYING for licensing conditions
6  */
7
8 #include "cache.h"
9 #include "refs.h"
10 #include "builtin.h"
11 #include "blob.h"
12 #include "commit.h"
13 #include "tag.h"
14 #include "tree-walk.h"
15 #include "diff.h"
16 #include "diffcore.h"
17 #include "revision.h"
18 #include "quote.h"
19 #include "xdiff-interface.h"
20 #include "cache-tree.h"
21 #include "string-list.h"
22 #include "mailmap.h"
23 #include "mergesort.h"
24 #include "parse-options.h"
25 #include "prio-queue.h"
26 #include "utf8.h"
27 #include "userdiff.h"
28 #include "line-range.h"
29 #include "line-log.h"
30 #include "dir.h"
31 #include "progress.h"
32
33 static char blame_usage[] = N_("git blame [<options>] [<rev-opts>] [<rev>] [--] <file>");
34
35 static const char *blame_opt_usage[] = {
36         blame_usage,
37         "",
38         N_("<rev-opts> are documented in git-rev-list(1)"),
39         NULL
40 };
41
42 static int longest_file;
43 static int longest_author;
44 static int max_orig_digits;
45 static int max_digits;
46 static int max_score_digits;
47 static int show_root;
48 static int reverse;
49 static int blank_boundary;
50 static int incremental;
51 static int xdl_opts;
52 static int abbrev = -1;
53 static int no_whole_file_rename;
54 static int show_progress;
55
56 static struct date_mode blame_date_mode = { DATE_ISO8601 };
57 static size_t blame_date_width;
58
59 static struct string_list mailmap = STRING_LIST_INIT_NODUP;
60
61 #ifndef DEBUG
62 #define DEBUG 0
63 #endif
64
65 /* stats */
66 static int num_read_blob;
67 static int num_get_patch;
68 static int num_commits;
69
70 #define PICKAXE_BLAME_MOVE              01
71 #define PICKAXE_BLAME_COPY              02
72 #define PICKAXE_BLAME_COPY_HARDER       04
73 #define PICKAXE_BLAME_COPY_HARDEST      010
74
75 /*
76  * blame for a blame_entry with score lower than these thresholds
77  * is not passed to the parent using move/copy logic.
78  */
79 static unsigned blame_move_score;
80 static unsigned blame_copy_score;
81 #define BLAME_DEFAULT_MOVE_SCORE        20
82 #define BLAME_DEFAULT_COPY_SCORE        40
83
84 /* Remember to update object flag allocation in object.h */
85 #define METAINFO_SHOWN          (1u<<12)
86 #define MORE_THAN_ONE_PATH      (1u<<13)
87
88 /*
89  * One blob in a commit that is being suspected
90  */
91 struct origin {
92         int refcnt;
93         /* Record preceding blame record for this blob */
94         struct origin *previous;
95         /* origins are put in a list linked via `next' hanging off the
96          * corresponding commit's util field in order to make finding
97          * them fast.  The presence in this chain does not count
98          * towards the origin's reference count.  It is tempting to
99          * let it count as long as the commit is pending examination,
100          * but even under circumstances where the commit will be
101          * present multiple times in the priority queue of unexamined
102          * commits, processing the first instance will not leave any
103          * work requiring the origin data for the second instance.  An
104          * interspersed commit changing that would have to be
105          * preexisting with a different ancestry and with the same
106          * commit date in order to wedge itself between two instances
107          * of the same commit in the priority queue _and_ produce
108          * blame entries relevant for it.  While we don't want to let
109          * us get tripped up by this case, it certainly does not seem
110          * worth optimizing for.
111          */
112         struct origin *next;
113         struct commit *commit;
114         /* `suspects' contains blame entries that may be attributed to
115          * this origin's commit or to parent commits.  When a commit
116          * is being processed, all suspects will be moved, either by
117          * assigning them to an origin in a different commit, or by
118          * shipping them to the scoreboard's ent list because they
119          * cannot be attributed to a different commit.
120          */
121         struct blame_entry *suspects;
122         mmfile_t file;
123         unsigned char blob_sha1[20];
124         unsigned mode;
125         /* guilty gets set when shipping any suspects to the final
126          * blame list instead of other commits
127          */
128         char guilty;
129         char path[FLEX_ARRAY];
130 };
131
132 struct progress_info {
133         struct progress *progress;
134         int blamed_lines;
135 };
136
137 static int diff_hunks(mmfile_t *file_a, mmfile_t *file_b,
138                       xdl_emit_hunk_consume_func_t hunk_func, void *cb_data)
139 {
140         xpparam_t xpp = {0};
141         xdemitconf_t xecfg = {0};
142         xdemitcb_t ecb = {NULL};
143
144         xpp.flags = xdl_opts;
145         xecfg.hunk_func = hunk_func;
146         ecb.priv = cb_data;
147         return xdi_diff(file_a, file_b, &xpp, &xecfg, &ecb);
148 }
149
150 /*
151  * Prepare diff_filespec and convert it using diff textconv API
152  * if the textconv driver exists.
153  * Return 1 if the conversion succeeds, 0 otherwise.
154  */
155 int textconv_object(const char *path,
156                     unsigned mode,
157                     const unsigned char *sha1,
158                     int sha1_valid,
159                     char **buf,
160                     unsigned long *buf_size)
161 {
162         struct diff_filespec *df;
163         struct userdiff_driver *textconv;
164
165         df = alloc_filespec(path);
166         fill_filespec(df, sha1, sha1_valid, mode);
167         textconv = get_textconv(df);
168         if (!textconv) {
169                 free_filespec(df);
170                 return 0;
171         }
172
173         *buf_size = fill_textconv(textconv, df, buf);
174         free_filespec(df);
175         return 1;
176 }
177
178 /*
179  * Given an origin, prepare mmfile_t structure to be used by the
180  * diff machinery
181  */
182 static void fill_origin_blob(struct diff_options *opt,
183                              struct origin *o, mmfile_t *file)
184 {
185         if (!o->file.ptr) {
186                 enum object_type type;
187                 unsigned long file_size;
188
189                 num_read_blob++;
190                 if (DIFF_OPT_TST(opt, ALLOW_TEXTCONV) &&
191                     textconv_object(o->path, o->mode, o->blob_sha1, 1, &file->ptr, &file_size))
192                         ;
193                 else
194                         file->ptr = read_sha1_file(o->blob_sha1, &type, &file_size);
195                 file->size = file_size;
196
197                 if (!file->ptr)
198                         die("Cannot read blob %s for path %s",
199                             sha1_to_hex(o->blob_sha1),
200                             o->path);
201                 o->file = *file;
202         }
203         else
204                 *file = o->file;
205 }
206
207 /*
208  * Origin is refcounted and usually we keep the blob contents to be
209  * reused.
210  */
211 static inline struct origin *origin_incref(struct origin *o)
212 {
213         if (o)
214                 o->refcnt++;
215         return o;
216 }
217
218 static void origin_decref(struct origin *o)
219 {
220         if (o && --o->refcnt <= 0) {
221                 struct origin *p, *l = NULL;
222                 if (o->previous)
223                         origin_decref(o->previous);
224                 free(o->file.ptr);
225                 /* Should be present exactly once in commit chain */
226                 for (p = o->commit->util; p; l = p, p = p->next) {
227                         if (p == o) {
228                                 if (l)
229                                         l->next = p->next;
230                                 else
231                                         o->commit->util = p->next;
232                                 free(o);
233                                 return;
234                         }
235                 }
236                 die("internal error in blame::origin_decref");
237         }
238 }
239
240 static void drop_origin_blob(struct origin *o)
241 {
242         if (o->file.ptr) {
243                 free(o->file.ptr);
244                 o->file.ptr = NULL;
245         }
246 }
247
248 /*
249  * Each group of lines is described by a blame_entry; it can be split
250  * as we pass blame to the parents.  They are arranged in linked lists
251  * kept as `suspects' of some unprocessed origin, or entered (when the
252  * blame origin has been finalized) into the scoreboard structure.
253  * While the scoreboard structure is only sorted at the end of
254  * processing (according to final image line number), the lists
255  * attached to an origin are sorted by the target line number.
256  */
257 struct blame_entry {
258         struct blame_entry *next;
259
260         /* the first line of this group in the final image;
261          * internally all line numbers are 0 based.
262          */
263         int lno;
264
265         /* how many lines this group has */
266         int num_lines;
267
268         /* the commit that introduced this group into the final image */
269         struct origin *suspect;
270
271         /* the line number of the first line of this group in the
272          * suspect's file; internally all line numbers are 0 based.
273          */
274         int s_lno;
275
276         /* how significant this entry is -- cached to avoid
277          * scanning the lines over and over.
278          */
279         unsigned score;
280 };
281
282 /*
283  * Any merge of blames happens on lists of blames that arrived via
284  * different parents in a single suspect.  In this case, we want to
285  * sort according to the suspect line numbers as opposed to the final
286  * image line numbers.  The function body is somewhat longish because
287  * it avoids unnecessary writes.
288  */
289
290 static struct blame_entry *blame_merge(struct blame_entry *list1,
291                                        struct blame_entry *list2)
292 {
293         struct blame_entry *p1 = list1, *p2 = list2,
294                 **tail = &list1;
295
296         if (!p1)
297                 return p2;
298         if (!p2)
299                 return p1;
300
301         if (p1->s_lno <= p2->s_lno) {
302                 do {
303                         tail = &p1->next;
304                         if ((p1 = *tail) == NULL) {
305                                 *tail = p2;
306                                 return list1;
307                         }
308                 } while (p1->s_lno <= p2->s_lno);
309         }
310         for (;;) {
311                 *tail = p2;
312                 do {
313                         tail = &p2->next;
314                         if ((p2 = *tail) == NULL)  {
315                                 *tail = p1;
316                                 return list1;
317                         }
318                 } while (p1->s_lno > p2->s_lno);
319                 *tail = p1;
320                 do {
321                         tail = &p1->next;
322                         if ((p1 = *tail) == NULL) {
323                                 *tail = p2;
324                                 return list1;
325                         }
326                 } while (p1->s_lno <= p2->s_lno);
327         }
328 }
329
330 static void *get_next_blame(const void *p)
331 {
332         return ((struct blame_entry *)p)->next;
333 }
334
335 static void set_next_blame(void *p1, void *p2)
336 {
337         ((struct blame_entry *)p1)->next = p2;
338 }
339
340 /*
341  * Final image line numbers are all different, so we don't need a
342  * three-way comparison here.
343  */
344
345 static int compare_blame_final(const void *p1, const void *p2)
346 {
347         return ((struct blame_entry *)p1)->lno > ((struct blame_entry *)p2)->lno
348                 ? 1 : -1;
349 }
350
351 static int compare_blame_suspect(const void *p1, const void *p2)
352 {
353         const struct blame_entry *s1 = p1, *s2 = p2;
354         /*
355          * to allow for collating suspects, we sort according to the
356          * respective pointer value as the primary sorting criterion.
357          * The actual relation is pretty unimportant as long as it
358          * establishes a total order.  Comparing as integers gives us
359          * that.
360          */
361         if (s1->suspect != s2->suspect)
362                 return (intptr_t)s1->suspect > (intptr_t)s2->suspect ? 1 : -1;
363         if (s1->s_lno == s2->s_lno)
364                 return 0;
365         return s1->s_lno > s2->s_lno ? 1 : -1;
366 }
367
368 static struct blame_entry *blame_sort(struct blame_entry *head,
369                                       int (*compare_fn)(const void *, const void *))
370 {
371         return llist_mergesort (head, get_next_blame, set_next_blame, compare_fn);
372 }
373
374 static int compare_commits_by_reverse_commit_date(const void *a,
375                                                   const void *b,
376                                                   void *c)
377 {
378         return -compare_commits_by_commit_date(a, b, c);
379 }
380
381 /*
382  * The current state of the blame assignment.
383  */
384 struct scoreboard {
385         /* the final commit (i.e. where we started digging from) */
386         struct commit *final;
387         /* Priority queue for commits with unassigned blame records */
388         struct prio_queue commits;
389         struct rev_info *revs;
390         const char *path;
391
392         /*
393          * The contents in the final image.
394          * Used by many functions to obtain contents of the nth line,
395          * indexed with scoreboard.lineno[blame_entry.lno].
396          */
397         const char *final_buf;
398         unsigned long final_buf_size;
399
400         /* linked list of blames */
401         struct blame_entry *ent;
402
403         /* look-up a line in the final buffer */
404         int num_lines;
405         int *lineno;
406 };
407
408 static void sanity_check_refcnt(struct scoreboard *);
409
410 /*
411  * If two blame entries that are next to each other came from
412  * contiguous lines in the same origin (i.e. <commit, path> pair),
413  * merge them together.
414  */
415 static void coalesce(struct scoreboard *sb)
416 {
417         struct blame_entry *ent, *next;
418
419         for (ent = sb->ent; ent && (next = ent->next); ent = next) {
420                 if (ent->suspect == next->suspect &&
421                     ent->s_lno + ent->num_lines == next->s_lno) {
422                         ent->num_lines += next->num_lines;
423                         ent->next = next->next;
424                         origin_decref(next->suspect);
425                         free(next);
426                         ent->score = 0;
427                         next = ent; /* again */
428                 }
429         }
430
431         if (DEBUG) /* sanity */
432                 sanity_check_refcnt(sb);
433 }
434
435 /*
436  * Merge the given sorted list of blames into a preexisting origin.
437  * If there were no previous blames to that commit, it is entered into
438  * the commit priority queue of the score board.
439  */
440
441 static void queue_blames(struct scoreboard *sb, struct origin *porigin,
442                          struct blame_entry *sorted)
443 {
444         if (porigin->suspects)
445                 porigin->suspects = blame_merge(porigin->suspects, sorted);
446         else {
447                 struct origin *o;
448                 for (o = porigin->commit->util; o; o = o->next) {
449                         if (o->suspects) {
450                                 porigin->suspects = sorted;
451                                 return;
452                         }
453                 }
454                 porigin->suspects = sorted;
455                 prio_queue_put(&sb->commits, porigin->commit);
456         }
457 }
458
459 /*
460  * Given a commit and a path in it, create a new origin structure.
461  * The callers that add blame to the scoreboard should use
462  * get_origin() to obtain shared, refcounted copy instead of calling
463  * this function directly.
464  */
465 static struct origin *make_origin(struct commit *commit, const char *path)
466 {
467         struct origin *o;
468         FLEX_ALLOC_STR(o, path, path);
469         o->commit = commit;
470         o->refcnt = 1;
471         o->next = commit->util;
472         commit->util = o;
473         return o;
474 }
475
476 /*
477  * Locate an existing origin or create a new one.
478  * This moves the origin to front position in the commit util list.
479  */
480 static struct origin *get_origin(struct scoreboard *sb,
481                                  struct commit *commit,
482                                  const char *path)
483 {
484         struct origin *o, *l;
485
486         for (o = commit->util, l = NULL; o; l = o, o = o->next) {
487                 if (!strcmp(o->path, path)) {
488                         /* bump to front */
489                         if (l) {
490                                 l->next = o->next;
491                                 o->next = commit->util;
492                                 commit->util = o;
493                         }
494                         return origin_incref(o);
495                 }
496         }
497         return make_origin(commit, path);
498 }
499
500 /*
501  * Fill the blob_sha1 field of an origin if it hasn't, so that later
502  * call to fill_origin_blob() can use it to locate the data.  blob_sha1
503  * for an origin is also used to pass the blame for the entire file to
504  * the parent to detect the case where a child's blob is identical to
505  * that of its parent's.
506  *
507  * This also fills origin->mode for corresponding tree path.
508  */
509 static int fill_blob_sha1_and_mode(struct origin *origin)
510 {
511         if (!is_null_sha1(origin->blob_sha1))
512                 return 0;
513         if (get_tree_entry(origin->commit->object.oid.hash,
514                            origin->path,
515                            origin->blob_sha1, &origin->mode))
516                 goto error_out;
517         if (sha1_object_info(origin->blob_sha1, NULL) != OBJ_BLOB)
518                 goto error_out;
519         return 0;
520  error_out:
521         hashclr(origin->blob_sha1);
522         origin->mode = S_IFINVALID;
523         return -1;
524 }
525
526 /*
527  * We have an origin -- check if the same path exists in the
528  * parent and return an origin structure to represent it.
529  */
530 static struct origin *find_origin(struct scoreboard *sb,
531                                   struct commit *parent,
532                                   struct origin *origin)
533 {
534         struct origin *porigin;
535         struct diff_options diff_opts;
536         const char *paths[2];
537
538         /* First check any existing origins */
539         for (porigin = parent->util; porigin; porigin = porigin->next)
540                 if (!strcmp(porigin->path, origin->path)) {
541                         /*
542                          * The same path between origin and its parent
543                          * without renaming -- the most common case.
544                          */
545                         return origin_incref (porigin);
546                 }
547
548         /* See if the origin->path is different between parent
549          * and origin first.  Most of the time they are the
550          * same and diff-tree is fairly efficient about this.
551          */
552         diff_setup(&diff_opts);
553         DIFF_OPT_SET(&diff_opts, RECURSIVE);
554         diff_opts.detect_rename = 0;
555         diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;
556         paths[0] = origin->path;
557         paths[1] = NULL;
558
559         parse_pathspec(&diff_opts.pathspec,
560                        PATHSPEC_ALL_MAGIC & ~PATHSPEC_LITERAL,
561                        PATHSPEC_LITERAL_PATH, "", paths);
562         diff_setup_done(&diff_opts);
563
564         if (is_null_oid(&origin->commit->object.oid))
565                 do_diff_cache(parent->tree->object.oid.hash, &diff_opts);
566         else
567                 diff_tree_sha1(parent->tree->object.oid.hash,
568                                origin->commit->tree->object.oid.hash,
569                                "", &diff_opts);
570         diffcore_std(&diff_opts);
571
572         if (!diff_queued_diff.nr) {
573                 /* The path is the same as parent */
574                 porigin = get_origin(sb, parent, origin->path);
575                 hashcpy(porigin->blob_sha1, origin->blob_sha1);
576                 porigin->mode = origin->mode;
577         } else {
578                 /*
579                  * Since origin->path is a pathspec, if the parent
580                  * commit had it as a directory, we will see a whole
581                  * bunch of deletion of files in the directory that we
582                  * do not care about.
583                  */
584                 int i;
585                 struct diff_filepair *p = NULL;
586                 for (i = 0; i < diff_queued_diff.nr; i++) {
587                         const char *name;
588                         p = diff_queued_diff.queue[i];
589                         name = p->one->path ? p->one->path : p->two->path;
590                         if (!strcmp(name, origin->path))
591                                 break;
592                 }
593                 if (!p)
594                         die("internal error in blame::find_origin");
595                 switch (p->status) {
596                 default:
597                         die("internal error in blame::find_origin (%c)",
598                             p->status);
599                 case 'M':
600                         porigin = get_origin(sb, parent, origin->path);
601                         hashcpy(porigin->blob_sha1, p->one->oid.hash);
602                         porigin->mode = p->one->mode;
603                         break;
604                 case 'A':
605                 case 'T':
606                         /* Did not exist in parent, or type changed */
607                         break;
608                 }
609         }
610         diff_flush(&diff_opts);
611         clear_pathspec(&diff_opts.pathspec);
612         return porigin;
613 }
614
615 /*
616  * We have an origin -- find the path that corresponds to it in its
617  * parent and return an origin structure to represent it.
618  */
619 static struct origin *find_rename(struct scoreboard *sb,
620                                   struct commit *parent,
621                                   struct origin *origin)
622 {
623         struct origin *porigin = NULL;
624         struct diff_options diff_opts;
625         int i;
626
627         diff_setup(&diff_opts);
628         DIFF_OPT_SET(&diff_opts, RECURSIVE);
629         diff_opts.detect_rename = DIFF_DETECT_RENAME;
630         diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;
631         diff_opts.single_follow = origin->path;
632         diff_setup_done(&diff_opts);
633
634         if (is_null_oid(&origin->commit->object.oid))
635                 do_diff_cache(parent->tree->object.oid.hash, &diff_opts);
636         else
637                 diff_tree_sha1(parent->tree->object.oid.hash,
638                                origin->commit->tree->object.oid.hash,
639                                "", &diff_opts);
640         diffcore_std(&diff_opts);
641
642         for (i = 0; i < diff_queued_diff.nr; i++) {
643                 struct diff_filepair *p = diff_queued_diff.queue[i];
644                 if ((p->status == 'R' || p->status == 'C') &&
645                     !strcmp(p->two->path, origin->path)) {
646                         porigin = get_origin(sb, parent, p->one->path);
647                         hashcpy(porigin->blob_sha1, p->one->oid.hash);
648                         porigin->mode = p->one->mode;
649                         break;
650                 }
651         }
652         diff_flush(&diff_opts);
653         clear_pathspec(&diff_opts.pathspec);
654         return porigin;
655 }
656
657 /*
658  * Append a new blame entry to a given output queue.
659  */
660 static void add_blame_entry(struct blame_entry ***queue, struct blame_entry *e)
661 {
662         origin_incref(e->suspect);
663
664         e->next = **queue;
665         **queue = e;
666         *queue = &e->next;
667 }
668
669 /*
670  * src typically is on-stack; we want to copy the information in it to
671  * a malloced blame_entry that gets added to the given queue.  The
672  * origin of dst loses a refcnt.
673  */
674 static void dup_entry(struct blame_entry ***queue,
675                       struct blame_entry *dst, struct blame_entry *src)
676 {
677         origin_incref(src->suspect);
678         origin_decref(dst->suspect);
679         memcpy(dst, src, sizeof(*src));
680         dst->next = **queue;
681         **queue = dst;
682         *queue = &dst->next;
683 }
684
685 static const char *nth_line(struct scoreboard *sb, long lno)
686 {
687         return sb->final_buf + sb->lineno[lno];
688 }
689
690 static const char *nth_line_cb(void *data, long lno)
691 {
692         return nth_line((struct scoreboard *)data, lno);
693 }
694
695 /*
696  * It is known that lines between tlno to same came from parent, and e
697  * has an overlap with that range.  it also is known that parent's
698  * line plno corresponds to e's line tlno.
699  *
700  *                <---- e ----->
701  *                   <------>
702  *                   <------------>
703  *             <------------>
704  *             <------------------>
705  *
706  * Split e into potentially three parts; before this chunk, the chunk
707  * to be blamed for the parent, and after that portion.
708  */
709 static void split_overlap(struct blame_entry *split,
710                           struct blame_entry *e,
711                           int tlno, int plno, int same,
712                           struct origin *parent)
713 {
714         int chunk_end_lno;
715         memset(split, 0, sizeof(struct blame_entry [3]));
716
717         if (e->s_lno < tlno) {
718                 /* there is a pre-chunk part not blamed on parent */
719                 split[0].suspect = origin_incref(e->suspect);
720                 split[0].lno = e->lno;
721                 split[0].s_lno = e->s_lno;
722                 split[0].num_lines = tlno - e->s_lno;
723                 split[1].lno = e->lno + tlno - e->s_lno;
724                 split[1].s_lno = plno;
725         }
726         else {
727                 split[1].lno = e->lno;
728                 split[1].s_lno = plno + (e->s_lno - tlno);
729         }
730
731         if (same < e->s_lno + e->num_lines) {
732                 /* there is a post-chunk part not blamed on parent */
733                 split[2].suspect = origin_incref(e->suspect);
734                 split[2].lno = e->lno + (same - e->s_lno);
735                 split[2].s_lno = e->s_lno + (same - e->s_lno);
736                 split[2].num_lines = e->s_lno + e->num_lines - same;
737                 chunk_end_lno = split[2].lno;
738         }
739         else
740                 chunk_end_lno = e->lno + e->num_lines;
741         split[1].num_lines = chunk_end_lno - split[1].lno;
742
743         /*
744          * if it turns out there is nothing to blame the parent for,
745          * forget about the splitting.  !split[1].suspect signals this.
746          */
747         if (split[1].num_lines < 1)
748                 return;
749         split[1].suspect = origin_incref(parent);
750 }
751
752 /*
753  * split_overlap() divided an existing blame e into up to three parts
754  * in split.  Any assigned blame is moved to queue to
755  * reflect the split.
756  */
757 static void split_blame(struct blame_entry ***blamed,
758                         struct blame_entry ***unblamed,
759                         struct blame_entry *split,
760                         struct blame_entry *e)
761 {
762         struct blame_entry *new_entry;
763
764         if (split[0].suspect && split[2].suspect) {
765                 /* The first part (reuse storage for the existing entry e) */
766                 dup_entry(unblamed, e, &split[0]);
767
768                 /* The last part -- me */
769                 new_entry = xmalloc(sizeof(*new_entry));
770                 memcpy(new_entry, &(split[2]), sizeof(struct blame_entry));
771                 add_blame_entry(unblamed, new_entry);
772
773                 /* ... and the middle part -- parent */
774                 new_entry = xmalloc(sizeof(*new_entry));
775                 memcpy(new_entry, &(split[1]), sizeof(struct blame_entry));
776                 add_blame_entry(blamed, new_entry);
777         }
778         else if (!split[0].suspect && !split[2].suspect)
779                 /*
780                  * The parent covers the entire area; reuse storage for
781                  * e and replace it with the parent.
782                  */
783                 dup_entry(blamed, e, &split[1]);
784         else if (split[0].suspect) {
785                 /* me and then parent */
786                 dup_entry(unblamed, e, &split[0]);
787
788                 new_entry = xmalloc(sizeof(*new_entry));
789                 memcpy(new_entry, &(split[1]), sizeof(struct blame_entry));
790                 add_blame_entry(blamed, new_entry);
791         }
792         else {
793                 /* parent and then me */
794                 dup_entry(blamed, e, &split[1]);
795
796                 new_entry = xmalloc(sizeof(*new_entry));
797                 memcpy(new_entry, &(split[2]), sizeof(struct blame_entry));
798                 add_blame_entry(unblamed, new_entry);
799         }
800 }
801
802 /*
803  * After splitting the blame, the origins used by the
804  * on-stack blame_entry should lose one refcnt each.
805  */
806 static void decref_split(struct blame_entry *split)
807 {
808         int i;
809
810         for (i = 0; i < 3; i++)
811                 origin_decref(split[i].suspect);
812 }
813
814 /*
815  * reverse_blame reverses the list given in head, appending tail.
816  * That allows us to build lists in reverse order, then reverse them
817  * afterwards.  This can be faster than building the list in proper
818  * order right away.  The reason is that building in proper order
819  * requires writing a link in the _previous_ element, while building
820  * in reverse order just requires placing the list head into the
821  * _current_ element.
822  */
823
824 static struct blame_entry *reverse_blame(struct blame_entry *head,
825                                          struct blame_entry *tail)
826 {
827         while (head) {
828                 struct blame_entry *next = head->next;
829                 head->next = tail;
830                 tail = head;
831                 head = next;
832         }
833         return tail;
834 }
835
836 /*
837  * Process one hunk from the patch between the current suspect for
838  * blame_entry e and its parent.  This first blames any unfinished
839  * entries before the chunk (which is where target and parent start
840  * differing) on the parent, and then splits blame entries at the
841  * start and at the end of the difference region.  Since use of -M and
842  * -C options may lead to overlapping/duplicate source line number
843  * ranges, all we can rely on from sorting/merging is the order of the
844  * first suspect line number.
845  */
846 static void blame_chunk(struct blame_entry ***dstq, struct blame_entry ***srcq,
847                         int tlno, int offset, int same,
848                         struct origin *parent)
849 {
850         struct blame_entry *e = **srcq;
851         struct blame_entry *samep = NULL, *diffp = NULL;
852
853         while (e && e->s_lno < tlno) {
854                 struct blame_entry *next = e->next;
855                 /*
856                  * current record starts before differing portion.  If
857                  * it reaches into it, we need to split it up and
858                  * examine the second part separately.
859                  */
860                 if (e->s_lno + e->num_lines > tlno) {
861                         /* Move second half to a new record */
862                         int len = tlno - e->s_lno;
863                         struct blame_entry *n = xcalloc(1, sizeof (struct blame_entry));
864                         n->suspect = e->suspect;
865                         n->lno = e->lno + len;
866                         n->s_lno = e->s_lno + len;
867                         n->num_lines = e->num_lines - len;
868                         e->num_lines = len;
869                         e->score = 0;
870                         /* Push new record to diffp */
871                         n->next = diffp;
872                         diffp = n;
873                 } else
874                         origin_decref(e->suspect);
875                 /* Pass blame for everything before the differing
876                  * chunk to the parent */
877                 e->suspect = origin_incref(parent);
878                 e->s_lno += offset;
879                 e->next = samep;
880                 samep = e;
881                 e = next;
882         }
883         /*
884          * As we don't know how much of a common stretch after this
885          * diff will occur, the currently blamed parts are all that we
886          * can assign to the parent for now.
887          */
888
889         if (samep) {
890                 **dstq = reverse_blame(samep, **dstq);
891                 *dstq = &samep->next;
892         }
893         /*
894          * Prepend the split off portions: everything after e starts
895          * after the blameable portion.
896          */
897         e = reverse_blame(diffp, e);
898
899         /*
900          * Now retain records on the target while parts are different
901          * from the parent.
902          */
903         samep = NULL;
904         diffp = NULL;
905         while (e && e->s_lno < same) {
906                 struct blame_entry *next = e->next;
907
908                 /*
909                  * If current record extends into sameness, need to split.
910                  */
911                 if (e->s_lno + e->num_lines > same) {
912                         /*
913                          * Move second half to a new record to be
914                          * processed by later chunks
915                          */
916                         int len = same - e->s_lno;
917                         struct blame_entry *n = xcalloc(1, sizeof (struct blame_entry));
918                         n->suspect = origin_incref(e->suspect);
919                         n->lno = e->lno + len;
920                         n->s_lno = e->s_lno + len;
921                         n->num_lines = e->num_lines - len;
922                         e->num_lines = len;
923                         e->score = 0;
924                         /* Push new record to samep */
925                         n->next = samep;
926                         samep = n;
927                 }
928                 e->next = diffp;
929                 diffp = e;
930                 e = next;
931         }
932         **srcq = reverse_blame(diffp, reverse_blame(samep, e));
933         /* Move across elements that are in the unblamable portion */
934         if (diffp)
935                 *srcq = &diffp->next;
936 }
937
938 struct blame_chunk_cb_data {
939         struct origin *parent;
940         long offset;
941         struct blame_entry **dstq;
942         struct blame_entry **srcq;
943 };
944
945 /* diff chunks are from parent to target */
946 static int blame_chunk_cb(long start_a, long count_a,
947                           long start_b, long count_b, void *data)
948 {
949         struct blame_chunk_cb_data *d = data;
950         if (start_a - start_b != d->offset)
951                 die("internal error in blame::blame_chunk_cb");
952         blame_chunk(&d->dstq, &d->srcq, start_b, start_a - start_b,
953                     start_b + count_b, d->parent);
954         d->offset = start_a + count_a - (start_b + count_b);
955         return 0;
956 }
957
958 /*
959  * We are looking at the origin 'target' and aiming to pass blame
960  * for the lines it is suspected to its parent.  Run diff to find
961  * which lines came from parent and pass blame for them.
962  */
963 static void pass_blame_to_parent(struct scoreboard *sb,
964                                  struct origin *target,
965                                  struct origin *parent)
966 {
967         mmfile_t file_p, file_o;
968         struct blame_chunk_cb_data d;
969         struct blame_entry *newdest = NULL;
970
971         if (!target->suspects)
972                 return; /* nothing remains for this target */
973
974         d.parent = parent;
975         d.offset = 0;
976         d.dstq = &newdest; d.srcq = &target->suspects;
977
978         fill_origin_blob(&sb->revs->diffopt, parent, &file_p);
979         fill_origin_blob(&sb->revs->diffopt, target, &file_o);
980         num_get_patch++;
981
982         if (diff_hunks(&file_p, &file_o, blame_chunk_cb, &d))
983                 die("unable to generate diff (%s -> %s)",
984                     oid_to_hex(&parent->commit->object.oid),
985                     oid_to_hex(&target->commit->object.oid));
986         /* The rest are the same as the parent */
987         blame_chunk(&d.dstq, &d.srcq, INT_MAX, d.offset, INT_MAX, parent);
988         *d.dstq = NULL;
989         queue_blames(sb, parent, newdest);
990
991         return;
992 }
993
994 /*
995  * The lines in blame_entry after splitting blames many times can become
996  * very small and trivial, and at some point it becomes pointless to
997  * blame the parents.  E.g. "\t\t}\n\t}\n\n" appears everywhere in any
998  * ordinary C program, and it is not worth to say it was copied from
999  * totally unrelated file in the parent.
1000  *
1001  * Compute how trivial the lines in the blame_entry are.
1002  */
1003 static unsigned ent_score(struct scoreboard *sb, struct blame_entry *e)
1004 {
1005         unsigned score;
1006         const char *cp, *ep;
1007
1008         if (e->score)
1009                 return e->score;
1010
1011         score = 1;
1012         cp = nth_line(sb, e->lno);
1013         ep = nth_line(sb, e->lno + e->num_lines);
1014         while (cp < ep) {
1015                 unsigned ch = *((unsigned char *)cp);
1016                 if (isalnum(ch))
1017                         score++;
1018                 cp++;
1019         }
1020         e->score = score;
1021         return score;
1022 }
1023
1024 /*
1025  * best_so_far[] and this[] are both a split of an existing blame_entry
1026  * that passes blame to the parent.  Maintain best_so_far the best split
1027  * so far, by comparing this and best_so_far and copying this into
1028  * bst_so_far as needed.
1029  */
1030 static void copy_split_if_better(struct scoreboard *sb,
1031                                  struct blame_entry *best_so_far,
1032                                  struct blame_entry *this)
1033 {
1034         int i;
1035
1036         if (!this[1].suspect)
1037                 return;
1038         if (best_so_far[1].suspect) {
1039                 if (ent_score(sb, &this[1]) < ent_score(sb, &best_so_far[1]))
1040                         return;
1041         }
1042
1043         for (i = 0; i < 3; i++)
1044                 origin_incref(this[i].suspect);
1045         decref_split(best_so_far);
1046         memcpy(best_so_far, this, sizeof(struct blame_entry [3]));
1047 }
1048
1049 /*
1050  * We are looking at a part of the final image represented by
1051  * ent (tlno and same are offset by ent->s_lno).
1052  * tlno is where we are looking at in the final image.
1053  * up to (but not including) same match preimage.
1054  * plno is where we are looking at in the preimage.
1055  *
1056  * <-------------- final image ---------------------->
1057  *       <------ent------>
1058  *         ^tlno ^same
1059  *    <---------preimage----->
1060  *         ^plno
1061  *
1062  * All line numbers are 0-based.
1063  */
1064 static void handle_split(struct scoreboard *sb,
1065                          struct blame_entry *ent,
1066                          int tlno, int plno, int same,
1067                          struct origin *parent,
1068                          struct blame_entry *split)
1069 {
1070         if (ent->num_lines <= tlno)
1071                 return;
1072         if (tlno < same) {
1073                 struct blame_entry this[3];
1074                 tlno += ent->s_lno;
1075                 same += ent->s_lno;
1076                 split_overlap(this, ent, tlno, plno, same, parent);
1077                 copy_split_if_better(sb, split, this);
1078                 decref_split(this);
1079         }
1080 }
1081
1082 struct handle_split_cb_data {
1083         struct scoreboard *sb;
1084         struct blame_entry *ent;
1085         struct origin *parent;
1086         struct blame_entry *split;
1087         long plno;
1088         long tlno;
1089 };
1090
1091 static int handle_split_cb(long start_a, long count_a,
1092                            long start_b, long count_b, void *data)
1093 {
1094         struct handle_split_cb_data *d = data;
1095         handle_split(d->sb, d->ent, d->tlno, d->plno, start_b, d->parent,
1096                      d->split);
1097         d->plno = start_a + count_a;
1098         d->tlno = start_b + count_b;
1099         return 0;
1100 }
1101
1102 /*
1103  * Find the lines from parent that are the same as ent so that
1104  * we can pass blames to it.  file_p has the blob contents for
1105  * the parent.
1106  */
1107 static void find_copy_in_blob(struct scoreboard *sb,
1108                               struct blame_entry *ent,
1109                               struct origin *parent,
1110                               struct blame_entry *split,
1111                               mmfile_t *file_p)
1112 {
1113         const char *cp;
1114         mmfile_t file_o;
1115         struct handle_split_cb_data d;
1116
1117         memset(&d, 0, sizeof(d));
1118         d.sb = sb; d.ent = ent; d.parent = parent; d.split = split;
1119         /*
1120          * Prepare mmfile that contains only the lines in ent.
1121          */
1122         cp = nth_line(sb, ent->lno);
1123         file_o.ptr = (char *) cp;
1124         file_o.size = nth_line(sb, ent->lno + ent->num_lines) - cp;
1125
1126         /*
1127          * file_o is a part of final image we are annotating.
1128          * file_p partially may match that image.
1129          */
1130         memset(split, 0, sizeof(struct blame_entry [3]));
1131         if (diff_hunks(file_p, &file_o, handle_split_cb, &d))
1132                 die("unable to generate diff (%s)",
1133                     oid_to_hex(&parent->commit->object.oid));
1134         /* remainder, if any, all match the preimage */
1135         handle_split(sb, ent, d.tlno, d.plno, ent->num_lines, parent, split);
1136 }
1137
1138 /* Move all blame entries from list *source that have a score smaller
1139  * than score_min to the front of list *small.
1140  * Returns a pointer to the link pointing to the old head of the small list.
1141  */
1142
1143 static struct blame_entry **filter_small(struct scoreboard *sb,
1144                                          struct blame_entry **small,
1145                                          struct blame_entry **source,
1146                                          unsigned score_min)
1147 {
1148         struct blame_entry *p = *source;
1149         struct blame_entry *oldsmall = *small;
1150         while (p) {
1151                 if (ent_score(sb, p) <= score_min) {
1152                         *small = p;
1153                         small = &p->next;
1154                         p = *small;
1155                 } else {
1156                         *source = p;
1157                         source = &p->next;
1158                         p = *source;
1159                 }
1160         }
1161         *small = oldsmall;
1162         *source = NULL;
1163         return small;
1164 }
1165
1166 /*
1167  * See if lines currently target is suspected for can be attributed to
1168  * parent.
1169  */
1170 static void find_move_in_parent(struct scoreboard *sb,
1171                                 struct blame_entry ***blamed,
1172                                 struct blame_entry **toosmall,
1173                                 struct origin *target,
1174                                 struct origin *parent)
1175 {
1176         struct blame_entry *e, split[3];
1177         struct blame_entry *unblamed = target->suspects;
1178         struct blame_entry *leftover = NULL;
1179         mmfile_t file_p;
1180
1181         if (!unblamed)
1182                 return; /* nothing remains for this target */
1183
1184         fill_origin_blob(&sb->revs->diffopt, parent, &file_p);
1185         if (!file_p.ptr)
1186                 return;
1187
1188         /* At each iteration, unblamed has a NULL-terminated list of
1189          * entries that have not yet been tested for blame.  leftover
1190          * contains the reversed list of entries that have been tested
1191          * without being assignable to the parent.
1192          */
1193         do {
1194                 struct blame_entry **unblamedtail = &unblamed;
1195                 struct blame_entry *next;
1196                 for (e = unblamed; e; e = next) {
1197                         next = e->next;
1198                         find_copy_in_blob(sb, e, parent, split, &file_p);
1199                         if (split[1].suspect &&
1200                             blame_move_score < ent_score(sb, &split[1])) {
1201                                 split_blame(blamed, &unblamedtail, split, e);
1202                         } else {
1203                                 e->next = leftover;
1204                                 leftover = e;
1205                         }
1206                         decref_split(split);
1207                 }
1208                 *unblamedtail = NULL;
1209                 toosmall = filter_small(sb, toosmall, &unblamed, blame_move_score);
1210         } while (unblamed);
1211         target->suspects = reverse_blame(leftover, NULL);
1212 }
1213
1214 struct blame_list {
1215         struct blame_entry *ent;
1216         struct blame_entry split[3];
1217 };
1218
1219 /*
1220  * Count the number of entries the target is suspected for,
1221  * and prepare a list of entry and the best split.
1222  */
1223 static struct blame_list *setup_blame_list(struct blame_entry *unblamed,
1224                                            int *num_ents_p)
1225 {
1226         struct blame_entry *e;
1227         int num_ents, i;
1228         struct blame_list *blame_list = NULL;
1229
1230         for (e = unblamed, num_ents = 0; e; e = e->next)
1231                 num_ents++;
1232         if (num_ents) {
1233                 blame_list = xcalloc(num_ents, sizeof(struct blame_list));
1234                 for (e = unblamed, i = 0; e; e = e->next)
1235                         blame_list[i++].ent = e;
1236         }
1237         *num_ents_p = num_ents;
1238         return blame_list;
1239 }
1240
1241 /*
1242  * For lines target is suspected for, see if we can find code movement
1243  * across file boundary from the parent commit.  porigin is the path
1244  * in the parent we already tried.
1245  */
1246 static void find_copy_in_parent(struct scoreboard *sb,
1247                                 struct blame_entry ***blamed,
1248                                 struct blame_entry **toosmall,
1249                                 struct origin *target,
1250                                 struct commit *parent,
1251                                 struct origin *porigin,
1252                                 int opt)
1253 {
1254         struct diff_options diff_opts;
1255         int i, j;
1256         struct blame_list *blame_list;
1257         int num_ents;
1258         struct blame_entry *unblamed = target->suspects;
1259         struct blame_entry *leftover = NULL;
1260
1261         if (!unblamed)
1262                 return; /* nothing remains for this target */
1263
1264         diff_setup(&diff_opts);
1265         DIFF_OPT_SET(&diff_opts, RECURSIVE);
1266         diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;
1267
1268         diff_setup_done(&diff_opts);
1269
1270         /* Try "find copies harder" on new path if requested;
1271          * we do not want to use diffcore_rename() actually to
1272          * match things up; find_copies_harder is set only to
1273          * force diff_tree_sha1() to feed all filepairs to diff_queue,
1274          * and this code needs to be after diff_setup_done(), which
1275          * usually makes find-copies-harder imply copy detection.
1276          */
1277         if ((opt & PICKAXE_BLAME_COPY_HARDEST)
1278             || ((opt & PICKAXE_BLAME_COPY_HARDER)
1279                 && (!porigin || strcmp(target->path, porigin->path))))
1280                 DIFF_OPT_SET(&diff_opts, FIND_COPIES_HARDER);
1281
1282         if (is_null_oid(&target->commit->object.oid))
1283                 do_diff_cache(parent->tree->object.oid.hash, &diff_opts);
1284         else
1285                 diff_tree_sha1(parent->tree->object.oid.hash,
1286                                target->commit->tree->object.oid.hash,
1287                                "", &diff_opts);
1288
1289         if (!DIFF_OPT_TST(&diff_opts, FIND_COPIES_HARDER))
1290                 diffcore_std(&diff_opts);
1291
1292         do {
1293                 struct blame_entry **unblamedtail = &unblamed;
1294                 blame_list = setup_blame_list(unblamed, &num_ents);
1295
1296                 for (i = 0; i < diff_queued_diff.nr; i++) {
1297                         struct diff_filepair *p = diff_queued_diff.queue[i];
1298                         struct origin *norigin;
1299                         mmfile_t file_p;
1300                         struct blame_entry this[3];
1301
1302                         if (!DIFF_FILE_VALID(p->one))
1303                                 continue; /* does not exist in parent */
1304                         if (S_ISGITLINK(p->one->mode))
1305                                 continue; /* ignore git links */
1306                         if (porigin && !strcmp(p->one->path, porigin->path))
1307                                 /* find_move already dealt with this path */
1308                                 continue;
1309
1310                         norigin = get_origin(sb, parent, p->one->path);
1311                         hashcpy(norigin->blob_sha1, p->one->oid.hash);
1312                         norigin->mode = p->one->mode;
1313                         fill_origin_blob(&sb->revs->diffopt, norigin, &file_p);
1314                         if (!file_p.ptr)
1315                                 continue;
1316
1317                         for (j = 0; j < num_ents; j++) {
1318                                 find_copy_in_blob(sb, blame_list[j].ent,
1319                                                   norigin, this, &file_p);
1320                                 copy_split_if_better(sb, blame_list[j].split,
1321                                                      this);
1322                                 decref_split(this);
1323                         }
1324                         origin_decref(norigin);
1325                 }
1326
1327                 for (j = 0; j < num_ents; j++) {
1328                         struct blame_entry *split = blame_list[j].split;
1329                         if (split[1].suspect &&
1330                             blame_copy_score < ent_score(sb, &split[1])) {
1331                                 split_blame(blamed, &unblamedtail, split,
1332                                             blame_list[j].ent);
1333                         } else {
1334                                 blame_list[j].ent->next = leftover;
1335                                 leftover = blame_list[j].ent;
1336                         }
1337                         decref_split(split);
1338                 }
1339                 free(blame_list);
1340                 *unblamedtail = NULL;
1341                 toosmall = filter_small(sb, toosmall, &unblamed, blame_copy_score);
1342         } while (unblamed);
1343         target->suspects = reverse_blame(leftover, NULL);
1344         diff_flush(&diff_opts);
1345         clear_pathspec(&diff_opts.pathspec);
1346 }
1347
1348 /*
1349  * The blobs of origin and porigin exactly match, so everything
1350  * origin is suspected for can be blamed on the parent.
1351  */
1352 static void pass_whole_blame(struct scoreboard *sb,
1353                              struct origin *origin, struct origin *porigin)
1354 {
1355         struct blame_entry *e, *suspects;
1356
1357         if (!porigin->file.ptr && origin->file.ptr) {
1358                 /* Steal its file */
1359                 porigin->file = origin->file;
1360                 origin->file.ptr = NULL;
1361         }
1362         suspects = origin->suspects;
1363         origin->suspects = NULL;
1364         for (e = suspects; e; e = e->next) {
1365                 origin_incref(porigin);
1366                 origin_decref(e->suspect);
1367                 e->suspect = porigin;
1368         }
1369         queue_blames(sb, porigin, suspects);
1370 }
1371
1372 /*
1373  * We pass blame from the current commit to its parents.  We keep saying
1374  * "parent" (and "porigin"), but what we mean is to find scapegoat to
1375  * exonerate ourselves.
1376  */
1377 static struct commit_list *first_scapegoat(struct rev_info *revs, struct commit *commit)
1378 {
1379         if (!reverse) {
1380                 if (revs->first_parent_only &&
1381                     commit->parents &&
1382                     commit->parents->next) {
1383                         free_commit_list(commit->parents->next);
1384                         commit->parents->next = NULL;
1385                 }
1386                 return commit->parents;
1387         }
1388         return lookup_decoration(&revs->children, &commit->object);
1389 }
1390
1391 static int num_scapegoats(struct rev_info *revs, struct commit *commit)
1392 {
1393         struct commit_list *l = first_scapegoat(revs, commit);
1394         return commit_list_count(l);
1395 }
1396
1397 /* Distribute collected unsorted blames to the respected sorted lists
1398  * in the various origins.
1399  */
1400 static void distribute_blame(struct scoreboard *sb, struct blame_entry *blamed)
1401 {
1402         blamed = blame_sort(blamed, compare_blame_suspect);
1403         while (blamed)
1404         {
1405                 struct origin *porigin = blamed->suspect;
1406                 struct blame_entry *suspects = NULL;
1407                 do {
1408                         struct blame_entry *next = blamed->next;
1409                         blamed->next = suspects;
1410                         suspects = blamed;
1411                         blamed = next;
1412                 } while (blamed && blamed->suspect == porigin);
1413                 suspects = reverse_blame(suspects, NULL);
1414                 queue_blames(sb, porigin, suspects);
1415         }
1416 }
1417
1418 #define MAXSG 16
1419
1420 static void pass_blame(struct scoreboard *sb, struct origin *origin, int opt)
1421 {
1422         struct rev_info *revs = sb->revs;
1423         int i, pass, num_sg;
1424         struct commit *commit = origin->commit;
1425         struct commit_list *sg;
1426         struct origin *sg_buf[MAXSG];
1427         struct origin *porigin, **sg_origin = sg_buf;
1428         struct blame_entry *toosmall = NULL;
1429         struct blame_entry *blames, **blametail = &blames;
1430
1431         num_sg = num_scapegoats(revs, commit);
1432         if (!num_sg)
1433                 goto finish;
1434         else if (num_sg < ARRAY_SIZE(sg_buf))
1435                 memset(sg_buf, 0, sizeof(sg_buf));
1436         else
1437                 sg_origin = xcalloc(num_sg, sizeof(*sg_origin));
1438
1439         /*
1440          * The first pass looks for unrenamed path to optimize for
1441          * common cases, then we look for renames in the second pass.
1442          */
1443         for (pass = 0; pass < 2 - no_whole_file_rename; pass++) {
1444                 struct origin *(*find)(struct scoreboard *,
1445                                        struct commit *, struct origin *);
1446                 find = pass ? find_rename : find_origin;
1447
1448                 for (i = 0, sg = first_scapegoat(revs, commit);
1449                      i < num_sg && sg;
1450                      sg = sg->next, i++) {
1451                         struct commit *p = sg->item;
1452                         int j, same;
1453
1454                         if (sg_origin[i])
1455                                 continue;
1456                         if (parse_commit(p))
1457                                 continue;
1458                         porigin = find(sb, p, origin);
1459                         if (!porigin)
1460                                 continue;
1461                         if (!hashcmp(porigin->blob_sha1, origin->blob_sha1)) {
1462                                 pass_whole_blame(sb, origin, porigin);
1463                                 origin_decref(porigin);
1464                                 goto finish;
1465                         }
1466                         for (j = same = 0; j < i; j++)
1467                                 if (sg_origin[j] &&
1468                                     !hashcmp(sg_origin[j]->blob_sha1,
1469                                              porigin->blob_sha1)) {
1470                                         same = 1;
1471                                         break;
1472                                 }
1473                         if (!same)
1474                                 sg_origin[i] = porigin;
1475                         else
1476                                 origin_decref(porigin);
1477                 }
1478         }
1479
1480         num_commits++;
1481         for (i = 0, sg = first_scapegoat(revs, commit);
1482              i < num_sg && sg;
1483              sg = sg->next, i++) {
1484                 struct origin *porigin = sg_origin[i];
1485                 if (!porigin)
1486                         continue;
1487                 if (!origin->previous) {
1488                         origin_incref(porigin);
1489                         origin->previous = porigin;
1490                 }
1491                 pass_blame_to_parent(sb, origin, porigin);
1492                 if (!origin->suspects)
1493                         goto finish;
1494         }
1495
1496         /*
1497          * Optionally find moves in parents' files.
1498          */
1499         if (opt & PICKAXE_BLAME_MOVE) {
1500                 filter_small(sb, &toosmall, &origin->suspects, blame_move_score);
1501                 if (origin->suspects) {
1502                         for (i = 0, sg = first_scapegoat(revs, commit);
1503                              i < num_sg && sg;
1504                              sg = sg->next, i++) {
1505                                 struct origin *porigin = sg_origin[i];
1506                                 if (!porigin)
1507                                         continue;
1508                                 find_move_in_parent(sb, &blametail, &toosmall, origin, porigin);
1509                                 if (!origin->suspects)
1510                                         break;
1511                         }
1512                 }
1513         }
1514
1515         /*
1516          * Optionally find copies from parents' files.
1517          */
1518         if (opt & PICKAXE_BLAME_COPY) {
1519                 if (blame_copy_score > blame_move_score)
1520                         filter_small(sb, &toosmall, &origin->suspects, blame_copy_score);
1521                 else if (blame_copy_score < blame_move_score) {
1522                         origin->suspects = blame_merge(origin->suspects, toosmall);
1523                         toosmall = NULL;
1524                         filter_small(sb, &toosmall, &origin->suspects, blame_copy_score);
1525                 }
1526                 if (!origin->suspects)
1527                         goto finish;
1528
1529                 for (i = 0, sg = first_scapegoat(revs, commit);
1530                      i < num_sg && sg;
1531                      sg = sg->next, i++) {
1532                         struct origin *porigin = sg_origin[i];
1533                         find_copy_in_parent(sb, &blametail, &toosmall,
1534                                             origin, sg->item, porigin, opt);
1535                         if (!origin->suspects)
1536                                 goto finish;
1537                 }
1538         }
1539
1540 finish:
1541         *blametail = NULL;
1542         distribute_blame(sb, blames);
1543         /*
1544          * prepend toosmall to origin->suspects
1545          *
1546          * There is no point in sorting: this ends up on a big
1547          * unsorted list in the caller anyway.
1548          */
1549         if (toosmall) {
1550                 struct blame_entry **tail = &toosmall;
1551                 while (*tail)
1552                         tail = &(*tail)->next;
1553                 *tail = origin->suspects;
1554                 origin->suspects = toosmall;
1555         }
1556         for (i = 0; i < num_sg; i++) {
1557                 if (sg_origin[i]) {
1558                         drop_origin_blob(sg_origin[i]);
1559                         origin_decref(sg_origin[i]);
1560                 }
1561         }
1562         drop_origin_blob(origin);
1563         if (sg_buf != sg_origin)
1564                 free(sg_origin);
1565 }
1566
1567 /*
1568  * Information on commits, used for output.
1569  */
1570 struct commit_info {
1571         struct strbuf author;
1572         struct strbuf author_mail;
1573         unsigned long author_time;
1574         struct strbuf author_tz;
1575
1576         /* filled only when asked for details */
1577         struct strbuf committer;
1578         struct strbuf committer_mail;
1579         unsigned long committer_time;
1580         struct strbuf committer_tz;
1581
1582         struct strbuf summary;
1583 };
1584
1585 /*
1586  * Parse author/committer line in the commit object buffer
1587  */
1588 static void get_ac_line(const char *inbuf, const char *what,
1589         struct strbuf *name, struct strbuf *mail,
1590         unsigned long *time, struct strbuf *tz)
1591 {
1592         struct ident_split ident;
1593         size_t len, maillen, namelen;
1594         char *tmp, *endp;
1595         const char *namebuf, *mailbuf;
1596
1597         tmp = strstr(inbuf, what);
1598         if (!tmp)
1599                 goto error_out;
1600         tmp += strlen(what);
1601         endp = strchr(tmp, '\n');
1602         if (!endp)
1603                 len = strlen(tmp);
1604         else
1605                 len = endp - tmp;
1606
1607         if (split_ident_line(&ident, tmp, len)) {
1608         error_out:
1609                 /* Ugh */
1610                 tmp = "(unknown)";
1611                 strbuf_addstr(name, tmp);
1612                 strbuf_addstr(mail, tmp);
1613                 strbuf_addstr(tz, tmp);
1614                 *time = 0;
1615                 return;
1616         }
1617
1618         namelen = ident.name_end - ident.name_begin;
1619         namebuf = ident.name_begin;
1620
1621         maillen = ident.mail_end - ident.mail_begin;
1622         mailbuf = ident.mail_begin;
1623
1624         if (ident.date_begin && ident.date_end)
1625                 *time = strtoul(ident.date_begin, NULL, 10);
1626         else
1627                 *time = 0;
1628
1629         if (ident.tz_begin && ident.tz_end)
1630                 strbuf_add(tz, ident.tz_begin, ident.tz_end - ident.tz_begin);
1631         else
1632                 strbuf_addstr(tz, "(unknown)");
1633
1634         /*
1635          * Now, convert both name and e-mail using mailmap
1636          */
1637         map_user(&mailmap, &mailbuf, &maillen,
1638                  &namebuf, &namelen);
1639
1640         strbuf_addf(mail, "<%.*s>", (int)maillen, mailbuf);
1641         strbuf_add(name, namebuf, namelen);
1642 }
1643
1644 static void commit_info_init(struct commit_info *ci)
1645 {
1646
1647         strbuf_init(&ci->author, 0);
1648         strbuf_init(&ci->author_mail, 0);
1649         strbuf_init(&ci->author_tz, 0);
1650         strbuf_init(&ci->committer, 0);
1651         strbuf_init(&ci->committer_mail, 0);
1652         strbuf_init(&ci->committer_tz, 0);
1653         strbuf_init(&ci->summary, 0);
1654 }
1655
1656 static void commit_info_destroy(struct commit_info *ci)
1657 {
1658
1659         strbuf_release(&ci->author);
1660         strbuf_release(&ci->author_mail);
1661         strbuf_release(&ci->author_tz);
1662         strbuf_release(&ci->committer);
1663         strbuf_release(&ci->committer_mail);
1664         strbuf_release(&ci->committer_tz);
1665         strbuf_release(&ci->summary);
1666 }
1667
1668 static void get_commit_info(struct commit *commit,
1669                             struct commit_info *ret,
1670                             int detailed)
1671 {
1672         int len;
1673         const char *subject, *encoding;
1674         const char *message;
1675
1676         commit_info_init(ret);
1677
1678         encoding = get_log_output_encoding();
1679         message = logmsg_reencode(commit, NULL, encoding);
1680         get_ac_line(message, "\nauthor ",
1681                     &ret->author, &ret->author_mail,
1682                     &ret->author_time, &ret->author_tz);
1683
1684         if (!detailed) {
1685                 unuse_commit_buffer(commit, message);
1686                 return;
1687         }
1688
1689         get_ac_line(message, "\ncommitter ",
1690                     &ret->committer, &ret->committer_mail,
1691                     &ret->committer_time, &ret->committer_tz);
1692
1693         len = find_commit_subject(message, &subject);
1694         if (len)
1695                 strbuf_add(&ret->summary, subject, len);
1696         else
1697                 strbuf_addf(&ret->summary, "(%s)", oid_to_hex(&commit->object.oid));
1698
1699         unuse_commit_buffer(commit, message);
1700 }
1701
1702 /*
1703  * Write out any suspect information which depends on the path. This must be
1704  * handled separately from emit_one_suspect_detail(), because a given commit
1705  * may have changes in multiple paths. So this needs to appear each time
1706  * we mention a new group.
1707  *
1708  * To allow LF and other nonportable characters in pathnames,
1709  * they are c-style quoted as needed.
1710  */
1711 static void write_filename_info(struct origin *suspect)
1712 {
1713         if (suspect->previous) {
1714                 struct origin *prev = suspect->previous;
1715                 printf("previous %s ", oid_to_hex(&prev->commit->object.oid));
1716                 write_name_quoted(prev->path, stdout, '\n');
1717         }
1718         printf("filename ");
1719         write_name_quoted(suspect->path, stdout, '\n');
1720 }
1721
1722 /*
1723  * Porcelain/Incremental format wants to show a lot of details per
1724  * commit.  Instead of repeating this every line, emit it only once,
1725  * the first time each commit appears in the output (unless the
1726  * user has specifically asked for us to repeat).
1727  */
1728 static int emit_one_suspect_detail(struct origin *suspect, int repeat)
1729 {
1730         struct commit_info ci;
1731
1732         if (!repeat && (suspect->commit->object.flags & METAINFO_SHOWN))
1733                 return 0;
1734
1735         suspect->commit->object.flags |= METAINFO_SHOWN;
1736         get_commit_info(suspect->commit, &ci, 1);
1737         printf("author %s\n", ci.author.buf);
1738         printf("author-mail %s\n", ci.author_mail.buf);
1739         printf("author-time %lu\n", ci.author_time);
1740         printf("author-tz %s\n", ci.author_tz.buf);
1741         printf("committer %s\n", ci.committer.buf);
1742         printf("committer-mail %s\n", ci.committer_mail.buf);
1743         printf("committer-time %lu\n", ci.committer_time);
1744         printf("committer-tz %s\n", ci.committer_tz.buf);
1745         printf("summary %s\n", ci.summary.buf);
1746         if (suspect->commit->object.flags & UNINTERESTING)
1747                 printf("boundary\n");
1748
1749         commit_info_destroy(&ci);
1750
1751         return 1;
1752 }
1753
1754 /*
1755  * The blame_entry is found to be guilty for the range.
1756  * Show it in incremental output.
1757  */
1758 static void found_guilty_entry(struct blame_entry *ent,
1759                            struct progress_info *pi)
1760 {
1761         if (incremental) {
1762                 struct origin *suspect = ent->suspect;
1763
1764                 printf("%s %d %d %d\n",
1765                        oid_to_hex(&suspect->commit->object.oid),
1766                        ent->s_lno + 1, ent->lno + 1, ent->num_lines);
1767                 emit_one_suspect_detail(suspect, 0);
1768                 write_filename_info(suspect);
1769                 maybe_flush_or_die(stdout, "stdout");
1770         }
1771         pi->blamed_lines += ent->num_lines;
1772         display_progress(pi->progress, pi->blamed_lines);
1773 }
1774
1775 /*
1776  * The main loop -- while we have blobs with lines whose true origin
1777  * is still unknown, pick one blob, and allow its lines to pass blames
1778  * to its parents. */
1779 static void assign_blame(struct scoreboard *sb, int opt)
1780 {
1781         struct rev_info *revs = sb->revs;
1782         struct commit *commit = prio_queue_get(&sb->commits);
1783         struct progress_info pi = { NULL, 0 };
1784
1785         if (show_progress)
1786                 pi.progress = start_progress_delay(_("Blaming lines"),
1787                                                    sb->num_lines, 50, 1);
1788
1789         while (commit) {
1790                 struct blame_entry *ent;
1791                 struct origin *suspect = commit->util;
1792
1793                 /* find one suspect to break down */
1794                 while (suspect && !suspect->suspects)
1795                         suspect = suspect->next;
1796
1797                 if (!suspect) {
1798                         commit = prio_queue_get(&sb->commits);
1799                         continue;
1800                 }
1801
1802                 assert(commit == suspect->commit);
1803
1804                 /*
1805                  * We will use this suspect later in the loop,
1806                  * so hold onto it in the meantime.
1807                  */
1808                 origin_incref(suspect);
1809                 parse_commit(commit);
1810                 if (reverse ||
1811                     (!(commit->object.flags & UNINTERESTING) &&
1812                      !(revs->max_age != -1 && commit->date < revs->max_age)))
1813                         pass_blame(sb, suspect, opt);
1814                 else {
1815                         commit->object.flags |= UNINTERESTING;
1816                         if (commit->object.parsed)
1817                                 mark_parents_uninteresting(commit);
1818                 }
1819                 /* treat root commit as boundary */
1820                 if (!commit->parents && !show_root)
1821                         commit->object.flags |= UNINTERESTING;
1822
1823                 /* Take responsibility for the remaining entries */
1824                 ent = suspect->suspects;
1825                 if (ent) {
1826                         suspect->guilty = 1;
1827                         for (;;) {
1828                                 struct blame_entry *next = ent->next;
1829                                 found_guilty_entry(ent, &pi);
1830                                 if (next) {
1831                                         ent = next;
1832                                         continue;
1833                                 }
1834                                 ent->next = sb->ent;
1835                                 sb->ent = suspect->suspects;
1836                                 suspect->suspects = NULL;
1837                                 break;
1838                         }
1839                 }
1840                 origin_decref(suspect);
1841
1842                 if (DEBUG) /* sanity */
1843                         sanity_check_refcnt(sb);
1844         }
1845
1846         stop_progress(&pi.progress);
1847 }
1848
1849 static const char *format_time(unsigned long time, const char *tz_str,
1850                                int show_raw_time)
1851 {
1852         static struct strbuf time_buf = STRBUF_INIT;
1853
1854         strbuf_reset(&time_buf);
1855         if (show_raw_time) {
1856                 strbuf_addf(&time_buf, "%lu %s", time, tz_str);
1857         }
1858         else {
1859                 const char *time_str;
1860                 size_t time_width;
1861                 int tz;
1862                 tz = atoi(tz_str);
1863                 time_str = show_date(time, tz, &blame_date_mode);
1864                 strbuf_addstr(&time_buf, time_str);
1865                 /*
1866                  * Add space paddings to time_buf to display a fixed width
1867                  * string, and use time_width for display width calibration.
1868                  */
1869                 for (time_width = utf8_strwidth(time_str);
1870                      time_width < blame_date_width;
1871                      time_width++)
1872                         strbuf_addch(&time_buf, ' ');
1873         }
1874         return time_buf.buf;
1875 }
1876
1877 #define OUTPUT_ANNOTATE_COMPAT  001
1878 #define OUTPUT_LONG_OBJECT_NAME 002
1879 #define OUTPUT_RAW_TIMESTAMP    004
1880 #define OUTPUT_PORCELAIN        010
1881 #define OUTPUT_SHOW_NAME        020
1882 #define OUTPUT_SHOW_NUMBER      040
1883 #define OUTPUT_SHOW_SCORE      0100
1884 #define OUTPUT_NO_AUTHOR       0200
1885 #define OUTPUT_SHOW_EMAIL       0400
1886 #define OUTPUT_LINE_PORCELAIN 01000
1887
1888 static void emit_porcelain_details(struct origin *suspect, int repeat)
1889 {
1890         if (emit_one_suspect_detail(suspect, repeat) ||
1891             (suspect->commit->object.flags & MORE_THAN_ONE_PATH))
1892                 write_filename_info(suspect);
1893 }
1894
1895 static void emit_porcelain(struct scoreboard *sb, struct blame_entry *ent,
1896                            int opt)
1897 {
1898         int repeat = opt & OUTPUT_LINE_PORCELAIN;
1899         int cnt;
1900         const char *cp;
1901         struct origin *suspect = ent->suspect;
1902         char hex[GIT_SHA1_HEXSZ + 1];
1903
1904         sha1_to_hex_r(hex, suspect->commit->object.oid.hash);
1905         printf("%s %d %d %d\n",
1906                hex,
1907                ent->s_lno + 1,
1908                ent->lno + 1,
1909                ent->num_lines);
1910         emit_porcelain_details(suspect, repeat);
1911
1912         cp = nth_line(sb, ent->lno);
1913         for (cnt = 0; cnt < ent->num_lines; cnt++) {
1914                 char ch;
1915                 if (cnt) {
1916                         printf("%s %d %d\n", hex,
1917                                ent->s_lno + 1 + cnt,
1918                                ent->lno + 1 + cnt);
1919                         if (repeat)
1920                                 emit_porcelain_details(suspect, 1);
1921                 }
1922                 putchar('\t');
1923                 do {
1924                         ch = *cp++;
1925                         putchar(ch);
1926                 } while (ch != '\n' &&
1927                          cp < sb->final_buf + sb->final_buf_size);
1928         }
1929
1930         if (sb->final_buf_size && cp[-1] != '\n')
1931                 putchar('\n');
1932 }
1933
1934 static void emit_other(struct scoreboard *sb, struct blame_entry *ent, int opt)
1935 {
1936         int cnt;
1937         const char *cp;
1938         struct origin *suspect = ent->suspect;
1939         struct commit_info ci;
1940         char hex[GIT_SHA1_HEXSZ + 1];
1941         int show_raw_time = !!(opt & OUTPUT_RAW_TIMESTAMP);
1942
1943         get_commit_info(suspect->commit, &ci, 1);
1944         sha1_to_hex_r(hex, suspect->commit->object.oid.hash);
1945
1946         cp = nth_line(sb, ent->lno);
1947         for (cnt = 0; cnt < ent->num_lines; cnt++) {
1948                 char ch;
1949                 int length = (opt & OUTPUT_LONG_OBJECT_NAME) ? 40 : abbrev;
1950
1951                 if (suspect->commit->object.flags & UNINTERESTING) {
1952                         if (blank_boundary)
1953                                 memset(hex, ' ', length);
1954                         else if (!(opt & OUTPUT_ANNOTATE_COMPAT)) {
1955                                 length--;
1956                                 putchar('^');
1957                         }
1958                 }
1959
1960                 printf("%.*s", length, hex);
1961                 if (opt & OUTPUT_ANNOTATE_COMPAT) {
1962                         const char *name;
1963                         if (opt & OUTPUT_SHOW_EMAIL)
1964                                 name = ci.author_mail.buf;
1965                         else
1966                                 name = ci.author.buf;
1967                         printf("\t(%10s\t%10s\t%d)", name,
1968                                format_time(ci.author_time, ci.author_tz.buf,
1969                                            show_raw_time),
1970                                ent->lno + 1 + cnt);
1971                 } else {
1972                         if (opt & OUTPUT_SHOW_SCORE)
1973                                 printf(" %*d %02d",
1974                                        max_score_digits, ent->score,
1975                                        ent->suspect->refcnt);
1976                         if (opt & OUTPUT_SHOW_NAME)
1977                                 printf(" %-*.*s", longest_file, longest_file,
1978                                        suspect->path);
1979                         if (opt & OUTPUT_SHOW_NUMBER)
1980                                 printf(" %*d", max_orig_digits,
1981                                        ent->s_lno + 1 + cnt);
1982
1983                         if (!(opt & OUTPUT_NO_AUTHOR)) {
1984                                 const char *name;
1985                                 int pad;
1986                                 if (opt & OUTPUT_SHOW_EMAIL)
1987                                         name = ci.author_mail.buf;
1988                                 else
1989                                         name = ci.author.buf;
1990                                 pad = longest_author - utf8_strwidth(name);
1991                                 printf(" (%s%*s %10s",
1992                                        name, pad, "",
1993                                        format_time(ci.author_time,
1994                                                    ci.author_tz.buf,
1995                                                    show_raw_time));
1996                         }
1997                         printf(" %*d) ",
1998                                max_digits, ent->lno + 1 + cnt);
1999                 }
2000                 do {
2001                         ch = *cp++;
2002                         putchar(ch);
2003                 } while (ch != '\n' &&
2004                          cp < sb->final_buf + sb->final_buf_size);
2005         }
2006
2007         if (sb->final_buf_size && cp[-1] != '\n')
2008                 putchar('\n');
2009
2010         commit_info_destroy(&ci);
2011 }
2012
2013 static void output(struct scoreboard *sb, int option)
2014 {
2015         struct blame_entry *ent;
2016
2017         if (option & OUTPUT_PORCELAIN) {
2018                 for (ent = sb->ent; ent; ent = ent->next) {
2019                         int count = 0;
2020                         struct origin *suspect;
2021                         struct commit *commit = ent->suspect->commit;
2022                         if (commit->object.flags & MORE_THAN_ONE_PATH)
2023                                 continue;
2024                         for (suspect = commit->util; suspect; suspect = suspect->next) {
2025                                 if (suspect->guilty && count++) {
2026                                         commit->object.flags |= MORE_THAN_ONE_PATH;
2027                                         break;
2028                                 }
2029                         }
2030                 }
2031         }
2032
2033         for (ent = sb->ent; ent; ent = ent->next) {
2034                 if (option & OUTPUT_PORCELAIN)
2035                         emit_porcelain(sb, ent, option);
2036                 else {
2037                         emit_other(sb, ent, option);
2038                 }
2039         }
2040 }
2041
2042 static const char *get_next_line(const char *start, const char *end)
2043 {
2044         const char *nl = memchr(start, '\n', end - start);
2045         return nl ? nl + 1 : end;
2046 }
2047
2048 /*
2049  * To allow quick access to the contents of nth line in the
2050  * final image, prepare an index in the scoreboard.
2051  */
2052 static int prepare_lines(struct scoreboard *sb)
2053 {
2054         const char *buf = sb->final_buf;
2055         unsigned long len = sb->final_buf_size;
2056         const char *end = buf + len;
2057         const char *p;
2058         int *lineno;
2059         int num = 0;
2060
2061         for (p = buf; p < end; p = get_next_line(p, end))
2062                 num++;
2063
2064         ALLOC_ARRAY(sb->lineno, num + 1);
2065         lineno = sb->lineno;
2066
2067         for (p = buf; p < end; p = get_next_line(p, end))
2068                 *lineno++ = p - buf;
2069
2070         *lineno = len;
2071
2072         sb->num_lines = num;
2073         return sb->num_lines;
2074 }
2075
2076 /*
2077  * Add phony grafts for use with -S; this is primarily to
2078  * support git's cvsserver that wants to give a linear history
2079  * to its clients.
2080  */
2081 static int read_ancestry(const char *graft_file)
2082 {
2083         FILE *fp = fopen(graft_file, "r");
2084         struct strbuf buf = STRBUF_INIT;
2085         if (!fp)
2086                 return -1;
2087         while (!strbuf_getwholeline(&buf, fp, '\n')) {
2088                 /* The format is just "Commit Parent1 Parent2 ...\n" */
2089                 struct commit_graft *graft = read_graft_line(buf.buf, buf.len);
2090                 if (graft)
2091                         register_commit_graft(graft, 0);
2092         }
2093         fclose(fp);
2094         strbuf_release(&buf);
2095         return 0;
2096 }
2097
2098 static int update_auto_abbrev(int auto_abbrev, struct origin *suspect)
2099 {
2100         const char *uniq = find_unique_abbrev(suspect->commit->object.oid.hash,
2101                                               auto_abbrev);
2102         int len = strlen(uniq);
2103         if (auto_abbrev < len)
2104                 return len;
2105         return auto_abbrev;
2106 }
2107
2108 /*
2109  * How many columns do we need to show line numbers, authors,
2110  * and filenames?
2111  */
2112 static void find_alignment(struct scoreboard *sb, int *option)
2113 {
2114         int longest_src_lines = 0;
2115         int longest_dst_lines = 0;
2116         unsigned largest_score = 0;
2117         struct blame_entry *e;
2118         int compute_auto_abbrev = (abbrev < 0);
2119         int auto_abbrev = DEFAULT_ABBREV;
2120
2121         for (e = sb->ent; e; e = e->next) {
2122                 struct origin *suspect = e->suspect;
2123                 int num;
2124
2125                 if (compute_auto_abbrev)
2126                         auto_abbrev = update_auto_abbrev(auto_abbrev, suspect);
2127                 if (strcmp(suspect->path, sb->path))
2128                         *option |= OUTPUT_SHOW_NAME;
2129                 num = strlen(suspect->path);
2130                 if (longest_file < num)
2131                         longest_file = num;
2132                 if (!(suspect->commit->object.flags & METAINFO_SHOWN)) {
2133                         struct commit_info ci;
2134                         suspect->commit->object.flags |= METAINFO_SHOWN;
2135                         get_commit_info(suspect->commit, &ci, 1);
2136                         if (*option & OUTPUT_SHOW_EMAIL)
2137                                 num = utf8_strwidth(ci.author_mail.buf);
2138                         else
2139                                 num = utf8_strwidth(ci.author.buf);
2140                         if (longest_author < num)
2141                                 longest_author = num;
2142                         commit_info_destroy(&ci);
2143                 }
2144                 num = e->s_lno + e->num_lines;
2145                 if (longest_src_lines < num)
2146                         longest_src_lines = num;
2147                 num = e->lno + e->num_lines;
2148                 if (longest_dst_lines < num)
2149                         longest_dst_lines = num;
2150                 if (largest_score < ent_score(sb, e))
2151                         largest_score = ent_score(sb, e);
2152         }
2153         max_orig_digits = decimal_width(longest_src_lines);
2154         max_digits = decimal_width(longest_dst_lines);
2155         max_score_digits = decimal_width(largest_score);
2156
2157         if (compute_auto_abbrev)
2158                 /* one more abbrev length is needed for the boundary commit */
2159                 abbrev = auto_abbrev + 1;
2160 }
2161
2162 /*
2163  * For debugging -- origin is refcounted, and this asserts that
2164  * we do not underflow.
2165  */
2166 static void sanity_check_refcnt(struct scoreboard *sb)
2167 {
2168         int baa = 0;
2169         struct blame_entry *ent;
2170
2171         for (ent = sb->ent; ent; ent = ent->next) {
2172                 /* Nobody should have zero or negative refcnt */
2173                 if (ent->suspect->refcnt <= 0) {
2174                         fprintf(stderr, "%s in %s has negative refcnt %d\n",
2175                                 ent->suspect->path,
2176                                 oid_to_hex(&ent->suspect->commit->object.oid),
2177                                 ent->suspect->refcnt);
2178                         baa = 1;
2179                 }
2180         }
2181         if (baa) {
2182                 int opt = 0160;
2183                 find_alignment(sb, &opt);
2184                 output(sb, opt);
2185                 die("Baa %d!", baa);
2186         }
2187 }
2188
2189 static unsigned parse_score(const char *arg)
2190 {
2191         char *end;
2192         unsigned long score = strtoul(arg, &end, 10);
2193         if (*end)
2194                 return 0;
2195         return score;
2196 }
2197
2198 static const char *add_prefix(const char *prefix, const char *path)
2199 {
2200         return prefix_path(prefix, prefix ? strlen(prefix) : 0, path);
2201 }
2202
2203 static int git_blame_config(const char *var, const char *value, void *cb)
2204 {
2205         if (!strcmp(var, "blame.showroot")) {
2206                 show_root = git_config_bool(var, value);
2207                 return 0;
2208         }
2209         if (!strcmp(var, "blame.blankboundary")) {
2210                 blank_boundary = git_config_bool(var, value);
2211                 return 0;
2212         }
2213         if (!strcmp(var, "blame.showemail")) {
2214                 int *output_option = cb;
2215                 if (git_config_bool(var, value))
2216                         *output_option |= OUTPUT_SHOW_EMAIL;
2217                 else
2218                         *output_option &= ~OUTPUT_SHOW_EMAIL;
2219                 return 0;
2220         }
2221         if (!strcmp(var, "blame.date")) {
2222                 if (!value)
2223                         return config_error_nonbool(var);
2224                 parse_date_format(value, &blame_date_mode);
2225                 return 0;
2226         }
2227
2228         if (userdiff_config(var, value) < 0)
2229                 return -1;
2230
2231         return git_default_config(var, value, cb);
2232 }
2233
2234 static void verify_working_tree_path(struct commit *work_tree, const char *path)
2235 {
2236         struct commit_list *parents;
2237         int pos;
2238
2239         for (parents = work_tree->parents; parents; parents = parents->next) {
2240                 const unsigned char *commit_sha1 = parents->item->object.oid.hash;
2241                 unsigned char blob_sha1[20];
2242                 unsigned mode;
2243
2244                 if (!get_tree_entry(commit_sha1, path, blob_sha1, &mode) &&
2245                     sha1_object_info(blob_sha1, NULL) == OBJ_BLOB)
2246                         return;
2247         }
2248
2249         pos = cache_name_pos(path, strlen(path));
2250         if (pos >= 0)
2251                 ; /* path is in the index */
2252         else if (-1 - pos < active_nr &&
2253                  !strcmp(active_cache[-1 - pos]->name, path))
2254                 ; /* path is in the index, unmerged */
2255         else
2256                 die("no such path '%s' in HEAD", path);
2257 }
2258
2259 static struct commit_list **append_parent(struct commit_list **tail, const unsigned char *sha1)
2260 {
2261         struct commit *parent;
2262
2263         parent = lookup_commit_reference(sha1);
2264         if (!parent)
2265                 die("no such commit %s", sha1_to_hex(sha1));
2266         return &commit_list_insert(parent, tail)->next;
2267 }
2268
2269 static void append_merge_parents(struct commit_list **tail)
2270 {
2271         int merge_head;
2272         struct strbuf line = STRBUF_INIT;
2273
2274         merge_head = open(git_path_merge_head(), O_RDONLY);
2275         if (merge_head < 0) {
2276                 if (errno == ENOENT)
2277                         return;
2278                 die("cannot open '%s' for reading", git_path_merge_head());
2279         }
2280
2281         while (!strbuf_getwholeline_fd(&line, merge_head, '\n')) {
2282                 unsigned char sha1[20];
2283                 if (line.len < 40 || get_sha1_hex(line.buf, sha1))
2284                         die("unknown line in '%s': %s", git_path_merge_head(), line.buf);
2285                 tail = append_parent(tail, sha1);
2286         }
2287         close(merge_head);
2288         strbuf_release(&line);
2289 }
2290
2291 /*
2292  * This isn't as simple as passing sb->buf and sb->len, because we
2293  * want to transfer ownership of the buffer to the commit (so we
2294  * must use detach).
2295  */
2296 static void set_commit_buffer_from_strbuf(struct commit *c, struct strbuf *sb)
2297 {
2298         size_t len;
2299         void *buf = strbuf_detach(sb, &len);
2300         set_commit_buffer(c, buf, len);
2301 }
2302
2303 /*
2304  * Prepare a dummy commit that represents the work tree (or staged) item.
2305  * Note that annotating work tree item never works in the reverse.
2306  */
2307 static struct commit *fake_working_tree_commit(struct diff_options *opt,
2308                                                const char *path,
2309                                                const char *contents_from)
2310 {
2311         struct commit *commit;
2312         struct origin *origin;
2313         struct commit_list **parent_tail, *parent;
2314         unsigned char head_sha1[20];
2315         struct strbuf buf = STRBUF_INIT;
2316         const char *ident;
2317         time_t now;
2318         int size, len;
2319         struct cache_entry *ce;
2320         unsigned mode;
2321         struct strbuf msg = STRBUF_INIT;
2322
2323         read_cache();
2324         time(&now);
2325         commit = alloc_commit_node();
2326         commit->object.parsed = 1;
2327         commit->date = now;
2328         parent_tail = &commit->parents;
2329
2330         if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, head_sha1, NULL))
2331                 die("no such ref: HEAD");
2332
2333         parent_tail = append_parent(parent_tail, head_sha1);
2334         append_merge_parents(parent_tail);
2335         verify_working_tree_path(commit, path);
2336
2337         origin = make_origin(commit, path);
2338
2339         ident = fmt_ident("Not Committed Yet", "not.committed.yet", NULL, 0);
2340         strbuf_addstr(&msg, "tree 0000000000000000000000000000000000000000\n");
2341         for (parent = commit->parents; parent; parent = parent->next)
2342                 strbuf_addf(&msg, "parent %s\n",
2343                             oid_to_hex(&parent->item->object.oid));
2344         strbuf_addf(&msg,
2345                     "author %s\n"
2346                     "committer %s\n\n"
2347                     "Version of %s from %s\n",
2348                     ident, ident, path,
2349                     (!contents_from ? path :
2350                      (!strcmp(contents_from, "-") ? "standard input" : contents_from)));
2351         set_commit_buffer_from_strbuf(commit, &msg);
2352
2353         if (!contents_from || strcmp("-", contents_from)) {
2354                 struct stat st;
2355                 const char *read_from;
2356                 char *buf_ptr;
2357                 unsigned long buf_len;
2358
2359                 if (contents_from) {
2360                         if (stat(contents_from, &st) < 0)
2361                                 die_errno("Cannot stat '%s'", contents_from);
2362                         read_from = contents_from;
2363                 }
2364                 else {
2365                         if (lstat(path, &st) < 0)
2366                                 die_errno("Cannot lstat '%s'", path);
2367                         read_from = path;
2368                 }
2369                 mode = canon_mode(st.st_mode);
2370
2371                 switch (st.st_mode & S_IFMT) {
2372                 case S_IFREG:
2373                         if (DIFF_OPT_TST(opt, ALLOW_TEXTCONV) &&
2374                             textconv_object(read_from, mode, null_sha1, 0, &buf_ptr, &buf_len))
2375                                 strbuf_attach(&buf, buf_ptr, buf_len, buf_len + 1);
2376                         else if (strbuf_read_file(&buf, read_from, st.st_size) != st.st_size)
2377                                 die_errno("cannot open or read '%s'", read_from);
2378                         break;
2379                 case S_IFLNK:
2380                         if (strbuf_readlink(&buf, read_from, st.st_size) < 0)
2381                                 die_errno("cannot readlink '%s'", read_from);
2382                         break;
2383                 default:
2384                         die("unsupported file type %s", read_from);
2385                 }
2386         }
2387         else {
2388                 /* Reading from stdin */
2389                 mode = 0;
2390                 if (strbuf_read(&buf, 0, 0) < 0)
2391                         die_errno("failed to read from stdin");
2392         }
2393         convert_to_git(path, buf.buf, buf.len, &buf, 0);
2394         origin->file.ptr = buf.buf;
2395         origin->file.size = buf.len;
2396         pretend_sha1_file(buf.buf, buf.len, OBJ_BLOB, origin->blob_sha1);
2397
2398         /*
2399          * Read the current index, replace the path entry with
2400          * origin->blob_sha1 without mucking with its mode or type
2401          * bits; we are not going to write this index out -- we just
2402          * want to run "diff-index --cached".
2403          */
2404         discard_cache();
2405         read_cache();
2406
2407         len = strlen(path);
2408         if (!mode) {
2409                 int pos = cache_name_pos(path, len);
2410                 if (0 <= pos)
2411                         mode = active_cache[pos]->ce_mode;
2412                 else
2413                         /* Let's not bother reading from HEAD tree */
2414                         mode = S_IFREG | 0644;
2415         }
2416         size = cache_entry_size(len);
2417         ce = xcalloc(1, size);
2418         hashcpy(ce->sha1, origin->blob_sha1);
2419         memcpy(ce->name, path, len);
2420         ce->ce_flags = create_ce_flags(0);
2421         ce->ce_namelen = len;
2422         ce->ce_mode = create_ce_mode(mode);
2423         add_cache_entry(ce, ADD_CACHE_OK_TO_ADD|ADD_CACHE_OK_TO_REPLACE);
2424
2425         cache_tree_invalidate_path(&the_index, path);
2426
2427         return commit;
2428 }
2429
2430 static struct commit *find_single_final(struct rev_info *revs,
2431                                         const char **name_p)
2432 {
2433         int i;
2434         struct commit *found = NULL;
2435         const char *name = NULL;
2436
2437         for (i = 0; i < revs->pending.nr; i++) {
2438                 struct object *obj = revs->pending.objects[i].item;
2439                 if (obj->flags & UNINTERESTING)
2440                         continue;
2441                 obj = deref_tag(obj, NULL, 0);
2442                 if (obj->type != OBJ_COMMIT)
2443                         die("Non commit %s?", revs->pending.objects[i].name);
2444                 if (found)
2445                         die("More than one commit to dig from %s and %s?",
2446                             revs->pending.objects[i].name, name);
2447                 found = (struct commit *)obj;
2448                 name = revs->pending.objects[i].name;
2449         }
2450         if (name_p)
2451                 *name_p = name;
2452         return found;
2453 }
2454
2455 static char *prepare_final(struct scoreboard *sb)
2456 {
2457         const char *name;
2458         sb->final = find_single_final(sb->revs, &name);
2459         return xstrdup_or_null(name);
2460 }
2461
2462 static char *prepare_initial(struct scoreboard *sb)
2463 {
2464         int i;
2465         const char *final_commit_name = NULL;
2466         struct rev_info *revs = sb->revs;
2467
2468         /*
2469          * There must be one and only one negative commit, and it must be
2470          * the boundary.
2471          */
2472         for (i = 0; i < revs->pending.nr; i++) {
2473                 struct object *obj = revs->pending.objects[i].item;
2474                 if (!(obj->flags & UNINTERESTING))
2475                         continue;
2476                 obj = deref_tag(obj, NULL, 0);
2477                 if (obj->type != OBJ_COMMIT)
2478                         die("Non commit %s?", revs->pending.objects[i].name);
2479                 if (sb->final)
2480                         die("More than one commit to dig down to %s and %s?",
2481                             revs->pending.objects[i].name,
2482                             final_commit_name);
2483                 sb->final = (struct commit *) obj;
2484                 final_commit_name = revs->pending.objects[i].name;
2485         }
2486         if (!final_commit_name)
2487                 die("No commit to dig down to?");
2488         return xstrdup(final_commit_name);
2489 }
2490
2491 static int blame_copy_callback(const struct option *option, const char *arg, int unset)
2492 {
2493         int *opt = option->value;
2494
2495         /*
2496          * -C enables copy from removed files;
2497          * -C -C enables copy from existing files, but only
2498          *       when blaming a new file;
2499          * -C -C -C enables copy from existing files for
2500          *          everybody
2501          */
2502         if (*opt & PICKAXE_BLAME_COPY_HARDER)
2503                 *opt |= PICKAXE_BLAME_COPY_HARDEST;
2504         if (*opt & PICKAXE_BLAME_COPY)
2505                 *opt |= PICKAXE_BLAME_COPY_HARDER;
2506         *opt |= PICKAXE_BLAME_COPY | PICKAXE_BLAME_MOVE;
2507
2508         if (arg)
2509                 blame_copy_score = parse_score(arg);
2510         return 0;
2511 }
2512
2513 static int blame_move_callback(const struct option *option, const char *arg, int unset)
2514 {
2515         int *opt = option->value;
2516
2517         *opt |= PICKAXE_BLAME_MOVE;
2518
2519         if (arg)
2520                 blame_move_score = parse_score(arg);
2521         return 0;
2522 }
2523
2524 int cmd_blame(int argc, const char **argv, const char *prefix)
2525 {
2526         struct rev_info revs;
2527         const char *path;
2528         struct scoreboard sb;
2529         struct origin *o;
2530         struct blame_entry *ent = NULL;
2531         long dashdash_pos, lno;
2532         char *final_commit_name = NULL;
2533         enum object_type type;
2534         struct commit *final_commit = NULL;
2535
2536         struct string_list range_list = STRING_LIST_INIT_NODUP;
2537         int output_option = 0, opt = 0;
2538         int show_stats = 0;
2539         const char *revs_file = NULL;
2540         const char *contents_from = NULL;
2541         const struct option options[] = {
2542                 OPT_BOOL(0, "incremental", &incremental, N_("Show blame entries as we find them, incrementally")),
2543                 OPT_BOOL('b', NULL, &blank_boundary, N_("Show blank SHA-1 for boundary commits (Default: off)")),
2544                 OPT_BOOL(0, "root", &show_root, N_("Do not treat root commits as boundaries (Default: off)")),
2545                 OPT_BOOL(0, "show-stats", &show_stats, N_("Show work cost statistics")),
2546                 OPT_BOOL(0, "progress", &show_progress, N_("Force progress reporting")),
2547                 OPT_BIT(0, "score-debug", &output_option, N_("Show output score for blame entries"), OUTPUT_SHOW_SCORE),
2548                 OPT_BIT('f', "show-name", &output_option, N_("Show original filename (Default: auto)"), OUTPUT_SHOW_NAME),
2549                 OPT_BIT('n', "show-number", &output_option, N_("Show original linenumber (Default: off)"), OUTPUT_SHOW_NUMBER),
2550                 OPT_BIT('p', "porcelain", &output_option, N_("Show in a format designed for machine consumption"), OUTPUT_PORCELAIN),
2551                 OPT_BIT(0, "line-porcelain", &output_option, N_("Show porcelain format with per-line commit information"), OUTPUT_PORCELAIN|OUTPUT_LINE_PORCELAIN),
2552                 OPT_BIT('c', NULL, &output_option, N_("Use the same output mode as git-annotate (Default: off)"), OUTPUT_ANNOTATE_COMPAT),
2553                 OPT_BIT('t', NULL, &output_option, N_("Show raw timestamp (Default: off)"), OUTPUT_RAW_TIMESTAMP),
2554                 OPT_BIT('l', NULL, &output_option, N_("Show long commit SHA1 (Default: off)"), OUTPUT_LONG_OBJECT_NAME),
2555                 OPT_BIT('s', NULL, &output_option, N_("Suppress author name and timestamp (Default: off)"), OUTPUT_NO_AUTHOR),
2556                 OPT_BIT('e', "show-email", &output_option, N_("Show author email instead of name (Default: off)"), OUTPUT_SHOW_EMAIL),
2557                 OPT_BIT('w', NULL, &xdl_opts, N_("Ignore whitespace differences"), XDF_IGNORE_WHITESPACE),
2558                 OPT_BIT(0, "minimal", &xdl_opts, N_("Spend extra cycles to find better match"), XDF_NEED_MINIMAL),
2559                 OPT_STRING('S', NULL, &revs_file, N_("file"), N_("Use revisions from <file> instead of calling git-rev-list")),
2560                 OPT_STRING(0, "contents", &contents_from, N_("file"), N_("Use <file>'s contents as the final image")),
2561                 { OPTION_CALLBACK, 'C', NULL, &opt, N_("score"), N_("Find line copies within and across files"), PARSE_OPT_OPTARG, blame_copy_callback },
2562                 { OPTION_CALLBACK, 'M', NULL, &opt, N_("score"), N_("Find line movements within and across files"), PARSE_OPT_OPTARG, blame_move_callback },
2563                 OPT_STRING_LIST('L', NULL, &range_list, N_("n,m"), N_("Process only line range n,m, counting from 1")),
2564                 OPT__ABBREV(&abbrev),
2565                 OPT_END()
2566         };
2567
2568         struct parse_opt_ctx_t ctx;
2569         int cmd_is_annotate = !strcmp(argv[0], "annotate");
2570         struct range_set ranges;
2571         unsigned int range_i;
2572         long anchor;
2573
2574         git_config(git_blame_config, &output_option);
2575         init_revisions(&revs, NULL);
2576         revs.date_mode = blame_date_mode;
2577         DIFF_OPT_SET(&revs.diffopt, ALLOW_TEXTCONV);
2578         DIFF_OPT_SET(&revs.diffopt, FOLLOW_RENAMES);
2579
2580         save_commit_buffer = 0;
2581         dashdash_pos = 0;
2582         show_progress = -1;
2583
2584         parse_options_start(&ctx, argc, argv, prefix, options,
2585                             PARSE_OPT_KEEP_DASHDASH | PARSE_OPT_KEEP_ARGV0);
2586         for (;;) {
2587                 switch (parse_options_step(&ctx, options, blame_opt_usage)) {
2588                 case PARSE_OPT_HELP:
2589                         exit(129);
2590                 case PARSE_OPT_DONE:
2591                         if (ctx.argv[0])
2592                                 dashdash_pos = ctx.cpidx;
2593                         goto parse_done;
2594                 }
2595
2596                 if (!strcmp(ctx.argv[0], "--reverse")) {
2597                         ctx.argv[0] = "--children";
2598                         reverse = 1;
2599                 }
2600                 parse_revision_opt(&revs, &ctx, options, blame_opt_usage);
2601         }
2602 parse_done:
2603         no_whole_file_rename = !DIFF_OPT_TST(&revs.diffopt, FOLLOW_RENAMES);
2604         DIFF_OPT_CLR(&revs.diffopt, FOLLOW_RENAMES);
2605         argc = parse_options_end(&ctx);
2606
2607         if (incremental || (output_option & OUTPUT_PORCELAIN)) {
2608                 if (show_progress > 0)
2609                         die("--progress can't be used with --incremental or porcelain formats");
2610                 show_progress = 0;
2611         } else if (show_progress < 0)
2612                 show_progress = isatty(2);
2613
2614         if (0 < abbrev && abbrev < GIT_SHA1_HEXSZ)
2615                 /* one more abbrev length is needed for the boundary commit */
2616                 abbrev++;
2617         else if (!abbrev)
2618                 abbrev = GIT_SHA1_HEXSZ;
2619
2620         if (revs_file && read_ancestry(revs_file))
2621                 die_errno("reading graft file '%s' failed", revs_file);
2622
2623         if (cmd_is_annotate) {
2624                 output_option |= OUTPUT_ANNOTATE_COMPAT;
2625                 blame_date_mode.type = DATE_ISO8601;
2626         } else {
2627                 blame_date_mode = revs.date_mode;
2628         }
2629
2630         /* The maximum width used to show the dates */
2631         switch (blame_date_mode.type) {
2632         case DATE_RFC2822:
2633                 blame_date_width = sizeof("Thu, 19 Oct 2006 16:00:04 -0700");
2634                 break;
2635         case DATE_ISO8601_STRICT:
2636                 blame_date_width = sizeof("2006-10-19T16:00:04-07:00");
2637                 break;
2638         case DATE_ISO8601:
2639                 blame_date_width = sizeof("2006-10-19 16:00:04 -0700");
2640                 break;
2641         case DATE_RAW:
2642                 blame_date_width = sizeof("1161298804 -0700");
2643                 break;
2644         case DATE_UNIX:
2645                 blame_date_width = sizeof("1161298804");
2646                 break;
2647         case DATE_SHORT:
2648                 blame_date_width = sizeof("2006-10-19");
2649                 break;
2650         case DATE_RELATIVE:
2651                 /* TRANSLATORS: This string is used to tell us the maximum
2652                    display width for a relative timestamp in "git blame"
2653                    output.  For C locale, "4 years, 11 months ago", which
2654                    takes 22 places, is the longest among various forms of
2655                    relative timestamps, but your language may need more or
2656                    fewer display columns. */
2657                 blame_date_width = utf8_strwidth(_("4 years, 11 months ago")) + 1; /* add the null */
2658                 break;
2659         case DATE_NORMAL:
2660                 blame_date_width = sizeof("Thu Oct 19 16:00:04 2006 -0700");
2661                 break;
2662         case DATE_STRFTIME:
2663                 blame_date_width = strlen(show_date(0, 0, &blame_date_mode)) + 1; /* add the null */
2664                 break;
2665         }
2666         blame_date_width -= 1; /* strip the null */
2667
2668         if (DIFF_OPT_TST(&revs.diffopt, FIND_COPIES_HARDER))
2669                 opt |= (PICKAXE_BLAME_COPY | PICKAXE_BLAME_MOVE |
2670                         PICKAXE_BLAME_COPY_HARDER);
2671
2672         if (!blame_move_score)
2673                 blame_move_score = BLAME_DEFAULT_MOVE_SCORE;
2674         if (!blame_copy_score)
2675                 blame_copy_score = BLAME_DEFAULT_COPY_SCORE;
2676
2677         /*
2678          * We have collected options unknown to us in argv[1..unk]
2679          * which are to be passed to revision machinery if we are
2680          * going to do the "bottom" processing.
2681          *
2682          * The remaining are:
2683          *
2684          * (1) if dashdash_pos != 0, it is either
2685          *     "blame [revisions] -- <path>" or
2686          *     "blame -- <path> <rev>"
2687          *
2688          * (2) otherwise, it is one of the two:
2689          *     "blame [revisions] <path>"
2690          *     "blame <path> <rev>"
2691          *
2692          * Note that we must strip out <path> from the arguments: we do not
2693          * want the path pruning but we may want "bottom" processing.
2694          */
2695         if (dashdash_pos) {
2696                 switch (argc - dashdash_pos - 1) {
2697                 case 2: /* (1b) */
2698                         if (argc != 4)
2699                                 usage_with_options(blame_opt_usage, options);
2700                         /* reorder for the new way: <rev> -- <path> */
2701                         argv[1] = argv[3];
2702                         argv[3] = argv[2];
2703                         argv[2] = "--";
2704                         /* FALLTHROUGH */
2705                 case 1: /* (1a) */
2706                         path = add_prefix(prefix, argv[--argc]);
2707                         argv[argc] = NULL;
2708                         break;
2709                 default:
2710                         usage_with_options(blame_opt_usage, options);
2711                 }
2712         } else {
2713                 if (argc < 2)
2714                         usage_with_options(blame_opt_usage, options);
2715                 path = add_prefix(prefix, argv[argc - 1]);
2716                 if (argc == 3 && !file_exists(path)) { /* (2b) */
2717                         path = add_prefix(prefix, argv[1]);
2718                         argv[1] = argv[2];
2719                 }
2720                 argv[argc - 1] = "--";
2721
2722                 setup_work_tree();
2723                 if (!file_exists(path))
2724                         die_errno("cannot stat path '%s'", path);
2725         }
2726
2727         revs.disable_stdin = 1;
2728         setup_revisions(argc, argv, &revs, NULL);
2729         memset(&sb, 0, sizeof(sb));
2730
2731         sb.revs = &revs;
2732         if (!reverse) {
2733                 final_commit_name = prepare_final(&sb);
2734                 sb.commits.compare = compare_commits_by_commit_date;
2735         }
2736         else if (contents_from)
2737                 die("--contents and --reverse do not blend well.");
2738         else {
2739                 final_commit_name = prepare_initial(&sb);
2740                 sb.commits.compare = compare_commits_by_reverse_commit_date;
2741                 if (revs.first_parent_only)
2742                         revs.children.name = NULL;
2743         }
2744
2745         if (!sb.final) {
2746                 /*
2747                  * "--not A B -- path" without anything positive;
2748                  * do not default to HEAD, but use the working tree
2749                  * or "--contents".
2750                  */
2751                 setup_work_tree();
2752                 sb.final = fake_working_tree_commit(&sb.revs->diffopt,
2753                                                     path, contents_from);
2754                 add_pending_object(&revs, &(sb.final->object), ":");
2755         }
2756         else if (contents_from)
2757                 die("Cannot use --contents with final commit object name");
2758
2759         if (reverse && revs.first_parent_only) {
2760                 final_commit = find_single_final(sb.revs, NULL);
2761                 if (!final_commit)
2762                         die("--reverse and --first-parent together require specified latest commit");
2763         }
2764
2765         /*
2766          * If we have bottom, this will mark the ancestors of the
2767          * bottom commits we would reach while traversing as
2768          * uninteresting.
2769          */
2770         if (prepare_revision_walk(&revs))
2771                 die(_("revision walk setup failed"));
2772
2773         if (reverse && revs.first_parent_only) {
2774                 struct commit *c = final_commit;
2775
2776                 sb.revs->children.name = "children";
2777                 while (c->parents &&
2778                        oidcmp(&c->object.oid, &sb.final->object.oid)) {
2779                         struct commit_list *l = xcalloc(1, sizeof(*l));
2780
2781                         l->item = c;
2782                         if (add_decoration(&sb.revs->children,
2783                                            &c->parents->item->object, l))
2784                                 die("BUG: not unique item in first-parent chain");
2785                         c = c->parents->item;
2786                 }
2787
2788                 if (oidcmp(&c->object.oid, &sb.final->object.oid))
2789                         die("--reverse --first-parent together require range along first-parent chain");
2790         }
2791
2792         if (is_null_oid(&sb.final->object.oid)) {
2793                 o = sb.final->util;
2794                 sb.final_buf = xmemdupz(o->file.ptr, o->file.size);
2795                 sb.final_buf_size = o->file.size;
2796         }
2797         else {
2798                 o = get_origin(&sb, sb.final, path);
2799                 if (fill_blob_sha1_and_mode(o))
2800                         die("no such path %s in %s", path, final_commit_name);
2801
2802                 if (DIFF_OPT_TST(&sb.revs->diffopt, ALLOW_TEXTCONV) &&
2803                     textconv_object(path, o->mode, o->blob_sha1, 1, (char **) &sb.final_buf,
2804                                     &sb.final_buf_size))
2805                         ;
2806                 else
2807                         sb.final_buf = read_sha1_file(o->blob_sha1, &type,
2808                                                       &sb.final_buf_size);
2809
2810                 if (!sb.final_buf)
2811                         die("Cannot read blob %s for path %s",
2812                             sha1_to_hex(o->blob_sha1),
2813                             path);
2814         }
2815         num_read_blob++;
2816         lno = prepare_lines(&sb);
2817
2818         if (lno && !range_list.nr)
2819                 string_list_append(&range_list, "1");
2820
2821         anchor = 1;
2822         range_set_init(&ranges, range_list.nr);
2823         for (range_i = 0; range_i < range_list.nr; ++range_i) {
2824                 long bottom, top;
2825                 if (parse_range_arg(range_list.items[range_i].string,
2826                                     nth_line_cb, &sb, lno, anchor,
2827                                     &bottom, &top, sb.path))
2828                         usage(blame_usage);
2829                 if (lno < top || ((lno || bottom) && lno < bottom))
2830                         die("file %s has only %lu lines", path, lno);
2831                 if (bottom < 1)
2832                         bottom = 1;
2833                 if (top < 1)
2834                         top = lno;
2835                 bottom--;
2836                 range_set_append_unsafe(&ranges, bottom, top);
2837                 anchor = top + 1;
2838         }
2839         sort_and_merge_range_set(&ranges);
2840
2841         for (range_i = ranges.nr; range_i > 0; --range_i) {
2842                 const struct range *r = &ranges.ranges[range_i - 1];
2843                 long bottom = r->start;
2844                 long top = r->end;
2845                 struct blame_entry *next = ent;
2846                 ent = xcalloc(1, sizeof(*ent));
2847                 ent->lno = bottom;
2848                 ent->num_lines = top - bottom;
2849                 ent->suspect = o;
2850                 ent->s_lno = bottom;
2851                 ent->next = next;
2852                 origin_incref(o);
2853         }
2854
2855         o->suspects = ent;
2856         prio_queue_put(&sb.commits, o->commit);
2857
2858         origin_decref(o);
2859
2860         range_set_release(&ranges);
2861         string_list_clear(&range_list, 0);
2862
2863         sb.ent = NULL;
2864         sb.path = path;
2865
2866         read_mailmap(&mailmap, NULL);
2867
2868         assign_blame(&sb, opt);
2869
2870         if (!incremental)
2871                 setup_pager();
2872
2873         free(final_commit_name);
2874
2875         if (incremental)
2876                 return 0;
2877
2878         sb.ent = blame_sort(sb.ent, compare_blame_final);
2879
2880         coalesce(&sb);
2881
2882         if (!(output_option & OUTPUT_PORCELAIN))
2883                 find_alignment(&sb, &output_option);
2884
2885         output(&sb, output_option);
2886         free((void *)sb.final_buf);
2887         for (ent = sb.ent; ent; ) {
2888                 struct blame_entry *e = ent->next;
2889                 free(ent);
2890                 ent = e;
2891         }
2892
2893         if (show_stats) {
2894                 printf("num read blob: %d\n", num_read_blob);
2895                 printf("num get patch: %d\n", num_get_patch);
2896                 printf("num commits: %d\n", num_commits);
2897         }
2898         return 0;
2899 }