Merge branch 'tb/grep-only-matching'
[git] / blame.c
1 #include "cache.h"
2 #include "refs.h"
3 #include "object-store.h"
4 #include "cache-tree.h"
5 #include "mergesort.h"
6 #include "diff.h"
7 #include "diffcore.h"
8 #include "tag.h"
9 #include "blame.h"
10 #include "alloc.h"
11 #include "commit-slab.h"
12
13 define_commit_slab(blame_suspects, struct blame_origin *);
14 static struct blame_suspects blame_suspects;
15
16 struct blame_origin *get_blame_suspects(struct commit *commit)
17 {
18         struct blame_origin **result;
19
20         result = blame_suspects_peek(&blame_suspects, commit);
21
22         return result ? *result : NULL;
23 }
24
25 static void set_blame_suspects(struct commit *commit, struct blame_origin *origin)
26 {
27         *blame_suspects_at(&blame_suspects, commit) = origin;
28 }
29
30 void blame_origin_decref(struct blame_origin *o)
31 {
32         if (o && --o->refcnt <= 0) {
33                 struct blame_origin *p, *l = NULL;
34                 if (o->previous)
35                         blame_origin_decref(o->previous);
36                 free(o->file.ptr);
37                 /* Should be present exactly once in commit chain */
38                 for (p = get_blame_suspects(o->commit); p; l = p, p = p->next) {
39                         if (p == o) {
40                                 if (l)
41                                         l->next = p->next;
42                                 else
43                                         set_blame_suspects(o->commit, p->next);
44                                 free(o);
45                                 return;
46                         }
47                 }
48                 die("internal error in blame_origin_decref");
49         }
50 }
51
52 /*
53  * Given a commit and a path in it, create a new origin structure.
54  * The callers that add blame to the scoreboard should use
55  * get_origin() to obtain shared, refcounted copy instead of calling
56  * this function directly.
57  */
58 static struct blame_origin *make_origin(struct commit *commit, const char *path)
59 {
60         struct blame_origin *o;
61         FLEX_ALLOC_STR(o, path, path);
62         o->commit = commit;
63         o->refcnt = 1;
64         o->next = get_blame_suspects(commit);
65         set_blame_suspects(commit, o);
66         return o;
67 }
68
69 /*
70  * Locate an existing origin or create a new one.
71  * This moves the origin to front position in the commit util list.
72  */
73 static struct blame_origin *get_origin(struct commit *commit, const char *path)
74 {
75         struct blame_origin *o, *l;
76
77         for (o = get_blame_suspects(commit), l = NULL; o; l = o, o = o->next) {
78                 if (!strcmp(o->path, path)) {
79                         /* bump to front */
80                         if (l) {
81                                 l->next = o->next;
82                                 o->next = get_blame_suspects(commit);
83                                 set_blame_suspects(commit, o);
84                         }
85                         return blame_origin_incref(o);
86                 }
87         }
88         return make_origin(commit, path);
89 }
90
91
92
93 static void verify_working_tree_path(struct commit *work_tree, const char *path)
94 {
95         struct commit_list *parents;
96         int pos;
97
98         for (parents = work_tree->parents; parents; parents = parents->next) {
99                 const struct object_id *commit_oid = &parents->item->object.oid;
100                 struct object_id blob_oid;
101                 unsigned mode;
102
103                 if (!get_tree_entry(commit_oid, path, &blob_oid, &mode) &&
104                     oid_object_info(the_repository, &blob_oid, NULL) == OBJ_BLOB)
105                         return;
106         }
107
108         pos = cache_name_pos(path, strlen(path));
109         if (pos >= 0)
110                 ; /* path is in the index */
111         else if (-1 - pos < active_nr &&
112                  !strcmp(active_cache[-1 - pos]->name, path))
113                 ; /* path is in the index, unmerged */
114         else
115                 die("no such path '%s' in HEAD", path);
116 }
117
118 static struct commit_list **append_parent(struct commit_list **tail, const struct object_id *oid)
119 {
120         struct commit *parent;
121
122         parent = lookup_commit_reference(the_repository, oid);
123         if (!parent)
124                 die("no such commit %s", oid_to_hex(oid));
125         return &commit_list_insert(parent, tail)->next;
126 }
127
128 static void append_merge_parents(struct commit_list **tail)
129 {
130         int merge_head;
131         struct strbuf line = STRBUF_INIT;
132
133         merge_head = open(git_path_merge_head(the_repository), O_RDONLY);
134         if (merge_head < 0) {
135                 if (errno == ENOENT)
136                         return;
137                 die("cannot open '%s' for reading",
138                     git_path_merge_head(the_repository));
139         }
140
141         while (!strbuf_getwholeline_fd(&line, merge_head, '\n')) {
142                 struct object_id oid;
143                 if (line.len < GIT_SHA1_HEXSZ || get_oid_hex(line.buf, &oid))
144                         die("unknown line in '%s': %s",
145                             git_path_merge_head(the_repository), line.buf);
146                 tail = append_parent(tail, &oid);
147         }
148         close(merge_head);
149         strbuf_release(&line);
150 }
151
152 /*
153  * This isn't as simple as passing sb->buf and sb->len, because we
154  * want to transfer ownership of the buffer to the commit (so we
155  * must use detach).
156  */
157 static void set_commit_buffer_from_strbuf(struct commit *c, struct strbuf *sb)
158 {
159         size_t len;
160         void *buf = strbuf_detach(sb, &len);
161         set_commit_buffer(the_repository, c, buf, len);
162 }
163
164 /*
165  * Prepare a dummy commit that represents the work tree (or staged) item.
166  * Note that annotating work tree item never works in the reverse.
167  */
168 static struct commit *fake_working_tree_commit(struct diff_options *opt,
169                                                const char *path,
170                                                const char *contents_from)
171 {
172         struct commit *commit;
173         struct blame_origin *origin;
174         struct commit_list **parent_tail, *parent;
175         struct object_id head_oid;
176         struct strbuf buf = STRBUF_INIT;
177         const char *ident;
178         time_t now;
179         int len;
180         struct cache_entry *ce;
181         unsigned mode;
182         struct strbuf msg = STRBUF_INIT;
183
184         read_cache();
185         time(&now);
186         commit = alloc_commit_node(the_repository);
187         commit->object.parsed = 1;
188         commit->date = now;
189         parent_tail = &commit->parents;
190
191         if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, &head_oid, NULL))
192                 die("no such ref: HEAD");
193
194         parent_tail = append_parent(parent_tail, &head_oid);
195         append_merge_parents(parent_tail);
196         verify_working_tree_path(commit, path);
197
198         origin = make_origin(commit, path);
199
200         ident = fmt_ident("Not Committed Yet", "not.committed.yet", NULL, 0);
201         strbuf_addstr(&msg, "tree 0000000000000000000000000000000000000000\n");
202         for (parent = commit->parents; parent; parent = parent->next)
203                 strbuf_addf(&msg, "parent %s\n",
204                             oid_to_hex(&parent->item->object.oid));
205         strbuf_addf(&msg,
206                     "author %s\n"
207                     "committer %s\n\n"
208                     "Version of %s from %s\n",
209                     ident, ident, path,
210                     (!contents_from ? path :
211                      (!strcmp(contents_from, "-") ? "standard input" : contents_from)));
212         set_commit_buffer_from_strbuf(commit, &msg);
213
214         if (!contents_from || strcmp("-", contents_from)) {
215                 struct stat st;
216                 const char *read_from;
217                 char *buf_ptr;
218                 unsigned long buf_len;
219
220                 if (contents_from) {
221                         if (stat(contents_from, &st) < 0)
222                                 die_errno("Cannot stat '%s'", contents_from);
223                         read_from = contents_from;
224                 }
225                 else {
226                         if (lstat(path, &st) < 0)
227                                 die_errno("Cannot lstat '%s'", path);
228                         read_from = path;
229                 }
230                 mode = canon_mode(st.st_mode);
231
232                 switch (st.st_mode & S_IFMT) {
233                 case S_IFREG:
234                         if (opt->flags.allow_textconv &&
235                             textconv_object(read_from, mode, &null_oid, 0, &buf_ptr, &buf_len))
236                                 strbuf_attach(&buf, buf_ptr, buf_len, buf_len + 1);
237                         else if (strbuf_read_file(&buf, read_from, st.st_size) != st.st_size)
238                                 die_errno("cannot open or read '%s'", read_from);
239                         break;
240                 case S_IFLNK:
241                         if (strbuf_readlink(&buf, read_from, st.st_size) < 0)
242                                 die_errno("cannot readlink '%s'", read_from);
243                         break;
244                 default:
245                         die("unsupported file type %s", read_from);
246                 }
247         }
248         else {
249                 /* Reading from stdin */
250                 mode = 0;
251                 if (strbuf_read(&buf, 0, 0) < 0)
252                         die_errno("failed to read from stdin");
253         }
254         convert_to_git(&the_index, path, buf.buf, buf.len, &buf, 0);
255         origin->file.ptr = buf.buf;
256         origin->file.size = buf.len;
257         pretend_object_file(buf.buf, buf.len, OBJ_BLOB, &origin->blob_oid);
258
259         /*
260          * Read the current index, replace the path entry with
261          * origin->blob_sha1 without mucking with its mode or type
262          * bits; we are not going to write this index out -- we just
263          * want to run "diff-index --cached".
264          */
265         discard_cache();
266         read_cache();
267
268         len = strlen(path);
269         if (!mode) {
270                 int pos = cache_name_pos(path, len);
271                 if (0 <= pos)
272                         mode = active_cache[pos]->ce_mode;
273                 else
274                         /* Let's not bother reading from HEAD tree */
275                         mode = S_IFREG | 0644;
276         }
277         ce = make_empty_cache_entry(&the_index, len);
278         oidcpy(&ce->oid, &origin->blob_oid);
279         memcpy(ce->name, path, len);
280         ce->ce_flags = create_ce_flags(0);
281         ce->ce_namelen = len;
282         ce->ce_mode = create_ce_mode(mode);
283         add_cache_entry(ce, ADD_CACHE_OK_TO_ADD|ADD_CACHE_OK_TO_REPLACE);
284
285         cache_tree_invalidate_path(&the_index, path);
286
287         return commit;
288 }
289
290
291
292 static int diff_hunks(mmfile_t *file_a, mmfile_t *file_b,
293                       xdl_emit_hunk_consume_func_t hunk_func, void *cb_data, int xdl_opts)
294 {
295         xpparam_t xpp = {0};
296         xdemitconf_t xecfg = {0};
297         xdemitcb_t ecb = {NULL};
298
299         xpp.flags = xdl_opts;
300         xecfg.hunk_func = hunk_func;
301         ecb.priv = cb_data;
302         return xdi_diff(file_a, file_b, &xpp, &xecfg, &ecb);
303 }
304
305 /*
306  * Given an origin, prepare mmfile_t structure to be used by the
307  * diff machinery
308  */
309 static void fill_origin_blob(struct diff_options *opt,
310                              struct blame_origin *o, mmfile_t *file, int *num_read_blob)
311 {
312         if (!o->file.ptr) {
313                 enum object_type type;
314                 unsigned long file_size;
315
316                 (*num_read_blob)++;
317                 if (opt->flags.allow_textconv &&
318                     textconv_object(o->path, o->mode, &o->blob_oid, 1, &file->ptr, &file_size))
319                         ;
320                 else
321                         file->ptr = read_object_file(&o->blob_oid, &type,
322                                                      &file_size);
323                 file->size = file_size;
324
325                 if (!file->ptr)
326                         die("Cannot read blob %s for path %s",
327                             oid_to_hex(&o->blob_oid),
328                             o->path);
329                 o->file = *file;
330         }
331         else
332                 *file = o->file;
333 }
334
335 static void drop_origin_blob(struct blame_origin *o)
336 {
337         if (o->file.ptr) {
338                 FREE_AND_NULL(o->file.ptr);
339         }
340 }
341
342 /*
343  * Any merge of blames happens on lists of blames that arrived via
344  * different parents in a single suspect.  In this case, we want to
345  * sort according to the suspect line numbers as opposed to the final
346  * image line numbers.  The function body is somewhat longish because
347  * it avoids unnecessary writes.
348  */
349
350 static struct blame_entry *blame_merge(struct blame_entry *list1,
351                                        struct blame_entry *list2)
352 {
353         struct blame_entry *p1 = list1, *p2 = list2,
354                 **tail = &list1;
355
356         if (!p1)
357                 return p2;
358         if (!p2)
359                 return p1;
360
361         if (p1->s_lno <= p2->s_lno) {
362                 do {
363                         tail = &p1->next;
364                         if ((p1 = *tail) == NULL) {
365                                 *tail = p2;
366                                 return list1;
367                         }
368                 } while (p1->s_lno <= p2->s_lno);
369         }
370         for (;;) {
371                 *tail = p2;
372                 do {
373                         tail = &p2->next;
374                         if ((p2 = *tail) == NULL)  {
375                                 *tail = p1;
376                                 return list1;
377                         }
378                 } while (p1->s_lno > p2->s_lno);
379                 *tail = p1;
380                 do {
381                         tail = &p1->next;
382                         if ((p1 = *tail) == NULL) {
383                                 *tail = p2;
384                                 return list1;
385                         }
386                 } while (p1->s_lno <= p2->s_lno);
387         }
388 }
389
390 static void *get_next_blame(const void *p)
391 {
392         return ((struct blame_entry *)p)->next;
393 }
394
395 static void set_next_blame(void *p1, void *p2)
396 {
397         ((struct blame_entry *)p1)->next = p2;
398 }
399
400 /*
401  * Final image line numbers are all different, so we don't need a
402  * three-way comparison here.
403  */
404
405 static int compare_blame_final(const void *p1, const void *p2)
406 {
407         return ((struct blame_entry *)p1)->lno > ((struct blame_entry *)p2)->lno
408                 ? 1 : -1;
409 }
410
411 static int compare_blame_suspect(const void *p1, const void *p2)
412 {
413         const struct blame_entry *s1 = p1, *s2 = p2;
414         /*
415          * to allow for collating suspects, we sort according to the
416          * respective pointer value as the primary sorting criterion.
417          * The actual relation is pretty unimportant as long as it
418          * establishes a total order.  Comparing as integers gives us
419          * that.
420          */
421         if (s1->suspect != s2->suspect)
422                 return (intptr_t)s1->suspect > (intptr_t)s2->suspect ? 1 : -1;
423         if (s1->s_lno == s2->s_lno)
424                 return 0;
425         return s1->s_lno > s2->s_lno ? 1 : -1;
426 }
427
428 void blame_sort_final(struct blame_scoreboard *sb)
429 {
430         sb->ent = llist_mergesort(sb->ent, get_next_blame, set_next_blame,
431                                   compare_blame_final);
432 }
433
434 static int compare_commits_by_reverse_commit_date(const void *a,
435                                                   const void *b,
436                                                   void *c)
437 {
438         return -compare_commits_by_commit_date(a, b, c);
439 }
440
441 /*
442  * For debugging -- origin is refcounted, and this asserts that
443  * we do not underflow.
444  */
445 static void sanity_check_refcnt(struct blame_scoreboard *sb)
446 {
447         int baa = 0;
448         struct blame_entry *ent;
449
450         for (ent = sb->ent; ent; ent = ent->next) {
451                 /* Nobody should have zero or negative refcnt */
452                 if (ent->suspect->refcnt <= 0) {
453                         fprintf(stderr, "%s in %s has negative refcnt %d\n",
454                                 ent->suspect->path,
455                                 oid_to_hex(&ent->suspect->commit->object.oid),
456                                 ent->suspect->refcnt);
457                         baa = 1;
458                 }
459         }
460         if (baa)
461                 sb->on_sanity_fail(sb, baa);
462 }
463
464 /*
465  * If two blame entries that are next to each other came from
466  * contiguous lines in the same origin (i.e. <commit, path> pair),
467  * merge them together.
468  */
469 void blame_coalesce(struct blame_scoreboard *sb)
470 {
471         struct blame_entry *ent, *next;
472
473         for (ent = sb->ent; ent && (next = ent->next); ent = next) {
474                 if (ent->suspect == next->suspect &&
475                     ent->s_lno + ent->num_lines == next->s_lno) {
476                         ent->num_lines += next->num_lines;
477                         ent->next = next->next;
478                         blame_origin_decref(next->suspect);
479                         free(next);
480                         ent->score = 0;
481                         next = ent; /* again */
482                 }
483         }
484
485         if (sb->debug) /* sanity */
486                 sanity_check_refcnt(sb);
487 }
488
489 /*
490  * Merge the given sorted list of blames into a preexisting origin.
491  * If there were no previous blames to that commit, it is entered into
492  * the commit priority queue of the score board.
493  */
494
495 static void queue_blames(struct blame_scoreboard *sb, struct blame_origin *porigin,
496                          struct blame_entry *sorted)
497 {
498         if (porigin->suspects)
499                 porigin->suspects = blame_merge(porigin->suspects, sorted);
500         else {
501                 struct blame_origin *o;
502                 for (o = get_blame_suspects(porigin->commit); o; o = o->next) {
503                         if (o->suspects) {
504                                 porigin->suspects = sorted;
505                                 return;
506                         }
507                 }
508                 porigin->suspects = sorted;
509                 prio_queue_put(&sb->commits, porigin->commit);
510         }
511 }
512
513 /*
514  * Fill the blob_sha1 field of an origin if it hasn't, so that later
515  * call to fill_origin_blob() can use it to locate the data.  blob_sha1
516  * for an origin is also used to pass the blame for the entire file to
517  * the parent to detect the case where a child's blob is identical to
518  * that of its parent's.
519  *
520  * This also fills origin->mode for corresponding tree path.
521  */
522 static int fill_blob_sha1_and_mode(struct blame_origin *origin)
523 {
524         if (!is_null_oid(&origin->blob_oid))
525                 return 0;
526         if (get_tree_entry(&origin->commit->object.oid, origin->path, &origin->blob_oid, &origin->mode))
527                 goto error_out;
528         if (oid_object_info(the_repository, &origin->blob_oid, NULL) != OBJ_BLOB)
529                 goto error_out;
530         return 0;
531  error_out:
532         oidclr(&origin->blob_oid);
533         origin->mode = S_IFINVALID;
534         return -1;
535 }
536
537 /*
538  * We have an origin -- check if the same path exists in the
539  * parent and return an origin structure to represent it.
540  */
541 static struct blame_origin *find_origin(struct commit *parent,
542                                   struct blame_origin *origin)
543 {
544         struct blame_origin *porigin;
545         struct diff_options diff_opts;
546         const char *paths[2];
547
548         /* First check any existing origins */
549         for (porigin = get_blame_suspects(parent); porigin; porigin = porigin->next)
550                 if (!strcmp(porigin->path, origin->path)) {
551                         /*
552                          * The same path between origin and its parent
553                          * without renaming -- the most common case.
554                          */
555                         return blame_origin_incref (porigin);
556                 }
557
558         /* See if the origin->path is different between parent
559          * and origin first.  Most of the time they are the
560          * same and diff-tree is fairly efficient about this.
561          */
562         diff_setup(&diff_opts);
563         diff_opts.flags.recursive = 1;
564         diff_opts.detect_rename = 0;
565         diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;
566         paths[0] = origin->path;
567         paths[1] = NULL;
568
569         parse_pathspec(&diff_opts.pathspec,
570                        PATHSPEC_ALL_MAGIC & ~PATHSPEC_LITERAL,
571                        PATHSPEC_LITERAL_PATH, "", paths);
572         diff_setup_done(&diff_opts);
573
574         if (is_null_oid(&origin->commit->object.oid))
575                 do_diff_cache(get_commit_tree_oid(parent), &diff_opts);
576         else
577                 diff_tree_oid(get_commit_tree_oid(parent),
578                               get_commit_tree_oid(origin->commit),
579                               "", &diff_opts);
580         diffcore_std(&diff_opts);
581
582         if (!diff_queued_diff.nr) {
583                 /* The path is the same as parent */
584                 porigin = get_origin(parent, origin->path);
585                 oidcpy(&porigin->blob_oid, &origin->blob_oid);
586                 porigin->mode = origin->mode;
587         } else {
588                 /*
589                  * Since origin->path is a pathspec, if the parent
590                  * commit had it as a directory, we will see a whole
591                  * bunch of deletion of files in the directory that we
592                  * do not care about.
593                  */
594                 int i;
595                 struct diff_filepair *p = NULL;
596                 for (i = 0; i < diff_queued_diff.nr; i++) {
597                         const char *name;
598                         p = diff_queued_diff.queue[i];
599                         name = p->one->path ? p->one->path : p->two->path;
600                         if (!strcmp(name, origin->path))
601                                 break;
602                 }
603                 if (!p)
604                         die("internal error in blame::find_origin");
605                 switch (p->status) {
606                 default:
607                         die("internal error in blame::find_origin (%c)",
608                             p->status);
609                 case 'M':
610                         porigin = get_origin(parent, origin->path);
611                         oidcpy(&porigin->blob_oid, &p->one->oid);
612                         porigin->mode = p->one->mode;
613                         break;
614                 case 'A':
615                 case 'T':
616                         /* Did not exist in parent, or type changed */
617                         break;
618                 }
619         }
620         diff_flush(&diff_opts);
621         clear_pathspec(&diff_opts.pathspec);
622         return porigin;
623 }
624
625 /*
626  * We have an origin -- find the path that corresponds to it in its
627  * parent and return an origin structure to represent it.
628  */
629 static struct blame_origin *find_rename(struct commit *parent,
630                                   struct blame_origin *origin)
631 {
632         struct blame_origin *porigin = NULL;
633         struct diff_options diff_opts;
634         int i;
635
636         diff_setup(&diff_opts);
637         diff_opts.flags.recursive = 1;
638         diff_opts.detect_rename = DIFF_DETECT_RENAME;
639         diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;
640         diff_opts.single_follow = origin->path;
641         diff_setup_done(&diff_opts);
642
643         if (is_null_oid(&origin->commit->object.oid))
644                 do_diff_cache(get_commit_tree_oid(parent), &diff_opts);
645         else
646                 diff_tree_oid(get_commit_tree_oid(parent),
647                               get_commit_tree_oid(origin->commit),
648                               "", &diff_opts);
649         diffcore_std(&diff_opts);
650
651         for (i = 0; i < diff_queued_diff.nr; i++) {
652                 struct diff_filepair *p = diff_queued_diff.queue[i];
653                 if ((p->status == 'R' || p->status == 'C') &&
654                     !strcmp(p->two->path, origin->path)) {
655                         porigin = get_origin(parent, p->one->path);
656                         oidcpy(&porigin->blob_oid, &p->one->oid);
657                         porigin->mode = p->one->mode;
658                         break;
659                 }
660         }
661         diff_flush(&diff_opts);
662         clear_pathspec(&diff_opts.pathspec);
663         return porigin;
664 }
665
666 /*
667  * Append a new blame entry to a given output queue.
668  */
669 static void add_blame_entry(struct blame_entry ***queue,
670                             const struct blame_entry *src)
671 {
672         struct blame_entry *e = xmalloc(sizeof(*e));
673         memcpy(e, src, sizeof(*e));
674         blame_origin_incref(e->suspect);
675
676         e->next = **queue;
677         **queue = e;
678         *queue = &e->next;
679 }
680
681 /*
682  * src typically is on-stack; we want to copy the information in it to
683  * a malloced blame_entry that gets added to the given queue.  The
684  * origin of dst loses a refcnt.
685  */
686 static void dup_entry(struct blame_entry ***queue,
687                       struct blame_entry *dst, struct blame_entry *src)
688 {
689         blame_origin_incref(src->suspect);
690         blame_origin_decref(dst->suspect);
691         memcpy(dst, src, sizeof(*src));
692         dst->next = **queue;
693         **queue = dst;
694         *queue = &dst->next;
695 }
696
697 const char *blame_nth_line(struct blame_scoreboard *sb, long lno)
698 {
699         return sb->final_buf + sb->lineno[lno];
700 }
701
702 /*
703  * It is known that lines between tlno to same came from parent, and e
704  * has an overlap with that range.  it also is known that parent's
705  * line plno corresponds to e's line tlno.
706  *
707  *                <---- e ----->
708  *                   <------>
709  *                   <------------>
710  *             <------------>
711  *             <------------------>
712  *
713  * Split e into potentially three parts; before this chunk, the chunk
714  * to be blamed for the parent, and after that portion.
715  */
716 static void split_overlap(struct blame_entry *split,
717                           struct blame_entry *e,
718                           int tlno, int plno, int same,
719                           struct blame_origin *parent)
720 {
721         int chunk_end_lno;
722         memset(split, 0, sizeof(struct blame_entry [3]));
723
724         if (e->s_lno < tlno) {
725                 /* there is a pre-chunk part not blamed on parent */
726                 split[0].suspect = blame_origin_incref(e->suspect);
727                 split[0].lno = e->lno;
728                 split[0].s_lno = e->s_lno;
729                 split[0].num_lines = tlno - e->s_lno;
730                 split[1].lno = e->lno + tlno - e->s_lno;
731                 split[1].s_lno = plno;
732         }
733         else {
734                 split[1].lno = e->lno;
735                 split[1].s_lno = plno + (e->s_lno - tlno);
736         }
737
738         if (same < e->s_lno + e->num_lines) {
739                 /* there is a post-chunk part not blamed on parent */
740                 split[2].suspect = blame_origin_incref(e->suspect);
741                 split[2].lno = e->lno + (same - e->s_lno);
742                 split[2].s_lno = e->s_lno + (same - e->s_lno);
743                 split[2].num_lines = e->s_lno + e->num_lines - same;
744                 chunk_end_lno = split[2].lno;
745         }
746         else
747                 chunk_end_lno = e->lno + e->num_lines;
748         split[1].num_lines = chunk_end_lno - split[1].lno;
749
750         /*
751          * if it turns out there is nothing to blame the parent for,
752          * forget about the splitting.  !split[1].suspect signals this.
753          */
754         if (split[1].num_lines < 1)
755                 return;
756         split[1].suspect = blame_origin_incref(parent);
757 }
758
759 /*
760  * split_overlap() divided an existing blame e into up to three parts
761  * in split.  Any assigned blame is moved to queue to
762  * reflect the split.
763  */
764 static void split_blame(struct blame_entry ***blamed,
765                         struct blame_entry ***unblamed,
766                         struct blame_entry *split,
767                         struct blame_entry *e)
768 {
769         if (split[0].suspect && split[2].suspect) {
770                 /* The first part (reuse storage for the existing entry e) */
771                 dup_entry(unblamed, e, &split[0]);
772
773                 /* The last part -- me */
774                 add_blame_entry(unblamed, &split[2]);
775
776                 /* ... and the middle part -- parent */
777                 add_blame_entry(blamed, &split[1]);
778         }
779         else if (!split[0].suspect && !split[2].suspect)
780                 /*
781                  * The parent covers the entire area; reuse storage for
782                  * e and replace it with the parent.
783                  */
784                 dup_entry(blamed, e, &split[1]);
785         else if (split[0].suspect) {
786                 /* me and then parent */
787                 dup_entry(unblamed, e, &split[0]);
788                 add_blame_entry(blamed, &split[1]);
789         }
790         else {
791                 /* parent and then me */
792                 dup_entry(blamed, e, &split[1]);
793                 add_blame_entry(unblamed, &split[2]);
794         }
795 }
796
797 /*
798  * After splitting the blame, the origins used by the
799  * on-stack blame_entry should lose one refcnt each.
800  */
801 static void decref_split(struct blame_entry *split)
802 {
803         int i;
804
805         for (i = 0; i < 3; i++)
806                 blame_origin_decref(split[i].suspect);
807 }
808
809 /*
810  * reverse_blame reverses the list given in head, appending tail.
811  * That allows us to build lists in reverse order, then reverse them
812  * afterwards.  This can be faster than building the list in proper
813  * order right away.  The reason is that building in proper order
814  * requires writing a link in the _previous_ element, while building
815  * in reverse order just requires placing the list head into the
816  * _current_ element.
817  */
818
819 static struct blame_entry *reverse_blame(struct blame_entry *head,
820                                          struct blame_entry *tail)
821 {
822         while (head) {
823                 struct blame_entry *next = head->next;
824                 head->next = tail;
825                 tail = head;
826                 head = next;
827         }
828         return tail;
829 }
830
831 /*
832  * Process one hunk from the patch between the current suspect for
833  * blame_entry e and its parent.  This first blames any unfinished
834  * entries before the chunk (which is where target and parent start
835  * differing) on the parent, and then splits blame entries at the
836  * start and at the end of the difference region.  Since use of -M and
837  * -C options may lead to overlapping/duplicate source line number
838  * ranges, all we can rely on from sorting/merging is the order of the
839  * first suspect line number.
840  */
841 static void blame_chunk(struct blame_entry ***dstq, struct blame_entry ***srcq,
842                         int tlno, int offset, int same,
843                         struct blame_origin *parent)
844 {
845         struct blame_entry *e = **srcq;
846         struct blame_entry *samep = NULL, *diffp = NULL;
847
848         while (e && e->s_lno < tlno) {
849                 struct blame_entry *next = e->next;
850                 /*
851                  * current record starts before differing portion.  If
852                  * it reaches into it, we need to split it up and
853                  * examine the second part separately.
854                  */
855                 if (e->s_lno + e->num_lines > tlno) {
856                         /* Move second half to a new record */
857                         int len = tlno - e->s_lno;
858                         struct blame_entry *n = xcalloc(1, sizeof (struct blame_entry));
859                         n->suspect = e->suspect;
860                         n->lno = e->lno + len;
861                         n->s_lno = e->s_lno + len;
862                         n->num_lines = e->num_lines - len;
863                         e->num_lines = len;
864                         e->score = 0;
865                         /* Push new record to diffp */
866                         n->next = diffp;
867                         diffp = n;
868                 } else
869                         blame_origin_decref(e->suspect);
870                 /* Pass blame for everything before the differing
871                  * chunk to the parent */
872                 e->suspect = blame_origin_incref(parent);
873                 e->s_lno += offset;
874                 e->next = samep;
875                 samep = e;
876                 e = next;
877         }
878         /*
879          * As we don't know how much of a common stretch after this
880          * diff will occur, the currently blamed parts are all that we
881          * can assign to the parent for now.
882          */
883
884         if (samep) {
885                 **dstq = reverse_blame(samep, **dstq);
886                 *dstq = &samep->next;
887         }
888         /*
889          * Prepend the split off portions: everything after e starts
890          * after the blameable portion.
891          */
892         e = reverse_blame(diffp, e);
893
894         /*
895          * Now retain records on the target while parts are different
896          * from the parent.
897          */
898         samep = NULL;
899         diffp = NULL;
900         while (e && e->s_lno < same) {
901                 struct blame_entry *next = e->next;
902
903                 /*
904                  * If current record extends into sameness, need to split.
905                  */
906                 if (e->s_lno + e->num_lines > same) {
907                         /*
908                          * Move second half to a new record to be
909                          * processed by later chunks
910                          */
911                         int len = same - e->s_lno;
912                         struct blame_entry *n = xcalloc(1, sizeof (struct blame_entry));
913                         n->suspect = blame_origin_incref(e->suspect);
914                         n->lno = e->lno + len;
915                         n->s_lno = e->s_lno + len;
916                         n->num_lines = e->num_lines - len;
917                         e->num_lines = len;
918                         e->score = 0;
919                         /* Push new record to samep */
920                         n->next = samep;
921                         samep = n;
922                 }
923                 e->next = diffp;
924                 diffp = e;
925                 e = next;
926         }
927         **srcq = reverse_blame(diffp, reverse_blame(samep, e));
928         /* Move across elements that are in the unblamable portion */
929         if (diffp)
930                 *srcq = &diffp->next;
931 }
932
933 struct blame_chunk_cb_data {
934         struct blame_origin *parent;
935         long offset;
936         struct blame_entry **dstq;
937         struct blame_entry **srcq;
938 };
939
940 /* diff chunks are from parent to target */
941 static int blame_chunk_cb(long start_a, long count_a,
942                           long start_b, long count_b, void *data)
943 {
944         struct blame_chunk_cb_data *d = data;
945         if (start_a - start_b != d->offset)
946                 die("internal error in blame::blame_chunk_cb");
947         blame_chunk(&d->dstq, &d->srcq, start_b, start_a - start_b,
948                     start_b + count_b, d->parent);
949         d->offset = start_a + count_a - (start_b + count_b);
950         return 0;
951 }
952
953 /*
954  * We are looking at the origin 'target' and aiming to pass blame
955  * for the lines it is suspected to its parent.  Run diff to find
956  * which lines came from parent and pass blame for them.
957  */
958 static void pass_blame_to_parent(struct blame_scoreboard *sb,
959                                  struct blame_origin *target,
960                                  struct blame_origin *parent)
961 {
962         mmfile_t file_p, file_o;
963         struct blame_chunk_cb_data d;
964         struct blame_entry *newdest = NULL;
965
966         if (!target->suspects)
967                 return; /* nothing remains for this target */
968
969         d.parent = parent;
970         d.offset = 0;
971         d.dstq = &newdest; d.srcq = &target->suspects;
972
973         fill_origin_blob(&sb->revs->diffopt, parent, &file_p, &sb->num_read_blob);
974         fill_origin_blob(&sb->revs->diffopt, target, &file_o, &sb->num_read_blob);
975         sb->num_get_patch++;
976
977         if (diff_hunks(&file_p, &file_o, blame_chunk_cb, &d, sb->xdl_opts))
978                 die("unable to generate diff (%s -> %s)",
979                     oid_to_hex(&parent->commit->object.oid),
980                     oid_to_hex(&target->commit->object.oid));
981         /* The rest are the same as the parent */
982         blame_chunk(&d.dstq, &d.srcq, INT_MAX, d.offset, INT_MAX, parent);
983         *d.dstq = NULL;
984         queue_blames(sb, parent, newdest);
985
986         return;
987 }
988
989 /*
990  * The lines in blame_entry after splitting blames many times can become
991  * very small and trivial, and at some point it becomes pointless to
992  * blame the parents.  E.g. "\t\t}\n\t}\n\n" appears everywhere in any
993  * ordinary C program, and it is not worth to say it was copied from
994  * totally unrelated file in the parent.
995  *
996  * Compute how trivial the lines in the blame_entry are.
997  */
998 unsigned blame_entry_score(struct blame_scoreboard *sb, struct blame_entry *e)
999 {
1000         unsigned score;
1001         const char *cp, *ep;
1002
1003         if (e->score)
1004                 return e->score;
1005
1006         score = 1;
1007         cp = blame_nth_line(sb, e->lno);
1008         ep = blame_nth_line(sb, e->lno + e->num_lines);
1009         while (cp < ep) {
1010                 unsigned ch = *((unsigned char *)cp);
1011                 if (isalnum(ch))
1012                         score++;
1013                 cp++;
1014         }
1015         e->score = score;
1016         return score;
1017 }
1018
1019 /*
1020  * best_so_far[] and potential[] are both a split of an existing blame_entry
1021  * that passes blame to the parent.  Maintain best_so_far the best split so
1022  * far, by comparing potential and best_so_far and copying potential into
1023  * bst_so_far as needed.
1024  */
1025 static void copy_split_if_better(struct blame_scoreboard *sb,
1026                                  struct blame_entry *best_so_far,
1027                                  struct blame_entry *potential)
1028 {
1029         int i;
1030
1031         if (!potential[1].suspect)
1032                 return;
1033         if (best_so_far[1].suspect) {
1034                 if (blame_entry_score(sb, &potential[1]) <
1035                     blame_entry_score(sb, &best_so_far[1]))
1036                         return;
1037         }
1038
1039         for (i = 0; i < 3; i++)
1040                 blame_origin_incref(potential[i].suspect);
1041         decref_split(best_so_far);
1042         memcpy(best_so_far, potential, sizeof(struct blame_entry[3]));
1043 }
1044
1045 /*
1046  * We are looking at a part of the final image represented by
1047  * ent (tlno and same are offset by ent->s_lno).
1048  * tlno is where we are looking at in the final image.
1049  * up to (but not including) same match preimage.
1050  * plno is where we are looking at in the preimage.
1051  *
1052  * <-------------- final image ---------------------->
1053  *       <------ent------>
1054  *         ^tlno ^same
1055  *    <---------preimage----->
1056  *         ^plno
1057  *
1058  * All line numbers are 0-based.
1059  */
1060 static void handle_split(struct blame_scoreboard *sb,
1061                          struct blame_entry *ent,
1062                          int tlno, int plno, int same,
1063                          struct blame_origin *parent,
1064                          struct blame_entry *split)
1065 {
1066         if (ent->num_lines <= tlno)
1067                 return;
1068         if (tlno < same) {
1069                 struct blame_entry potential[3];
1070                 tlno += ent->s_lno;
1071                 same += ent->s_lno;
1072                 split_overlap(potential, ent, tlno, plno, same, parent);
1073                 copy_split_if_better(sb, split, potential);
1074                 decref_split(potential);
1075         }
1076 }
1077
1078 struct handle_split_cb_data {
1079         struct blame_scoreboard *sb;
1080         struct blame_entry *ent;
1081         struct blame_origin *parent;
1082         struct blame_entry *split;
1083         long plno;
1084         long tlno;
1085 };
1086
1087 static int handle_split_cb(long start_a, long count_a,
1088                            long start_b, long count_b, void *data)
1089 {
1090         struct handle_split_cb_data *d = data;
1091         handle_split(d->sb, d->ent, d->tlno, d->plno, start_b, d->parent,
1092                      d->split);
1093         d->plno = start_a + count_a;
1094         d->tlno = start_b + count_b;
1095         return 0;
1096 }
1097
1098 /*
1099  * Find the lines from parent that are the same as ent so that
1100  * we can pass blames to it.  file_p has the blob contents for
1101  * the parent.
1102  */
1103 static void find_copy_in_blob(struct blame_scoreboard *sb,
1104                               struct blame_entry *ent,
1105                               struct blame_origin *parent,
1106                               struct blame_entry *split,
1107                               mmfile_t *file_p)
1108 {
1109         const char *cp;
1110         mmfile_t file_o;
1111         struct handle_split_cb_data d;
1112
1113         memset(&d, 0, sizeof(d));
1114         d.sb = sb; d.ent = ent; d.parent = parent; d.split = split;
1115         /*
1116          * Prepare mmfile that contains only the lines in ent.
1117          */
1118         cp = blame_nth_line(sb, ent->lno);
1119         file_o.ptr = (char *) cp;
1120         file_o.size = blame_nth_line(sb, ent->lno + ent->num_lines) - cp;
1121
1122         /*
1123          * file_o is a part of final image we are annotating.
1124          * file_p partially may match that image.
1125          */
1126         memset(split, 0, sizeof(struct blame_entry [3]));
1127         if (diff_hunks(file_p, &file_o, handle_split_cb, &d, sb->xdl_opts))
1128                 die("unable to generate diff (%s)",
1129                     oid_to_hex(&parent->commit->object.oid));
1130         /* remainder, if any, all match the preimage */
1131         handle_split(sb, ent, d.tlno, d.plno, ent->num_lines, parent, split);
1132 }
1133
1134 /* Move all blame entries from list *source that have a score smaller
1135  * than score_min to the front of list *small.
1136  * Returns a pointer to the link pointing to the old head of the small list.
1137  */
1138
1139 static struct blame_entry **filter_small(struct blame_scoreboard *sb,
1140                                          struct blame_entry **small,
1141                                          struct blame_entry **source,
1142                                          unsigned score_min)
1143 {
1144         struct blame_entry *p = *source;
1145         struct blame_entry *oldsmall = *small;
1146         while (p) {
1147                 if (blame_entry_score(sb, p) <= score_min) {
1148                         *small = p;
1149                         small = &p->next;
1150                         p = *small;
1151                 } else {
1152                         *source = p;
1153                         source = &p->next;
1154                         p = *source;
1155                 }
1156         }
1157         *small = oldsmall;
1158         *source = NULL;
1159         return small;
1160 }
1161
1162 /*
1163  * See if lines currently target is suspected for can be attributed to
1164  * parent.
1165  */
1166 static void find_move_in_parent(struct blame_scoreboard *sb,
1167                                 struct blame_entry ***blamed,
1168                                 struct blame_entry **toosmall,
1169                                 struct blame_origin *target,
1170                                 struct blame_origin *parent)
1171 {
1172         struct blame_entry *e, split[3];
1173         struct blame_entry *unblamed = target->suspects;
1174         struct blame_entry *leftover = NULL;
1175         mmfile_t file_p;
1176
1177         if (!unblamed)
1178                 return; /* nothing remains for this target */
1179
1180         fill_origin_blob(&sb->revs->diffopt, parent, &file_p, &sb->num_read_blob);
1181         if (!file_p.ptr)
1182                 return;
1183
1184         /* At each iteration, unblamed has a NULL-terminated list of
1185          * entries that have not yet been tested for blame.  leftover
1186          * contains the reversed list of entries that have been tested
1187          * without being assignable to the parent.
1188          */
1189         do {
1190                 struct blame_entry **unblamedtail = &unblamed;
1191                 struct blame_entry *next;
1192                 for (e = unblamed; e; e = next) {
1193                         next = e->next;
1194                         find_copy_in_blob(sb, e, parent, split, &file_p);
1195                         if (split[1].suspect &&
1196                             sb->move_score < blame_entry_score(sb, &split[1])) {
1197                                 split_blame(blamed, &unblamedtail, split, e);
1198                         } else {
1199                                 e->next = leftover;
1200                                 leftover = e;
1201                         }
1202                         decref_split(split);
1203                 }
1204                 *unblamedtail = NULL;
1205                 toosmall = filter_small(sb, toosmall, &unblamed, sb->move_score);
1206         } while (unblamed);
1207         target->suspects = reverse_blame(leftover, NULL);
1208 }
1209
1210 struct blame_list {
1211         struct blame_entry *ent;
1212         struct blame_entry split[3];
1213 };
1214
1215 /*
1216  * Count the number of entries the target is suspected for,
1217  * and prepare a list of entry and the best split.
1218  */
1219 static struct blame_list *setup_blame_list(struct blame_entry *unblamed,
1220                                            int *num_ents_p)
1221 {
1222         struct blame_entry *e;
1223         int num_ents, i;
1224         struct blame_list *blame_list = NULL;
1225
1226         for (e = unblamed, num_ents = 0; e; e = e->next)
1227                 num_ents++;
1228         if (num_ents) {
1229                 blame_list = xcalloc(num_ents, sizeof(struct blame_list));
1230                 for (e = unblamed, i = 0; e; e = e->next)
1231                         blame_list[i++].ent = e;
1232         }
1233         *num_ents_p = num_ents;
1234         return blame_list;
1235 }
1236
1237 /*
1238  * For lines target is suspected for, see if we can find code movement
1239  * across file boundary from the parent commit.  porigin is the path
1240  * in the parent we already tried.
1241  */
1242 static void find_copy_in_parent(struct blame_scoreboard *sb,
1243                                 struct blame_entry ***blamed,
1244                                 struct blame_entry **toosmall,
1245                                 struct blame_origin *target,
1246                                 struct commit *parent,
1247                                 struct blame_origin *porigin,
1248                                 int opt)
1249 {
1250         struct diff_options diff_opts;
1251         int i, j;
1252         struct blame_list *blame_list;
1253         int num_ents;
1254         struct blame_entry *unblamed = target->suspects;
1255         struct blame_entry *leftover = NULL;
1256
1257         if (!unblamed)
1258                 return; /* nothing remains for this target */
1259
1260         diff_setup(&diff_opts);
1261         diff_opts.flags.recursive = 1;
1262         diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;
1263
1264         diff_setup_done(&diff_opts);
1265
1266         /* Try "find copies harder" on new path if requested;
1267          * we do not want to use diffcore_rename() actually to
1268          * match things up; find_copies_harder is set only to
1269          * force diff_tree_oid() to feed all filepairs to diff_queue,
1270          * and this code needs to be after diff_setup_done(), which
1271          * usually makes find-copies-harder imply copy detection.
1272          */
1273         if ((opt & PICKAXE_BLAME_COPY_HARDEST)
1274             || ((opt & PICKAXE_BLAME_COPY_HARDER)
1275                 && (!porigin || strcmp(target->path, porigin->path))))
1276                 diff_opts.flags.find_copies_harder = 1;
1277
1278         if (is_null_oid(&target->commit->object.oid))
1279                 do_diff_cache(get_commit_tree_oid(parent), &diff_opts);
1280         else
1281                 diff_tree_oid(get_commit_tree_oid(parent),
1282                               get_commit_tree_oid(target->commit),
1283                               "", &diff_opts);
1284
1285         if (!diff_opts.flags.find_copies_harder)
1286                 diffcore_std(&diff_opts);
1287
1288         do {
1289                 struct blame_entry **unblamedtail = &unblamed;
1290                 blame_list = setup_blame_list(unblamed, &num_ents);
1291
1292                 for (i = 0; i < diff_queued_diff.nr; i++) {
1293                         struct diff_filepair *p = diff_queued_diff.queue[i];
1294                         struct blame_origin *norigin;
1295                         mmfile_t file_p;
1296                         struct blame_entry potential[3];
1297
1298                         if (!DIFF_FILE_VALID(p->one))
1299                                 continue; /* does not exist in parent */
1300                         if (S_ISGITLINK(p->one->mode))
1301                                 continue; /* ignore git links */
1302                         if (porigin && !strcmp(p->one->path, porigin->path))
1303                                 /* find_move already dealt with this path */
1304                                 continue;
1305
1306                         norigin = get_origin(parent, p->one->path);
1307                         oidcpy(&norigin->blob_oid, &p->one->oid);
1308                         norigin->mode = p->one->mode;
1309                         fill_origin_blob(&sb->revs->diffopt, norigin, &file_p, &sb->num_read_blob);
1310                         if (!file_p.ptr)
1311                                 continue;
1312
1313                         for (j = 0; j < num_ents; j++) {
1314                                 find_copy_in_blob(sb, blame_list[j].ent,
1315                                                   norigin, potential, &file_p);
1316                                 copy_split_if_better(sb, blame_list[j].split,
1317                                                      potential);
1318                                 decref_split(potential);
1319                         }
1320                         blame_origin_decref(norigin);
1321                 }
1322
1323                 for (j = 0; j < num_ents; j++) {
1324                         struct blame_entry *split = blame_list[j].split;
1325                         if (split[1].suspect &&
1326                             sb->copy_score < blame_entry_score(sb, &split[1])) {
1327                                 split_blame(blamed, &unblamedtail, split,
1328                                             blame_list[j].ent);
1329                         } else {
1330                                 blame_list[j].ent->next = leftover;
1331                                 leftover = blame_list[j].ent;
1332                         }
1333                         decref_split(split);
1334                 }
1335                 free(blame_list);
1336                 *unblamedtail = NULL;
1337                 toosmall = filter_small(sb, toosmall, &unblamed, sb->copy_score);
1338         } while (unblamed);
1339         target->suspects = reverse_blame(leftover, NULL);
1340         diff_flush(&diff_opts);
1341         clear_pathspec(&diff_opts.pathspec);
1342 }
1343
1344 /*
1345  * The blobs of origin and porigin exactly match, so everything
1346  * origin is suspected for can be blamed on the parent.
1347  */
1348 static void pass_whole_blame(struct blame_scoreboard *sb,
1349                              struct blame_origin *origin, struct blame_origin *porigin)
1350 {
1351         struct blame_entry *e, *suspects;
1352
1353         if (!porigin->file.ptr && origin->file.ptr) {
1354                 /* Steal its file */
1355                 porigin->file = origin->file;
1356                 origin->file.ptr = NULL;
1357         }
1358         suspects = origin->suspects;
1359         origin->suspects = NULL;
1360         for (e = suspects; e; e = e->next) {
1361                 blame_origin_incref(porigin);
1362                 blame_origin_decref(e->suspect);
1363                 e->suspect = porigin;
1364         }
1365         queue_blames(sb, porigin, suspects);
1366 }
1367
1368 /*
1369  * We pass blame from the current commit to its parents.  We keep saying
1370  * "parent" (and "porigin"), but what we mean is to find scapegoat to
1371  * exonerate ourselves.
1372  */
1373 static struct commit_list *first_scapegoat(struct rev_info *revs, struct commit *commit,
1374                                         int reverse)
1375 {
1376         if (!reverse) {
1377                 if (revs->first_parent_only &&
1378                     commit->parents &&
1379                     commit->parents->next) {
1380                         free_commit_list(commit->parents->next);
1381                         commit->parents->next = NULL;
1382                 }
1383                 return commit->parents;
1384         }
1385         return lookup_decoration(&revs->children, &commit->object);
1386 }
1387
1388 static int num_scapegoats(struct rev_info *revs, struct commit *commit, int reverse)
1389 {
1390         struct commit_list *l = first_scapegoat(revs, commit, reverse);
1391         return commit_list_count(l);
1392 }
1393
1394 /* Distribute collected unsorted blames to the respected sorted lists
1395  * in the various origins.
1396  */
1397 static void distribute_blame(struct blame_scoreboard *sb, struct blame_entry *blamed)
1398 {
1399         blamed = llist_mergesort(blamed, get_next_blame, set_next_blame,
1400                                  compare_blame_suspect);
1401         while (blamed)
1402         {
1403                 struct blame_origin *porigin = blamed->suspect;
1404                 struct blame_entry *suspects = NULL;
1405                 do {
1406                         struct blame_entry *next = blamed->next;
1407                         blamed->next = suspects;
1408                         suspects = blamed;
1409                         blamed = next;
1410                 } while (blamed && blamed->suspect == porigin);
1411                 suspects = reverse_blame(suspects, NULL);
1412                 queue_blames(sb, porigin, suspects);
1413         }
1414 }
1415
1416 #define MAXSG 16
1417
1418 static void pass_blame(struct blame_scoreboard *sb, struct blame_origin *origin, int opt)
1419 {
1420         struct rev_info *revs = sb->revs;
1421         int i, pass, num_sg;
1422         struct commit *commit = origin->commit;
1423         struct commit_list *sg;
1424         struct blame_origin *sg_buf[MAXSG];
1425         struct blame_origin *porigin, **sg_origin = sg_buf;
1426         struct blame_entry *toosmall = NULL;
1427         struct blame_entry *blames, **blametail = &blames;
1428
1429         num_sg = num_scapegoats(revs, commit, sb->reverse);
1430         if (!num_sg)
1431                 goto finish;
1432         else if (num_sg < ARRAY_SIZE(sg_buf))
1433                 memset(sg_buf, 0, sizeof(sg_buf));
1434         else
1435                 sg_origin = xcalloc(num_sg, sizeof(*sg_origin));
1436
1437         /*
1438          * The first pass looks for unrenamed path to optimize for
1439          * common cases, then we look for renames in the second pass.
1440          */
1441         for (pass = 0; pass < 2 - sb->no_whole_file_rename; pass++) {
1442                 struct blame_origin *(*find)(struct commit *, struct blame_origin *);
1443                 find = pass ? find_rename : find_origin;
1444
1445                 for (i = 0, sg = first_scapegoat(revs, commit, sb->reverse);
1446                      i < num_sg && sg;
1447                      sg = sg->next, i++) {
1448                         struct commit *p = sg->item;
1449                         int j, same;
1450
1451                         if (sg_origin[i])
1452                                 continue;
1453                         if (parse_commit(p))
1454                                 continue;
1455                         porigin = find(p, origin);
1456                         if (!porigin)
1457                                 continue;
1458                         if (!oidcmp(&porigin->blob_oid, &origin->blob_oid)) {
1459                                 pass_whole_blame(sb, origin, porigin);
1460                                 blame_origin_decref(porigin);
1461                                 goto finish;
1462                         }
1463                         for (j = same = 0; j < i; j++)
1464                                 if (sg_origin[j] &&
1465                                     !oidcmp(&sg_origin[j]->blob_oid, &porigin->blob_oid)) {
1466                                         same = 1;
1467                                         break;
1468                                 }
1469                         if (!same)
1470                                 sg_origin[i] = porigin;
1471                         else
1472                                 blame_origin_decref(porigin);
1473                 }
1474         }
1475
1476         sb->num_commits++;
1477         for (i = 0, sg = first_scapegoat(revs, commit, sb->reverse);
1478              i < num_sg && sg;
1479              sg = sg->next, i++) {
1480                 struct blame_origin *porigin = sg_origin[i];
1481                 if (!porigin)
1482                         continue;
1483                 if (!origin->previous) {
1484                         blame_origin_incref(porigin);
1485                         origin->previous = porigin;
1486                 }
1487                 pass_blame_to_parent(sb, origin, porigin);
1488                 if (!origin->suspects)
1489                         goto finish;
1490         }
1491
1492         /*
1493          * Optionally find moves in parents' files.
1494          */
1495         if (opt & PICKAXE_BLAME_MOVE) {
1496                 filter_small(sb, &toosmall, &origin->suspects, sb->move_score);
1497                 if (origin->suspects) {
1498                         for (i = 0, sg = first_scapegoat(revs, commit, sb->reverse);
1499                              i < num_sg && sg;
1500                              sg = sg->next, i++) {
1501                                 struct blame_origin *porigin = sg_origin[i];
1502                                 if (!porigin)
1503                                         continue;
1504                                 find_move_in_parent(sb, &blametail, &toosmall, origin, porigin);
1505                                 if (!origin->suspects)
1506                                         break;
1507                         }
1508                 }
1509         }
1510
1511         /*
1512          * Optionally find copies from parents' files.
1513          */
1514         if (opt & PICKAXE_BLAME_COPY) {
1515                 if (sb->copy_score > sb->move_score)
1516                         filter_small(sb, &toosmall, &origin->suspects, sb->copy_score);
1517                 else if (sb->copy_score < sb->move_score) {
1518                         origin->suspects = blame_merge(origin->suspects, toosmall);
1519                         toosmall = NULL;
1520                         filter_small(sb, &toosmall, &origin->suspects, sb->copy_score);
1521                 }
1522                 if (!origin->suspects)
1523                         goto finish;
1524
1525                 for (i = 0, sg = first_scapegoat(revs, commit, sb->reverse);
1526                      i < num_sg && sg;
1527                      sg = sg->next, i++) {
1528                         struct blame_origin *porigin = sg_origin[i];
1529                         find_copy_in_parent(sb, &blametail, &toosmall,
1530                                             origin, sg->item, porigin, opt);
1531                         if (!origin->suspects)
1532                                 goto finish;
1533                 }
1534         }
1535
1536 finish:
1537         *blametail = NULL;
1538         distribute_blame(sb, blames);
1539         /*
1540          * prepend toosmall to origin->suspects
1541          *
1542          * There is no point in sorting: this ends up on a big
1543          * unsorted list in the caller anyway.
1544          */
1545         if (toosmall) {
1546                 struct blame_entry **tail = &toosmall;
1547                 while (*tail)
1548                         tail = &(*tail)->next;
1549                 *tail = origin->suspects;
1550                 origin->suspects = toosmall;
1551         }
1552         for (i = 0; i < num_sg; i++) {
1553                 if (sg_origin[i]) {
1554                         drop_origin_blob(sg_origin[i]);
1555                         blame_origin_decref(sg_origin[i]);
1556                 }
1557         }
1558         drop_origin_blob(origin);
1559         if (sg_buf != sg_origin)
1560                 free(sg_origin);
1561 }
1562
1563 /*
1564  * The main loop -- while we have blobs with lines whose true origin
1565  * is still unknown, pick one blob, and allow its lines to pass blames
1566  * to its parents. */
1567 void assign_blame(struct blame_scoreboard *sb, int opt)
1568 {
1569         struct rev_info *revs = sb->revs;
1570         struct commit *commit = prio_queue_get(&sb->commits);
1571
1572         while (commit) {
1573                 struct blame_entry *ent;
1574                 struct blame_origin *suspect = get_blame_suspects(commit);
1575
1576                 /* find one suspect to break down */
1577                 while (suspect && !suspect->suspects)
1578                         suspect = suspect->next;
1579
1580                 if (!suspect) {
1581                         commit = prio_queue_get(&sb->commits);
1582                         continue;
1583                 }
1584
1585                 assert(commit == suspect->commit);
1586
1587                 /*
1588                  * We will use this suspect later in the loop,
1589                  * so hold onto it in the meantime.
1590                  */
1591                 blame_origin_incref(suspect);
1592                 parse_commit(commit);
1593                 if (sb->reverse ||
1594                     (!(commit->object.flags & UNINTERESTING) &&
1595                      !(revs->max_age != -1 && commit->date < revs->max_age)))
1596                         pass_blame(sb, suspect, opt);
1597                 else {
1598                         commit->object.flags |= UNINTERESTING;
1599                         if (commit->object.parsed)
1600                                 mark_parents_uninteresting(commit);
1601                 }
1602                 /* treat root commit as boundary */
1603                 if (!commit->parents && !sb->show_root)
1604                         commit->object.flags |= UNINTERESTING;
1605
1606                 /* Take responsibility for the remaining entries */
1607                 ent = suspect->suspects;
1608                 if (ent) {
1609                         suspect->guilty = 1;
1610                         for (;;) {
1611                                 struct blame_entry *next = ent->next;
1612                                 if (sb->found_guilty_entry)
1613                                         sb->found_guilty_entry(ent, sb->found_guilty_entry_data);
1614                                 if (next) {
1615                                         ent = next;
1616                                         continue;
1617                                 }
1618                                 ent->next = sb->ent;
1619                                 sb->ent = suspect->suspects;
1620                                 suspect->suspects = NULL;
1621                                 break;
1622                         }
1623                 }
1624                 blame_origin_decref(suspect);
1625
1626                 if (sb->debug) /* sanity */
1627                         sanity_check_refcnt(sb);
1628         }
1629 }
1630
1631 static const char *get_next_line(const char *start, const char *end)
1632 {
1633         const char *nl = memchr(start, '\n', end - start);
1634         return nl ? nl + 1 : end;
1635 }
1636
1637 /*
1638  * To allow quick access to the contents of nth line in the
1639  * final image, prepare an index in the scoreboard.
1640  */
1641 static int prepare_lines(struct blame_scoreboard *sb)
1642 {
1643         const char *buf = sb->final_buf;
1644         unsigned long len = sb->final_buf_size;
1645         const char *end = buf + len;
1646         const char *p;
1647         int *lineno;
1648         int num = 0;
1649
1650         for (p = buf; p < end; p = get_next_line(p, end))
1651                 num++;
1652
1653         ALLOC_ARRAY(sb->lineno, num + 1);
1654         lineno = sb->lineno;
1655
1656         for (p = buf; p < end; p = get_next_line(p, end))
1657                 *lineno++ = p - buf;
1658
1659         *lineno = len;
1660
1661         sb->num_lines = num;
1662         return sb->num_lines;
1663 }
1664
1665 static struct commit *find_single_final(struct rev_info *revs,
1666                                         const char **name_p)
1667 {
1668         int i;
1669         struct commit *found = NULL;
1670         const char *name = NULL;
1671
1672         for (i = 0; i < revs->pending.nr; i++) {
1673                 struct object *obj = revs->pending.objects[i].item;
1674                 if (obj->flags & UNINTERESTING)
1675                         continue;
1676                 obj = deref_tag(the_repository, obj, NULL, 0);
1677                 if (obj->type != OBJ_COMMIT)
1678                         die("Non commit %s?", revs->pending.objects[i].name);
1679                 if (found)
1680                         die("More than one commit to dig from %s and %s?",
1681                             revs->pending.objects[i].name, name);
1682                 found = (struct commit *)obj;
1683                 name = revs->pending.objects[i].name;
1684         }
1685         if (name_p)
1686                 *name_p = xstrdup_or_null(name);
1687         return found;
1688 }
1689
1690 static struct commit *dwim_reverse_initial(struct rev_info *revs,
1691                                            const char **name_p)
1692 {
1693         /*
1694          * DWIM "git blame --reverse ONE -- PATH" as
1695          * "git blame --reverse ONE..HEAD -- PATH" but only do so
1696          * when it makes sense.
1697          */
1698         struct object *obj;
1699         struct commit *head_commit;
1700         struct object_id head_oid;
1701
1702         if (revs->pending.nr != 1)
1703                 return NULL;
1704
1705         /* Is that sole rev a committish? */
1706         obj = revs->pending.objects[0].item;
1707         obj = deref_tag(the_repository, obj, NULL, 0);
1708         if (obj->type != OBJ_COMMIT)
1709                 return NULL;
1710
1711         /* Do we have HEAD? */
1712         if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, &head_oid, NULL))
1713                 return NULL;
1714         head_commit = lookup_commit_reference_gently(the_repository,
1715                                                      &head_oid, 1);
1716         if (!head_commit)
1717                 return NULL;
1718
1719         /* Turn "ONE" into "ONE..HEAD" then */
1720         obj->flags |= UNINTERESTING;
1721         add_pending_object(revs, &head_commit->object, "HEAD");
1722
1723         if (name_p)
1724                 *name_p = revs->pending.objects[0].name;
1725         return (struct commit *)obj;
1726 }
1727
1728 static struct commit *find_single_initial(struct rev_info *revs,
1729                                           const char **name_p)
1730 {
1731         int i;
1732         struct commit *found = NULL;
1733         const char *name = NULL;
1734
1735         /*
1736          * There must be one and only one negative commit, and it must be
1737          * the boundary.
1738          */
1739         for (i = 0; i < revs->pending.nr; i++) {
1740                 struct object *obj = revs->pending.objects[i].item;
1741                 if (!(obj->flags & UNINTERESTING))
1742                         continue;
1743                 obj = deref_tag(the_repository, obj, NULL, 0);
1744                 if (obj->type != OBJ_COMMIT)
1745                         die("Non commit %s?", revs->pending.objects[i].name);
1746                 if (found)
1747                         die("More than one commit to dig up from, %s and %s?",
1748                             revs->pending.objects[i].name, name);
1749                 found = (struct commit *) obj;
1750                 name = revs->pending.objects[i].name;
1751         }
1752
1753         if (!name)
1754                 found = dwim_reverse_initial(revs, &name);
1755         if (!name)
1756                 die("No commit to dig up from?");
1757
1758         if (name_p)
1759                 *name_p = xstrdup(name);
1760         return found;
1761 }
1762
1763 void init_scoreboard(struct blame_scoreboard *sb)
1764 {
1765         memset(sb, 0, sizeof(struct blame_scoreboard));
1766         sb->move_score = BLAME_DEFAULT_MOVE_SCORE;
1767         sb->copy_score = BLAME_DEFAULT_COPY_SCORE;
1768 }
1769
1770 void setup_scoreboard(struct blame_scoreboard *sb, const char *path, struct blame_origin **orig)
1771 {
1772         const char *final_commit_name = NULL;
1773         struct blame_origin *o;
1774         struct commit *final_commit = NULL;
1775         enum object_type type;
1776
1777         init_blame_suspects(&blame_suspects);
1778
1779         if (sb->reverse && sb->contents_from)
1780                 die(_("--contents and --reverse do not blend well."));
1781
1782         if (!sb->reverse) {
1783                 sb->final = find_single_final(sb->revs, &final_commit_name);
1784                 sb->commits.compare = compare_commits_by_commit_date;
1785         } else {
1786                 sb->final = find_single_initial(sb->revs, &final_commit_name);
1787                 sb->commits.compare = compare_commits_by_reverse_commit_date;
1788         }
1789
1790         if (sb->final && sb->contents_from)
1791                 die(_("cannot use --contents with final commit object name"));
1792
1793         if (sb->reverse && sb->revs->first_parent_only)
1794                 sb->revs->children.name = NULL;
1795
1796         if (!sb->final) {
1797                 /*
1798                  * "--not A B -- path" without anything positive;
1799                  * do not default to HEAD, but use the working tree
1800                  * or "--contents".
1801                  */
1802                 setup_work_tree();
1803                 sb->final = fake_working_tree_commit(&sb->revs->diffopt,
1804                                                      path, sb->contents_from);
1805                 add_pending_object(sb->revs, &(sb->final->object), ":");
1806         }
1807
1808         if (sb->reverse && sb->revs->first_parent_only) {
1809                 final_commit = find_single_final(sb->revs, NULL);
1810                 if (!final_commit)
1811                         die(_("--reverse and --first-parent together require specified latest commit"));
1812         }
1813
1814         /*
1815          * If we have bottom, this will mark the ancestors of the
1816          * bottom commits we would reach while traversing as
1817          * uninteresting.
1818          */
1819         if (prepare_revision_walk(sb->revs))
1820                 die(_("revision walk setup failed"));
1821
1822         if (sb->reverse && sb->revs->first_parent_only) {
1823                 struct commit *c = final_commit;
1824
1825                 sb->revs->children.name = "children";
1826                 while (c->parents &&
1827                        oidcmp(&c->object.oid, &sb->final->object.oid)) {
1828                         struct commit_list *l = xcalloc(1, sizeof(*l));
1829
1830                         l->item = c;
1831                         if (add_decoration(&sb->revs->children,
1832                                            &c->parents->item->object, l))
1833                                 BUG("not unique item in first-parent chain");
1834                         c = c->parents->item;
1835                 }
1836
1837                 if (oidcmp(&c->object.oid, &sb->final->object.oid))
1838                         die(_("--reverse --first-parent together require range along first-parent chain"));
1839         }
1840
1841         if (is_null_oid(&sb->final->object.oid)) {
1842                 o = get_blame_suspects(sb->final);
1843                 sb->final_buf = xmemdupz(o->file.ptr, o->file.size);
1844                 sb->final_buf_size = o->file.size;
1845         }
1846         else {
1847                 o = get_origin(sb->final, path);
1848                 if (fill_blob_sha1_and_mode(o))
1849                         die(_("no such path %s in %s"), path, final_commit_name);
1850
1851                 if (sb->revs->diffopt.flags.allow_textconv &&
1852                     textconv_object(path, o->mode, &o->blob_oid, 1, (char **) &sb->final_buf,
1853                                     &sb->final_buf_size))
1854                         ;
1855                 else
1856                         sb->final_buf = read_object_file(&o->blob_oid, &type,
1857                                                          &sb->final_buf_size);
1858
1859                 if (!sb->final_buf)
1860                         die(_("cannot read blob %s for path %s"),
1861                             oid_to_hex(&o->blob_oid),
1862                             path);
1863         }
1864         sb->num_read_blob++;
1865         prepare_lines(sb);
1866
1867         if (orig)
1868                 *orig = o;
1869
1870         free((char *)final_commit_name);
1871 }
1872
1873
1874
1875 struct blame_entry *blame_entry_prepend(struct blame_entry *head,
1876                                         long start, long end,
1877                                         struct blame_origin *o)
1878 {
1879         struct blame_entry *new_head = xcalloc(1, sizeof(struct blame_entry));
1880         new_head->lno = start;
1881         new_head->num_lines = end - start;
1882         new_head->suspect = o;
1883         new_head->s_lno = start;
1884         new_head->next = head;
1885         blame_origin_incref(o);
1886         return new_head;
1887 }