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