diff.c: remove the_index dependency in textconv() functions
[git.git] / blame.c
blob9d57c76baa0951a369e6af49b72b6520cddd4e86
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"
13 define_commit_slab(blame_suspects, struct blame_origin *);
14 static struct blame_suspects blame_suspects;
16 struct blame_origin *get_blame_suspects(struct commit *commit)
18 struct blame_origin **result;
20 result = blame_suspects_peek(&blame_suspects, commit);
22 return result ? *result : NULL;
25 static void set_blame_suspects(struct commit *commit, struct blame_origin *origin)
27 *blame_suspects_at(&blame_suspects, commit) = origin;
30 void blame_origin_decref(struct blame_origin *o)
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;
48 die("internal error in blame_origin_decref");
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.
58 static struct blame_origin *make_origin(struct commit *commit, const char *path)
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;
70 * Locate an existing origin or create a new one.
71 * This moves the origin to front position in the commit util list.
73 static struct blame_origin *get_origin(struct commit *commit, const char *path)
75 struct blame_origin *o, *l;
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);
85 return blame_origin_incref(o);
88 return make_origin(commit, path);
93 static void verify_working_tree_path(struct repository *r,
94 struct commit *work_tree, const char *path)
96 struct commit_list *parents;
97 int pos;
99 for (parents = work_tree->parents; parents; parents = parents->next) {
100 const struct object_id *commit_oid = &parents->item->object.oid;
101 struct object_id blob_oid;
102 unsigned mode;
104 if (!get_tree_entry(commit_oid, path, &blob_oid, &mode) &&
105 oid_object_info(r, &blob_oid, NULL) == OBJ_BLOB)
106 return;
109 pos = index_name_pos(r->index, path, strlen(path));
110 if (pos >= 0)
111 ; /* path is in the index */
112 else if (-1 - pos < r->index->cache_nr &&
113 !strcmp(r->index->cache[-1 - pos]->name, path))
114 ; /* path is in the index, unmerged */
115 else
116 die("no such path '%s' in HEAD", path);
119 static struct commit_list **append_parent(struct commit_list **tail, const struct object_id *oid)
121 struct commit *parent;
123 parent = lookup_commit_reference(the_repository, oid);
124 if (!parent)
125 die("no such commit %s", oid_to_hex(oid));
126 return &commit_list_insert(parent, tail)->next;
129 static void append_merge_parents(struct commit_list **tail)
131 int merge_head;
132 struct strbuf line = STRBUF_INIT;
134 merge_head = open(git_path_merge_head(the_repository), O_RDONLY);
135 if (merge_head < 0) {
136 if (errno == ENOENT)
137 return;
138 die("cannot open '%s' for reading",
139 git_path_merge_head(the_repository));
142 while (!strbuf_getwholeline_fd(&line, merge_head, '\n')) {
143 struct object_id oid;
144 if (line.len < GIT_SHA1_HEXSZ || get_oid_hex(line.buf, &oid))
145 die("unknown line in '%s': %s",
146 git_path_merge_head(the_repository), line.buf);
147 tail = append_parent(tail, &oid);
149 close(merge_head);
150 strbuf_release(&line);
154 * This isn't as simple as passing sb->buf and sb->len, because we
155 * want to transfer ownership of the buffer to the commit (so we
156 * must use detach).
158 static void set_commit_buffer_from_strbuf(struct commit *c, struct strbuf *sb)
160 size_t len;
161 void *buf = strbuf_detach(sb, &len);
162 set_commit_buffer(the_repository, c, buf, len);
166 * Prepare a dummy commit that represents the work tree (or staged) item.
167 * Note that annotating work tree item never works in the reverse.
169 static struct commit *fake_working_tree_commit(struct repository *r,
170 struct diff_options *opt,
171 const char *path,
172 const char *contents_from)
174 struct commit *commit;
175 struct blame_origin *origin;
176 struct commit_list **parent_tail, *parent;
177 struct object_id head_oid;
178 struct strbuf buf = STRBUF_INIT;
179 const char *ident;
180 time_t now;
181 int len;
182 struct cache_entry *ce;
183 unsigned mode;
184 struct strbuf msg = STRBUF_INIT;
186 read_index(r->index);
187 time(&now);
188 commit = alloc_commit_node(the_repository);
189 commit->object.parsed = 1;
190 commit->date = now;
191 parent_tail = &commit->parents;
193 if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, &head_oid, NULL))
194 die("no such ref: HEAD");
196 parent_tail = append_parent(parent_tail, &head_oid);
197 append_merge_parents(parent_tail);
198 verify_working_tree_path(r, commit, path);
200 origin = make_origin(commit, path);
202 ident = fmt_ident("Not Committed Yet", "not.committed.yet", NULL, 0);
203 strbuf_addstr(&msg, "tree 0000000000000000000000000000000000000000\n");
204 for (parent = commit->parents; parent; parent = parent->next)
205 strbuf_addf(&msg, "parent %s\n",
206 oid_to_hex(&parent->item->object.oid));
207 strbuf_addf(&msg,
208 "author %s\n"
209 "committer %s\n\n"
210 "Version of %s from %s\n",
211 ident, ident, path,
212 (!contents_from ? path :
213 (!strcmp(contents_from, "-") ? "standard input" : contents_from)));
214 set_commit_buffer_from_strbuf(commit, &msg);
216 if (!contents_from || strcmp("-", contents_from)) {
217 struct stat st;
218 const char *read_from;
219 char *buf_ptr;
220 unsigned long buf_len;
222 if (contents_from) {
223 if (stat(contents_from, &st) < 0)
224 die_errno("Cannot stat '%s'", contents_from);
225 read_from = contents_from;
227 else {
228 if (lstat(path, &st) < 0)
229 die_errno("Cannot lstat '%s'", path);
230 read_from = path;
232 mode = canon_mode(st.st_mode);
234 switch (st.st_mode & S_IFMT) {
235 case S_IFREG:
236 if (opt->flags.allow_textconv &&
237 textconv_object(r, read_from, mode, &null_oid, 0, &buf_ptr, &buf_len))
238 strbuf_attach(&buf, buf_ptr, buf_len, buf_len + 1);
239 else if (strbuf_read_file(&buf, read_from, st.st_size) != st.st_size)
240 die_errno("cannot open or read '%s'", read_from);
241 break;
242 case S_IFLNK:
243 if (strbuf_readlink(&buf, read_from, st.st_size) < 0)
244 die_errno("cannot readlink '%s'", read_from);
245 break;
246 default:
247 die("unsupported file type %s", read_from);
250 else {
251 /* Reading from stdin */
252 mode = 0;
253 if (strbuf_read(&buf, 0, 0) < 0)
254 die_errno("failed to read from stdin");
256 convert_to_git(r->index, path, buf.buf, buf.len, &buf, 0);
257 origin->file.ptr = buf.buf;
258 origin->file.size = buf.len;
259 pretend_object_file(buf.buf, buf.len, OBJ_BLOB, &origin->blob_oid);
262 * Read the current index, replace the path entry with
263 * origin->blob_sha1 without mucking with its mode or type
264 * bits; we are not going to write this index out -- we just
265 * want to run "diff-index --cached".
267 discard_index(r->index);
268 read_index(r->index);
270 len = strlen(path);
271 if (!mode) {
272 int pos = index_name_pos(r->index, path, len);
273 if (0 <= pos)
274 mode = r->index->cache[pos]->ce_mode;
275 else
276 /* Let's not bother reading from HEAD tree */
277 mode = S_IFREG | 0644;
279 ce = make_empty_cache_entry(r->index, len);
280 oidcpy(&ce->oid, &origin->blob_oid);
281 memcpy(ce->name, path, len);
282 ce->ce_flags = create_ce_flags(0);
283 ce->ce_namelen = len;
284 ce->ce_mode = create_ce_mode(mode);
285 add_index_entry(r->index, ce,
286 ADD_CACHE_OK_TO_ADD | ADD_CACHE_OK_TO_REPLACE);
288 cache_tree_invalidate_path(r->index, path);
290 return commit;
295 static int diff_hunks(mmfile_t *file_a, mmfile_t *file_b,
296 xdl_emit_hunk_consume_func_t hunk_func, void *cb_data, int xdl_opts)
298 xpparam_t xpp = {0};
299 xdemitconf_t xecfg = {0};
300 xdemitcb_t ecb = {NULL};
302 xpp.flags = xdl_opts;
303 xecfg.hunk_func = hunk_func;
304 ecb.priv = cb_data;
305 return xdi_diff(file_a, file_b, &xpp, &xecfg, &ecb);
309 * Given an origin, prepare mmfile_t structure to be used by the
310 * diff machinery
312 static void fill_origin_blob(struct diff_options *opt,
313 struct blame_origin *o, mmfile_t *file, int *num_read_blob)
315 if (!o->file.ptr) {
316 enum object_type type;
317 unsigned long file_size;
319 (*num_read_blob)++;
320 if (opt->flags.allow_textconv &&
321 textconv_object(opt->repo, o->path, o->mode,
322 &o->blob_oid, 1, &file->ptr, &file_size))
324 else
325 file->ptr = read_object_file(&o->blob_oid, &type,
326 &file_size);
327 file->size = file_size;
329 if (!file->ptr)
330 die("Cannot read blob %s for path %s",
331 oid_to_hex(&o->blob_oid),
332 o->path);
333 o->file = *file;
335 else
336 *file = o->file;
339 static void drop_origin_blob(struct blame_origin *o)
341 FREE_AND_NULL(o->file.ptr);
345 * Any merge of blames happens on lists of blames that arrived via
346 * different parents in a single suspect. In this case, we want to
347 * sort according to the suspect line numbers as opposed to the final
348 * image line numbers. The function body is somewhat longish because
349 * it avoids unnecessary writes.
352 static struct blame_entry *blame_merge(struct blame_entry *list1,
353 struct blame_entry *list2)
355 struct blame_entry *p1 = list1, *p2 = list2,
356 **tail = &list1;
358 if (!p1)
359 return p2;
360 if (!p2)
361 return p1;
363 if (p1->s_lno <= p2->s_lno) {
364 do {
365 tail = &p1->next;
366 if ((p1 = *tail) == NULL) {
367 *tail = p2;
368 return list1;
370 } while (p1->s_lno <= p2->s_lno);
372 for (;;) {
373 *tail = p2;
374 do {
375 tail = &p2->next;
376 if ((p2 = *tail) == NULL) {
377 *tail = p1;
378 return list1;
380 } while (p1->s_lno > p2->s_lno);
381 *tail = p1;
382 do {
383 tail = &p1->next;
384 if ((p1 = *tail) == NULL) {
385 *tail = p2;
386 return list1;
388 } while (p1->s_lno <= p2->s_lno);
392 static void *get_next_blame(const void *p)
394 return ((struct blame_entry *)p)->next;
397 static void set_next_blame(void *p1, void *p2)
399 ((struct blame_entry *)p1)->next = p2;
403 * Final image line numbers are all different, so we don't need a
404 * three-way comparison here.
407 static int compare_blame_final(const void *p1, const void *p2)
409 return ((struct blame_entry *)p1)->lno > ((struct blame_entry *)p2)->lno
410 ? 1 : -1;
413 static int compare_blame_suspect(const void *p1, const void *p2)
415 const struct blame_entry *s1 = p1, *s2 = p2;
417 * to allow for collating suspects, we sort according to the
418 * respective pointer value as the primary sorting criterion.
419 * The actual relation is pretty unimportant as long as it
420 * establishes a total order. Comparing as integers gives us
421 * that.
423 if (s1->suspect != s2->suspect)
424 return (intptr_t)s1->suspect > (intptr_t)s2->suspect ? 1 : -1;
425 if (s1->s_lno == s2->s_lno)
426 return 0;
427 return s1->s_lno > s2->s_lno ? 1 : -1;
430 void blame_sort_final(struct blame_scoreboard *sb)
432 sb->ent = llist_mergesort(sb->ent, get_next_blame, set_next_blame,
433 compare_blame_final);
436 static int compare_commits_by_reverse_commit_date(const void *a,
437 const void *b,
438 void *c)
440 return -compare_commits_by_commit_date(a, b, c);
444 * For debugging -- origin is refcounted, and this asserts that
445 * we do not underflow.
447 static void sanity_check_refcnt(struct blame_scoreboard *sb)
449 int baa = 0;
450 struct blame_entry *ent;
452 for (ent = sb->ent; ent; ent = ent->next) {
453 /* Nobody should have zero or negative refcnt */
454 if (ent->suspect->refcnt <= 0) {
455 fprintf(stderr, "%s in %s has negative refcnt %d\n",
456 ent->suspect->path,
457 oid_to_hex(&ent->suspect->commit->object.oid),
458 ent->suspect->refcnt);
459 baa = 1;
462 if (baa)
463 sb->on_sanity_fail(sb, baa);
467 * If two blame entries that are next to each other came from
468 * contiguous lines in the same origin (i.e. <commit, path> pair),
469 * merge them together.
471 void blame_coalesce(struct blame_scoreboard *sb)
473 struct blame_entry *ent, *next;
475 for (ent = sb->ent; ent && (next = ent->next); ent = next) {
476 if (ent->suspect == next->suspect &&
477 ent->s_lno + ent->num_lines == next->s_lno) {
478 ent->num_lines += next->num_lines;
479 ent->next = next->next;
480 blame_origin_decref(next->suspect);
481 free(next);
482 ent->score = 0;
483 next = ent; /* again */
487 if (sb->debug) /* sanity */
488 sanity_check_refcnt(sb);
492 * Merge the given sorted list of blames into a preexisting origin.
493 * If there were no previous blames to that commit, it is entered into
494 * the commit priority queue of the score board.
497 static void queue_blames(struct blame_scoreboard *sb, struct blame_origin *porigin,
498 struct blame_entry *sorted)
500 if (porigin->suspects)
501 porigin->suspects = blame_merge(porigin->suspects, sorted);
502 else {
503 struct blame_origin *o;
504 for (o = get_blame_suspects(porigin->commit); o; o = o->next) {
505 if (o->suspects) {
506 porigin->suspects = sorted;
507 return;
510 porigin->suspects = sorted;
511 prio_queue_put(&sb->commits, porigin->commit);
516 * Fill the blob_sha1 field of an origin if it hasn't, so that later
517 * call to fill_origin_blob() can use it to locate the data. blob_sha1
518 * for an origin is also used to pass the blame for the entire file to
519 * the parent to detect the case where a child's blob is identical to
520 * that of its parent's.
522 * This also fills origin->mode for corresponding tree path.
524 static int fill_blob_sha1_and_mode(struct repository *r,
525 struct blame_origin *origin)
527 if (!is_null_oid(&origin->blob_oid))
528 return 0;
529 if (get_tree_entry(&origin->commit->object.oid, origin->path, &origin->blob_oid, &origin->mode))
530 goto error_out;
531 if (oid_object_info(r, &origin->blob_oid, NULL) != OBJ_BLOB)
532 goto error_out;
533 return 0;
534 error_out:
535 oidclr(&origin->blob_oid);
536 origin->mode = S_IFINVALID;
537 return -1;
541 * We have an origin -- check if the same path exists in the
542 * parent and return an origin structure to represent it.
544 static struct blame_origin *find_origin(struct commit *parent,
545 struct blame_origin *origin)
547 struct blame_origin *porigin;
548 struct diff_options diff_opts;
549 const char *paths[2];
551 /* First check any existing origins */
552 for (porigin = get_blame_suspects(parent); porigin; porigin = porigin->next)
553 if (!strcmp(porigin->path, origin->path)) {
555 * The same path between origin and its parent
556 * without renaming -- the most common case.
558 return blame_origin_incref (porigin);
561 /* See if the origin->path is different between parent
562 * and origin first. Most of the time they are the
563 * same and diff-tree is fairly efficient about this.
565 diff_setup(&diff_opts);
566 diff_opts.flags.recursive = 1;
567 diff_opts.detect_rename = 0;
568 diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;
569 paths[0] = origin->path;
570 paths[1] = NULL;
572 parse_pathspec(&diff_opts.pathspec,
573 PATHSPEC_ALL_MAGIC & ~PATHSPEC_LITERAL,
574 PATHSPEC_LITERAL_PATH, "", paths);
575 diff_setup_done(&diff_opts);
577 if (is_null_oid(&origin->commit->object.oid))
578 do_diff_cache(get_commit_tree_oid(parent), &diff_opts);
579 else
580 diff_tree_oid(get_commit_tree_oid(parent),
581 get_commit_tree_oid(origin->commit),
582 "", &diff_opts);
583 diffcore_std(&diff_opts);
585 if (!diff_queued_diff.nr) {
586 /* The path is the same as parent */
587 porigin = get_origin(parent, origin->path);
588 oidcpy(&porigin->blob_oid, &origin->blob_oid);
589 porigin->mode = origin->mode;
590 } else {
592 * Since origin->path is a pathspec, if the parent
593 * commit had it as a directory, we will see a whole
594 * bunch of deletion of files in the directory that we
595 * do not care about.
597 int i;
598 struct diff_filepair *p = NULL;
599 for (i = 0; i < diff_queued_diff.nr; i++) {
600 const char *name;
601 p = diff_queued_diff.queue[i];
602 name = p->one->path ? p->one->path : p->two->path;
603 if (!strcmp(name, origin->path))
604 break;
606 if (!p)
607 die("internal error in blame::find_origin");
608 switch (p->status) {
609 default:
610 die("internal error in blame::find_origin (%c)",
611 p->status);
612 case 'M':
613 porigin = get_origin(parent, origin->path);
614 oidcpy(&porigin->blob_oid, &p->one->oid);
615 porigin->mode = p->one->mode;
616 break;
617 case 'A':
618 case 'T':
619 /* Did not exist in parent, or type changed */
620 break;
623 diff_flush(&diff_opts);
624 clear_pathspec(&diff_opts.pathspec);
625 return porigin;
629 * We have an origin -- find the path that corresponds to it in its
630 * parent and return an origin structure to represent it.
632 static struct blame_origin *find_rename(struct commit *parent,
633 struct blame_origin *origin)
635 struct blame_origin *porigin = NULL;
636 struct diff_options diff_opts;
637 int i;
639 diff_setup(&diff_opts);
640 diff_opts.flags.recursive = 1;
641 diff_opts.detect_rename = DIFF_DETECT_RENAME;
642 diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;
643 diff_opts.single_follow = origin->path;
644 diff_setup_done(&diff_opts);
646 if (is_null_oid(&origin->commit->object.oid))
647 do_diff_cache(get_commit_tree_oid(parent), &diff_opts);
648 else
649 diff_tree_oid(get_commit_tree_oid(parent),
650 get_commit_tree_oid(origin->commit),
651 "", &diff_opts);
652 diffcore_std(&diff_opts);
654 for (i = 0; i < diff_queued_diff.nr; i++) {
655 struct diff_filepair *p = diff_queued_diff.queue[i];
656 if ((p->status == 'R' || p->status == 'C') &&
657 !strcmp(p->two->path, origin->path)) {
658 porigin = get_origin(parent, p->one->path);
659 oidcpy(&porigin->blob_oid, &p->one->oid);
660 porigin->mode = p->one->mode;
661 break;
664 diff_flush(&diff_opts);
665 clear_pathspec(&diff_opts.pathspec);
666 return porigin;
670 * Append a new blame entry to a given output queue.
672 static void add_blame_entry(struct blame_entry ***queue,
673 const struct blame_entry *src)
675 struct blame_entry *e = xmalloc(sizeof(*e));
676 memcpy(e, src, sizeof(*e));
677 blame_origin_incref(e->suspect);
679 e->next = **queue;
680 **queue = e;
681 *queue = &e->next;
685 * src typically is on-stack; we want to copy the information in it to
686 * a malloced blame_entry that gets added to the given queue. The
687 * origin of dst loses a refcnt.
689 static void dup_entry(struct blame_entry ***queue,
690 struct blame_entry *dst, struct blame_entry *src)
692 blame_origin_incref(src->suspect);
693 blame_origin_decref(dst->suspect);
694 memcpy(dst, src, sizeof(*src));
695 dst->next = **queue;
696 **queue = dst;
697 *queue = &dst->next;
700 const char *blame_nth_line(struct blame_scoreboard *sb, long lno)
702 return sb->final_buf + sb->lineno[lno];
706 * It is known that lines between tlno to same came from parent, and e
707 * has an overlap with that range. it also is known that parent's
708 * line plno corresponds to e's line tlno.
710 * <---- e ----->
711 * <------>
712 * <------------>
713 * <------------>
714 * <------------------>
716 * Split e into potentially three parts; before this chunk, the chunk
717 * to be blamed for the parent, and after that portion.
719 static void split_overlap(struct blame_entry *split,
720 struct blame_entry *e,
721 int tlno, int plno, int same,
722 struct blame_origin *parent)
724 int chunk_end_lno;
725 memset(split, 0, sizeof(struct blame_entry [3]));
727 if (e->s_lno < tlno) {
728 /* there is a pre-chunk part not blamed on parent */
729 split[0].suspect = blame_origin_incref(e->suspect);
730 split[0].lno = e->lno;
731 split[0].s_lno = e->s_lno;
732 split[0].num_lines = tlno - e->s_lno;
733 split[1].lno = e->lno + tlno - e->s_lno;
734 split[1].s_lno = plno;
736 else {
737 split[1].lno = e->lno;
738 split[1].s_lno = plno + (e->s_lno - tlno);
741 if (same < e->s_lno + e->num_lines) {
742 /* there is a post-chunk part not blamed on parent */
743 split[2].suspect = blame_origin_incref(e->suspect);
744 split[2].lno = e->lno + (same - e->s_lno);
745 split[2].s_lno = e->s_lno + (same - e->s_lno);
746 split[2].num_lines = e->s_lno + e->num_lines - same;
747 chunk_end_lno = split[2].lno;
749 else
750 chunk_end_lno = e->lno + e->num_lines;
751 split[1].num_lines = chunk_end_lno - split[1].lno;
754 * if it turns out there is nothing to blame the parent for,
755 * forget about the splitting. !split[1].suspect signals this.
757 if (split[1].num_lines < 1)
758 return;
759 split[1].suspect = blame_origin_incref(parent);
763 * split_overlap() divided an existing blame e into up to three parts
764 * in split. Any assigned blame is moved to queue to
765 * reflect the split.
767 static void split_blame(struct blame_entry ***blamed,
768 struct blame_entry ***unblamed,
769 struct blame_entry *split,
770 struct blame_entry *e)
772 if (split[0].suspect && split[2].suspect) {
773 /* The first part (reuse storage for the existing entry e) */
774 dup_entry(unblamed, e, &split[0]);
776 /* The last part -- me */
777 add_blame_entry(unblamed, &split[2]);
779 /* ... and the middle part -- parent */
780 add_blame_entry(blamed, &split[1]);
782 else if (!split[0].suspect && !split[2].suspect)
784 * The parent covers the entire area; reuse storage for
785 * e and replace it with the parent.
787 dup_entry(blamed, e, &split[1]);
788 else if (split[0].suspect) {
789 /* me and then parent */
790 dup_entry(unblamed, e, &split[0]);
791 add_blame_entry(blamed, &split[1]);
793 else {
794 /* parent and then me */
795 dup_entry(blamed, e, &split[1]);
796 add_blame_entry(unblamed, &split[2]);
801 * After splitting the blame, the origins used by the
802 * on-stack blame_entry should lose one refcnt each.
804 static void decref_split(struct blame_entry *split)
806 int i;
808 for (i = 0; i < 3; i++)
809 blame_origin_decref(split[i].suspect);
813 * reverse_blame reverses the list given in head, appending tail.
814 * That allows us to build lists in reverse order, then reverse them
815 * afterwards. This can be faster than building the list in proper
816 * order right away. The reason is that building in proper order
817 * requires writing a link in the _previous_ element, while building
818 * in reverse order just requires placing the list head into the
819 * _current_ element.
822 static struct blame_entry *reverse_blame(struct blame_entry *head,
823 struct blame_entry *tail)
825 while (head) {
826 struct blame_entry *next = head->next;
827 head->next = tail;
828 tail = head;
829 head = next;
831 return tail;
835 * Process one hunk from the patch between the current suspect for
836 * blame_entry e and its parent. This first blames any unfinished
837 * entries before the chunk (which is where target and parent start
838 * differing) on the parent, and then splits blame entries at the
839 * start and at the end of the difference region. Since use of -M and
840 * -C options may lead to overlapping/duplicate source line number
841 * ranges, all we can rely on from sorting/merging is the order of the
842 * first suspect line number.
844 static void blame_chunk(struct blame_entry ***dstq, struct blame_entry ***srcq,
845 int tlno, int offset, int same,
846 struct blame_origin *parent)
848 struct blame_entry *e = **srcq;
849 struct blame_entry *samep = NULL, *diffp = NULL;
851 while (e && e->s_lno < tlno) {
852 struct blame_entry *next = e->next;
854 * current record starts before differing portion. If
855 * it reaches into it, we need to split it up and
856 * examine the second part separately.
858 if (e->s_lno + e->num_lines > tlno) {
859 /* Move second half to a new record */
860 int len = tlno - e->s_lno;
861 struct blame_entry *n = xcalloc(1, sizeof (struct blame_entry));
862 n->suspect = e->suspect;
863 n->lno = e->lno + len;
864 n->s_lno = e->s_lno + len;
865 n->num_lines = e->num_lines - len;
866 e->num_lines = len;
867 e->score = 0;
868 /* Push new record to diffp */
869 n->next = diffp;
870 diffp = n;
871 } else
872 blame_origin_decref(e->suspect);
873 /* Pass blame for everything before the differing
874 * chunk to the parent */
875 e->suspect = blame_origin_incref(parent);
876 e->s_lno += offset;
877 e->next = samep;
878 samep = e;
879 e = next;
882 * As we don't know how much of a common stretch after this
883 * diff will occur, the currently blamed parts are all that we
884 * can assign to the parent for now.
887 if (samep) {
888 **dstq = reverse_blame(samep, **dstq);
889 *dstq = &samep->next;
892 * Prepend the split off portions: everything after e starts
893 * after the blameable portion.
895 e = reverse_blame(diffp, e);
898 * Now retain records on the target while parts are different
899 * from the parent.
901 samep = NULL;
902 diffp = NULL;
903 while (e && e->s_lno < same) {
904 struct blame_entry *next = e->next;
907 * If current record extends into sameness, need to split.
909 if (e->s_lno + e->num_lines > same) {
911 * Move second half to a new record to be
912 * processed by later chunks
914 int len = same - e->s_lno;
915 struct blame_entry *n = xcalloc(1, sizeof (struct blame_entry));
916 n->suspect = blame_origin_incref(e->suspect);
917 n->lno = e->lno + len;
918 n->s_lno = e->s_lno + len;
919 n->num_lines = e->num_lines - len;
920 e->num_lines = len;
921 e->score = 0;
922 /* Push new record to samep */
923 n->next = samep;
924 samep = n;
926 e->next = diffp;
927 diffp = e;
928 e = next;
930 **srcq = reverse_blame(diffp, reverse_blame(samep, e));
931 /* Move across elements that are in the unblamable portion */
932 if (diffp)
933 *srcq = &diffp->next;
936 struct blame_chunk_cb_data {
937 struct blame_origin *parent;
938 long offset;
939 struct blame_entry **dstq;
940 struct blame_entry **srcq;
943 /* diff chunks are from parent to target */
944 static int blame_chunk_cb(long start_a, long count_a,
945 long start_b, long count_b, void *data)
947 struct blame_chunk_cb_data *d = data;
948 if (start_a - start_b != d->offset)
949 die("internal error in blame::blame_chunk_cb");
950 blame_chunk(&d->dstq, &d->srcq, start_b, start_a - start_b,
951 start_b + count_b, d->parent);
952 d->offset = start_a + count_a - (start_b + count_b);
953 return 0;
957 * We are looking at the origin 'target' and aiming to pass blame
958 * for the lines it is suspected to its parent. Run diff to find
959 * which lines came from parent and pass blame for them.
961 static void pass_blame_to_parent(struct blame_scoreboard *sb,
962 struct blame_origin *target,
963 struct blame_origin *parent)
965 mmfile_t file_p, file_o;
966 struct blame_chunk_cb_data d;
967 struct blame_entry *newdest = NULL;
969 if (!target->suspects)
970 return; /* nothing remains for this target */
972 d.parent = parent;
973 d.offset = 0;
974 d.dstq = &newdest; d.srcq = &target->suspects;
976 fill_origin_blob(&sb->revs->diffopt, parent, &file_p, &sb->num_read_blob);
977 fill_origin_blob(&sb->revs->diffopt, target, &file_o, &sb->num_read_blob);
978 sb->num_get_patch++;
980 if (diff_hunks(&file_p, &file_o, blame_chunk_cb, &d, sb->xdl_opts))
981 die("unable to generate diff (%s -> %s)",
982 oid_to_hex(&parent->commit->object.oid),
983 oid_to_hex(&target->commit->object.oid));
984 /* The rest are the same as the parent */
985 blame_chunk(&d.dstq, &d.srcq, INT_MAX, d.offset, INT_MAX, parent);
986 *d.dstq = NULL;
987 queue_blames(sb, parent, newdest);
989 return;
993 * The lines in blame_entry after splitting blames many times can become
994 * very small and trivial, and at some point it becomes pointless to
995 * blame the parents. E.g. "\t\t}\n\t}\n\n" appears everywhere in any
996 * ordinary C program, and it is not worth to say it was copied from
997 * totally unrelated file in the parent.
999 * Compute how trivial the lines in the blame_entry are.
1001 unsigned blame_entry_score(struct blame_scoreboard *sb, struct blame_entry *e)
1003 unsigned score;
1004 const char *cp, *ep;
1006 if (e->score)
1007 return e->score;
1009 score = 1;
1010 cp = blame_nth_line(sb, e->lno);
1011 ep = blame_nth_line(sb, e->lno + e->num_lines);
1012 while (cp < ep) {
1013 unsigned ch = *((unsigned char *)cp);
1014 if (isalnum(ch))
1015 score++;
1016 cp++;
1018 e->score = score;
1019 return score;
1023 * best_so_far[] and potential[] are both a split of an existing blame_entry
1024 * that passes blame to the parent. Maintain best_so_far the best split so
1025 * far, by comparing potential and best_so_far and copying potential into
1026 * bst_so_far as needed.
1028 static void copy_split_if_better(struct blame_scoreboard *sb,
1029 struct blame_entry *best_so_far,
1030 struct blame_entry *potential)
1032 int i;
1034 if (!potential[1].suspect)
1035 return;
1036 if (best_so_far[1].suspect) {
1037 if (blame_entry_score(sb, &potential[1]) <
1038 blame_entry_score(sb, &best_so_far[1]))
1039 return;
1042 for (i = 0; i < 3; i++)
1043 blame_origin_incref(potential[i].suspect);
1044 decref_split(best_so_far);
1045 memcpy(best_so_far, potential, sizeof(struct blame_entry[3]));
1049 * We are looking at a part of the final image represented by
1050 * ent (tlno and same are offset by ent->s_lno).
1051 * tlno is where we are looking at in the final image.
1052 * up to (but not including) same match preimage.
1053 * plno is where we are looking at in the preimage.
1055 * <-------------- final image ---------------------->
1056 * <------ent------>
1057 * ^tlno ^same
1058 * <---------preimage----->
1059 * ^plno
1061 * All line numbers are 0-based.
1063 static void handle_split(struct blame_scoreboard *sb,
1064 struct blame_entry *ent,
1065 int tlno, int plno, int same,
1066 struct blame_origin *parent,
1067 struct blame_entry *split)
1069 if (ent->num_lines <= tlno)
1070 return;
1071 if (tlno < same) {
1072 struct blame_entry potential[3];
1073 tlno += ent->s_lno;
1074 same += ent->s_lno;
1075 split_overlap(potential, ent, tlno, plno, same, parent);
1076 copy_split_if_better(sb, split, potential);
1077 decref_split(potential);
1081 struct handle_split_cb_data {
1082 struct blame_scoreboard *sb;
1083 struct blame_entry *ent;
1084 struct blame_origin *parent;
1085 struct blame_entry *split;
1086 long plno;
1087 long tlno;
1090 static int handle_split_cb(long start_a, long count_a,
1091 long start_b, long count_b, void *data)
1093 struct handle_split_cb_data *d = data;
1094 handle_split(d->sb, d->ent, d->tlno, d->plno, start_b, d->parent,
1095 d->split);
1096 d->plno = start_a + count_a;
1097 d->tlno = start_b + count_b;
1098 return 0;
1102 * Find the lines from parent that are the same as ent so that
1103 * we can pass blames to it. file_p has the blob contents for
1104 * the parent.
1106 static void find_copy_in_blob(struct blame_scoreboard *sb,
1107 struct blame_entry *ent,
1108 struct blame_origin *parent,
1109 struct blame_entry *split,
1110 mmfile_t *file_p)
1112 const char *cp;
1113 mmfile_t file_o;
1114 struct handle_split_cb_data d;
1116 memset(&d, 0, sizeof(d));
1117 d.sb = sb; d.ent = ent; d.parent = parent; d.split = split;
1119 * Prepare mmfile that contains only the lines in ent.
1121 cp = blame_nth_line(sb, ent->lno);
1122 file_o.ptr = (char *) cp;
1123 file_o.size = blame_nth_line(sb, ent->lno + ent->num_lines) - cp;
1126 * file_o is a part of final image we are annotating.
1127 * file_p partially may match that image.
1129 memset(split, 0, sizeof(struct blame_entry [3]));
1130 if (diff_hunks(file_p, &file_o, handle_split_cb, &d, sb->xdl_opts))
1131 die("unable to generate diff (%s)",
1132 oid_to_hex(&parent->commit->object.oid));
1133 /* remainder, if any, all match the preimage */
1134 handle_split(sb, ent, d.tlno, d.plno, ent->num_lines, parent, split);
1137 /* Move all blame entries from list *source that have a score smaller
1138 * than score_min to the front of list *small.
1139 * Returns a pointer to the link pointing to the old head of the small list.
1142 static struct blame_entry **filter_small(struct blame_scoreboard *sb,
1143 struct blame_entry **small,
1144 struct blame_entry **source,
1145 unsigned score_min)
1147 struct blame_entry *p = *source;
1148 struct blame_entry *oldsmall = *small;
1149 while (p) {
1150 if (blame_entry_score(sb, p) <= score_min) {
1151 *small = p;
1152 small = &p->next;
1153 p = *small;
1154 } else {
1155 *source = p;
1156 source = &p->next;
1157 p = *source;
1160 *small = oldsmall;
1161 *source = NULL;
1162 return small;
1166 * See if lines currently target is suspected for can be attributed to
1167 * parent.
1169 static void find_move_in_parent(struct blame_scoreboard *sb,
1170 struct blame_entry ***blamed,
1171 struct blame_entry **toosmall,
1172 struct blame_origin *target,
1173 struct blame_origin *parent)
1175 struct blame_entry *e, split[3];
1176 struct blame_entry *unblamed = target->suspects;
1177 struct blame_entry *leftover = NULL;
1178 mmfile_t file_p;
1180 if (!unblamed)
1181 return; /* nothing remains for this target */
1183 fill_origin_blob(&sb->revs->diffopt, parent, &file_p, &sb->num_read_blob);
1184 if (!file_p.ptr)
1185 return;
1187 /* At each iteration, unblamed has a NULL-terminated list of
1188 * entries that have not yet been tested for blame. leftover
1189 * contains the reversed list of entries that have been tested
1190 * without being assignable to the parent.
1192 do {
1193 struct blame_entry **unblamedtail = &unblamed;
1194 struct blame_entry *next;
1195 for (e = unblamed; e; e = next) {
1196 next = e->next;
1197 find_copy_in_blob(sb, e, parent, split, &file_p);
1198 if (split[1].suspect &&
1199 sb->move_score < blame_entry_score(sb, &split[1])) {
1200 split_blame(blamed, &unblamedtail, split, e);
1201 } else {
1202 e->next = leftover;
1203 leftover = e;
1205 decref_split(split);
1207 *unblamedtail = NULL;
1208 toosmall = filter_small(sb, toosmall, &unblamed, sb->move_score);
1209 } while (unblamed);
1210 target->suspects = reverse_blame(leftover, NULL);
1213 struct blame_list {
1214 struct blame_entry *ent;
1215 struct blame_entry split[3];
1219 * Count the number of entries the target is suspected for,
1220 * and prepare a list of entry and the best split.
1222 static struct blame_list *setup_blame_list(struct blame_entry *unblamed,
1223 int *num_ents_p)
1225 struct blame_entry *e;
1226 int num_ents, i;
1227 struct blame_list *blame_list = NULL;
1229 for (e = unblamed, num_ents = 0; e; e = e->next)
1230 num_ents++;
1231 if (num_ents) {
1232 blame_list = xcalloc(num_ents, sizeof(struct blame_list));
1233 for (e = unblamed, i = 0; e; e = e->next)
1234 blame_list[i++].ent = e;
1236 *num_ents_p = num_ents;
1237 return blame_list;
1241 * For lines target is suspected for, see if we can find code movement
1242 * across file boundary from the parent commit. porigin is the path
1243 * in the parent we already tried.
1245 static void find_copy_in_parent(struct blame_scoreboard *sb,
1246 struct blame_entry ***blamed,
1247 struct blame_entry **toosmall,
1248 struct blame_origin *target,
1249 struct commit *parent,
1250 struct blame_origin *porigin,
1251 int opt)
1253 struct diff_options diff_opts;
1254 int i, j;
1255 struct blame_list *blame_list;
1256 int num_ents;
1257 struct blame_entry *unblamed = target->suspects;
1258 struct blame_entry *leftover = NULL;
1260 if (!unblamed)
1261 return; /* nothing remains for this target */
1263 diff_setup(&diff_opts);
1264 diff_opts.flags.recursive = 1;
1265 diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;
1267 diff_setup_done(&diff_opts);
1269 /* Try "find copies harder" on new path if requested;
1270 * we do not want to use diffcore_rename() actually to
1271 * match things up; find_copies_harder is set only to
1272 * force diff_tree_oid() to feed all filepairs to diff_queue,
1273 * and this code needs to be after diff_setup_done(), which
1274 * usually makes find-copies-harder imply copy detection.
1276 if ((opt & PICKAXE_BLAME_COPY_HARDEST)
1277 || ((opt & PICKAXE_BLAME_COPY_HARDER)
1278 && (!porigin || strcmp(target->path, porigin->path))))
1279 diff_opts.flags.find_copies_harder = 1;
1281 if (is_null_oid(&target->commit->object.oid))
1282 do_diff_cache(get_commit_tree_oid(parent), &diff_opts);
1283 else
1284 diff_tree_oid(get_commit_tree_oid(parent),
1285 get_commit_tree_oid(target->commit),
1286 "", &diff_opts);
1288 if (!diff_opts.flags.find_copies_harder)
1289 diffcore_std(&diff_opts);
1291 do {
1292 struct blame_entry **unblamedtail = &unblamed;
1293 blame_list = setup_blame_list(unblamed, &num_ents);
1295 for (i = 0; i < diff_queued_diff.nr; i++) {
1296 struct diff_filepair *p = diff_queued_diff.queue[i];
1297 struct blame_origin *norigin;
1298 mmfile_t file_p;
1299 struct blame_entry potential[3];
1301 if (!DIFF_FILE_VALID(p->one))
1302 continue; /* does not exist in parent */
1303 if (S_ISGITLINK(p->one->mode))
1304 continue; /* ignore git links */
1305 if (porigin && !strcmp(p->one->path, porigin->path))
1306 /* find_move already dealt with this path */
1307 continue;
1309 norigin = get_origin(parent, p->one->path);
1310 oidcpy(&norigin->blob_oid, &p->one->oid);
1311 norigin->mode = p->one->mode;
1312 fill_origin_blob(&sb->revs->diffopt, norigin, &file_p, &sb->num_read_blob);
1313 if (!file_p.ptr)
1314 continue;
1316 for (j = 0; j < num_ents; j++) {
1317 find_copy_in_blob(sb, blame_list[j].ent,
1318 norigin, potential, &file_p);
1319 copy_split_if_better(sb, blame_list[j].split,
1320 potential);
1321 decref_split(potential);
1323 blame_origin_decref(norigin);
1326 for (j = 0; j < num_ents; j++) {
1327 struct blame_entry *split = blame_list[j].split;
1328 if (split[1].suspect &&
1329 sb->copy_score < blame_entry_score(sb, &split[1])) {
1330 split_blame(blamed, &unblamedtail, split,
1331 blame_list[j].ent);
1332 } else {
1333 blame_list[j].ent->next = leftover;
1334 leftover = blame_list[j].ent;
1336 decref_split(split);
1338 free(blame_list);
1339 *unblamedtail = NULL;
1340 toosmall = filter_small(sb, toosmall, &unblamed, sb->copy_score);
1341 } while (unblamed);
1342 target->suspects = reverse_blame(leftover, NULL);
1343 diff_flush(&diff_opts);
1344 clear_pathspec(&diff_opts.pathspec);
1348 * The blobs of origin and porigin exactly match, so everything
1349 * origin is suspected for can be blamed on the parent.
1351 static void pass_whole_blame(struct blame_scoreboard *sb,
1352 struct blame_origin *origin, struct blame_origin *porigin)
1354 struct blame_entry *e, *suspects;
1356 if (!porigin->file.ptr && origin->file.ptr) {
1357 /* Steal its file */
1358 porigin->file = origin->file;
1359 origin->file.ptr = NULL;
1361 suspects = origin->suspects;
1362 origin->suspects = NULL;
1363 for (e = suspects; e; e = e->next) {
1364 blame_origin_incref(porigin);
1365 blame_origin_decref(e->suspect);
1366 e->suspect = porigin;
1368 queue_blames(sb, porigin, suspects);
1372 * We pass blame from the current commit to its parents. We keep saying
1373 * "parent" (and "porigin"), but what we mean is to find scapegoat to
1374 * exonerate ourselves.
1376 static struct commit_list *first_scapegoat(struct rev_info *revs, struct commit *commit,
1377 int reverse)
1379 if (!reverse) {
1380 if (revs->first_parent_only &&
1381 commit->parents &&
1382 commit->parents->next) {
1383 free_commit_list(commit->parents->next);
1384 commit->parents->next = NULL;
1386 return commit->parents;
1388 return lookup_decoration(&revs->children, &commit->object);
1391 static int num_scapegoats(struct rev_info *revs, struct commit *commit, int reverse)
1393 struct commit_list *l = first_scapegoat(revs, commit, reverse);
1394 return commit_list_count(l);
1397 /* Distribute collected unsorted blames to the respected sorted lists
1398 * in the various origins.
1400 static void distribute_blame(struct blame_scoreboard *sb, struct blame_entry *blamed)
1402 blamed = llist_mergesort(blamed, get_next_blame, set_next_blame,
1403 compare_blame_suspect);
1404 while (blamed)
1406 struct blame_origin *porigin = blamed->suspect;
1407 struct blame_entry *suspects = NULL;
1408 do {
1409 struct blame_entry *next = blamed->next;
1410 blamed->next = suspects;
1411 suspects = blamed;
1412 blamed = next;
1413 } while (blamed && blamed->suspect == porigin);
1414 suspects = reverse_blame(suspects, NULL);
1415 queue_blames(sb, porigin, suspects);
1419 #define MAXSG 16
1421 static void pass_blame(struct blame_scoreboard *sb, struct blame_origin *origin, int opt)
1423 struct rev_info *revs = sb->revs;
1424 int i, pass, num_sg;
1425 struct commit *commit = origin->commit;
1426 struct commit_list *sg;
1427 struct blame_origin *sg_buf[MAXSG];
1428 struct blame_origin *porigin, **sg_origin = sg_buf;
1429 struct blame_entry *toosmall = NULL;
1430 struct blame_entry *blames, **blametail = &blames;
1432 num_sg = num_scapegoats(revs, commit, sb->reverse);
1433 if (!num_sg)
1434 goto finish;
1435 else if (num_sg < ARRAY_SIZE(sg_buf))
1436 memset(sg_buf, 0, sizeof(sg_buf));
1437 else
1438 sg_origin = xcalloc(num_sg, sizeof(*sg_origin));
1441 * The first pass looks for unrenamed path to optimize for
1442 * common cases, then we look for renames in the second pass.
1444 for (pass = 0; pass < 2 - sb->no_whole_file_rename; pass++) {
1445 struct blame_origin *(*find)(struct commit *, struct blame_origin *);
1446 find = pass ? find_rename : find_origin;
1448 for (i = 0, sg = first_scapegoat(revs, commit, sb->reverse);
1449 i < num_sg && sg;
1450 sg = sg->next, i++) {
1451 struct commit *p = sg->item;
1452 int j, same;
1454 if (sg_origin[i])
1455 continue;
1456 if (parse_commit(p))
1457 continue;
1458 porigin = find(p, origin);
1459 if (!porigin)
1460 continue;
1461 if (!oidcmp(&porigin->blob_oid, &origin->blob_oid)) {
1462 pass_whole_blame(sb, origin, porigin);
1463 blame_origin_decref(porigin);
1464 goto finish;
1466 for (j = same = 0; j < i; j++)
1467 if (sg_origin[j] &&
1468 !oidcmp(&sg_origin[j]->blob_oid, &porigin->blob_oid)) {
1469 same = 1;
1470 break;
1472 if (!same)
1473 sg_origin[i] = porigin;
1474 else
1475 blame_origin_decref(porigin);
1479 sb->num_commits++;
1480 for (i = 0, sg = first_scapegoat(revs, commit, sb->reverse);
1481 i < num_sg && sg;
1482 sg = sg->next, i++) {
1483 struct blame_origin *porigin = sg_origin[i];
1484 if (!porigin)
1485 continue;
1486 if (!origin->previous) {
1487 blame_origin_incref(porigin);
1488 origin->previous = porigin;
1490 pass_blame_to_parent(sb, origin, porigin);
1491 if (!origin->suspects)
1492 goto finish;
1496 * Optionally find moves in parents' files.
1498 if (opt & PICKAXE_BLAME_MOVE) {
1499 filter_small(sb, &toosmall, &origin->suspects, sb->move_score);
1500 if (origin->suspects) {
1501 for (i = 0, sg = first_scapegoat(revs, commit, sb->reverse);
1502 i < num_sg && sg;
1503 sg = sg->next, i++) {
1504 struct blame_origin *porigin = sg_origin[i];
1505 if (!porigin)
1506 continue;
1507 find_move_in_parent(sb, &blametail, &toosmall, origin, porigin);
1508 if (!origin->suspects)
1509 break;
1515 * Optionally find copies from parents' files.
1517 if (opt & PICKAXE_BLAME_COPY) {
1518 if (sb->copy_score > sb->move_score)
1519 filter_small(sb, &toosmall, &origin->suspects, sb->copy_score);
1520 else if (sb->copy_score < sb->move_score) {
1521 origin->suspects = blame_merge(origin->suspects, toosmall);
1522 toosmall = NULL;
1523 filter_small(sb, &toosmall, &origin->suspects, sb->copy_score);
1525 if (!origin->suspects)
1526 goto finish;
1528 for (i = 0, sg = first_scapegoat(revs, commit, sb->reverse);
1529 i < num_sg && sg;
1530 sg = sg->next, i++) {
1531 struct blame_origin *porigin = sg_origin[i];
1532 find_copy_in_parent(sb, &blametail, &toosmall,
1533 origin, sg->item, porigin, opt);
1534 if (!origin->suspects)
1535 goto finish;
1539 finish:
1540 *blametail = NULL;
1541 distribute_blame(sb, blames);
1543 * prepend toosmall to origin->suspects
1545 * There is no point in sorting: this ends up on a big
1546 * unsorted list in the caller anyway.
1548 if (toosmall) {
1549 struct blame_entry **tail = &toosmall;
1550 while (*tail)
1551 tail = &(*tail)->next;
1552 *tail = origin->suspects;
1553 origin->suspects = toosmall;
1555 for (i = 0; i < num_sg; i++) {
1556 if (sg_origin[i]) {
1557 drop_origin_blob(sg_origin[i]);
1558 blame_origin_decref(sg_origin[i]);
1561 drop_origin_blob(origin);
1562 if (sg_buf != sg_origin)
1563 free(sg_origin);
1567 * The main loop -- while we have blobs with lines whose true origin
1568 * is still unknown, pick one blob, and allow its lines to pass blames
1569 * to its parents. */
1570 void assign_blame(struct blame_scoreboard *sb, int opt)
1572 struct rev_info *revs = sb->revs;
1573 struct commit *commit = prio_queue_get(&sb->commits);
1575 while (commit) {
1576 struct blame_entry *ent;
1577 struct blame_origin *suspect = get_blame_suspects(commit);
1579 /* find one suspect to break down */
1580 while (suspect && !suspect->suspects)
1581 suspect = suspect->next;
1583 if (!suspect) {
1584 commit = prio_queue_get(&sb->commits);
1585 continue;
1588 assert(commit == suspect->commit);
1591 * We will use this suspect later in the loop,
1592 * so hold onto it in the meantime.
1594 blame_origin_incref(suspect);
1595 parse_commit(commit);
1596 if (sb->reverse ||
1597 (!(commit->object.flags & UNINTERESTING) &&
1598 !(revs->max_age != -1 && commit->date < revs->max_age)))
1599 pass_blame(sb, suspect, opt);
1600 else {
1601 commit->object.flags |= UNINTERESTING;
1602 if (commit->object.parsed)
1603 mark_parents_uninteresting(commit);
1605 /* treat root commit as boundary */
1606 if (!commit->parents && !sb->show_root)
1607 commit->object.flags |= UNINTERESTING;
1609 /* Take responsibility for the remaining entries */
1610 ent = suspect->suspects;
1611 if (ent) {
1612 suspect->guilty = 1;
1613 for (;;) {
1614 struct blame_entry *next = ent->next;
1615 if (sb->found_guilty_entry)
1616 sb->found_guilty_entry(ent, sb->found_guilty_entry_data);
1617 if (next) {
1618 ent = next;
1619 continue;
1621 ent->next = sb->ent;
1622 sb->ent = suspect->suspects;
1623 suspect->suspects = NULL;
1624 break;
1627 blame_origin_decref(suspect);
1629 if (sb->debug) /* sanity */
1630 sanity_check_refcnt(sb);
1634 static const char *get_next_line(const char *start, const char *end)
1636 const char *nl = memchr(start, '\n', end - start);
1637 return nl ? nl + 1 : end;
1641 * To allow quick access to the contents of nth line in the
1642 * final image, prepare an index in the scoreboard.
1644 static int prepare_lines(struct blame_scoreboard *sb)
1646 const char *buf = sb->final_buf;
1647 unsigned long len = sb->final_buf_size;
1648 const char *end = buf + len;
1649 const char *p;
1650 int *lineno;
1651 int num = 0;
1653 for (p = buf; p < end; p = get_next_line(p, end))
1654 num++;
1656 ALLOC_ARRAY(sb->lineno, num + 1);
1657 lineno = sb->lineno;
1659 for (p = buf; p < end; p = get_next_line(p, end))
1660 *lineno++ = p - buf;
1662 *lineno = len;
1664 sb->num_lines = num;
1665 return sb->num_lines;
1668 static struct commit *find_single_final(struct rev_info *revs,
1669 const char **name_p)
1671 int i;
1672 struct commit *found = NULL;
1673 const char *name = NULL;
1675 for (i = 0; i < revs->pending.nr; i++) {
1676 struct object *obj = revs->pending.objects[i].item;
1677 if (obj->flags & UNINTERESTING)
1678 continue;
1679 obj = deref_tag(the_repository, obj, NULL, 0);
1680 if (obj->type != OBJ_COMMIT)
1681 die("Non commit %s?", revs->pending.objects[i].name);
1682 if (found)
1683 die("More than one commit to dig from %s and %s?",
1684 revs->pending.objects[i].name, name);
1685 found = (struct commit *)obj;
1686 name = revs->pending.objects[i].name;
1688 if (name_p)
1689 *name_p = xstrdup_or_null(name);
1690 return found;
1693 static struct commit *dwim_reverse_initial(struct rev_info *revs,
1694 const char **name_p)
1697 * DWIM "git blame --reverse ONE -- PATH" as
1698 * "git blame --reverse ONE..HEAD -- PATH" but only do so
1699 * when it makes sense.
1701 struct object *obj;
1702 struct commit *head_commit;
1703 struct object_id head_oid;
1705 if (revs->pending.nr != 1)
1706 return NULL;
1708 /* Is that sole rev a committish? */
1709 obj = revs->pending.objects[0].item;
1710 obj = deref_tag(the_repository, obj, NULL, 0);
1711 if (obj->type != OBJ_COMMIT)
1712 return NULL;
1714 /* Do we have HEAD? */
1715 if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, &head_oid, NULL))
1716 return NULL;
1717 head_commit = lookup_commit_reference_gently(the_repository,
1718 &head_oid, 1);
1719 if (!head_commit)
1720 return NULL;
1722 /* Turn "ONE" into "ONE..HEAD" then */
1723 obj->flags |= UNINTERESTING;
1724 add_pending_object(revs, &head_commit->object, "HEAD");
1726 if (name_p)
1727 *name_p = revs->pending.objects[0].name;
1728 return (struct commit *)obj;
1731 static struct commit *find_single_initial(struct rev_info *revs,
1732 const char **name_p)
1734 int i;
1735 struct commit *found = NULL;
1736 const char *name = NULL;
1739 * There must be one and only one negative commit, and it must be
1740 * the boundary.
1742 for (i = 0; i < revs->pending.nr; i++) {
1743 struct object *obj = revs->pending.objects[i].item;
1744 if (!(obj->flags & UNINTERESTING))
1745 continue;
1746 obj = deref_tag(the_repository, obj, NULL, 0);
1747 if (obj->type != OBJ_COMMIT)
1748 die("Non commit %s?", revs->pending.objects[i].name);
1749 if (found)
1750 die("More than one commit to dig up from, %s and %s?",
1751 revs->pending.objects[i].name, name);
1752 found = (struct commit *) obj;
1753 name = revs->pending.objects[i].name;
1756 if (!name)
1757 found = dwim_reverse_initial(revs, &name);
1758 if (!name)
1759 die("No commit to dig up from?");
1761 if (name_p)
1762 *name_p = xstrdup(name);
1763 return found;
1766 void init_scoreboard(struct blame_scoreboard *sb)
1768 memset(sb, 0, sizeof(struct blame_scoreboard));
1769 sb->move_score = BLAME_DEFAULT_MOVE_SCORE;
1770 sb->copy_score = BLAME_DEFAULT_COPY_SCORE;
1773 void setup_scoreboard(struct blame_scoreboard *sb,
1774 const char *path,
1775 struct blame_origin **orig)
1777 const char *final_commit_name = NULL;
1778 struct blame_origin *o;
1779 struct commit *final_commit = NULL;
1780 enum object_type type;
1782 init_blame_suspects(&blame_suspects);
1784 if (sb->reverse && sb->contents_from)
1785 die(_("--contents and --reverse do not blend well."));
1787 if (!sb->repo)
1788 BUG("repo is NULL");
1790 if (!sb->reverse) {
1791 sb->final = find_single_final(sb->revs, &final_commit_name);
1792 sb->commits.compare = compare_commits_by_commit_date;
1793 } else {
1794 sb->final = find_single_initial(sb->revs, &final_commit_name);
1795 sb->commits.compare = compare_commits_by_reverse_commit_date;
1798 if (sb->final && sb->contents_from)
1799 die(_("cannot use --contents with final commit object name"));
1801 if (sb->reverse && sb->revs->first_parent_only)
1802 sb->revs->children.name = NULL;
1804 if (!sb->final) {
1806 * "--not A B -- path" without anything positive;
1807 * do not default to HEAD, but use the working tree
1808 * or "--contents".
1810 setup_work_tree();
1811 sb->final = fake_working_tree_commit(sb->repo,
1812 &sb->revs->diffopt,
1813 path, sb->contents_from);
1814 add_pending_object(sb->revs, &(sb->final->object), ":");
1817 if (sb->reverse && sb->revs->first_parent_only) {
1818 final_commit = find_single_final(sb->revs, NULL);
1819 if (!final_commit)
1820 die(_("--reverse and --first-parent together require specified latest commit"));
1824 * If we have bottom, this will mark the ancestors of the
1825 * bottom commits we would reach while traversing as
1826 * uninteresting.
1828 if (prepare_revision_walk(sb->revs))
1829 die(_("revision walk setup failed"));
1831 if (sb->reverse && sb->revs->first_parent_only) {
1832 struct commit *c = final_commit;
1834 sb->revs->children.name = "children";
1835 while (c->parents &&
1836 oidcmp(&c->object.oid, &sb->final->object.oid)) {
1837 struct commit_list *l = xcalloc(1, sizeof(*l));
1839 l->item = c;
1840 if (add_decoration(&sb->revs->children,
1841 &c->parents->item->object, l))
1842 BUG("not unique item in first-parent chain");
1843 c = c->parents->item;
1846 if (oidcmp(&c->object.oid, &sb->final->object.oid))
1847 die(_("--reverse --first-parent together require range along first-parent chain"));
1850 if (is_null_oid(&sb->final->object.oid)) {
1851 o = get_blame_suspects(sb->final);
1852 sb->final_buf = xmemdupz(o->file.ptr, o->file.size);
1853 sb->final_buf_size = o->file.size;
1855 else {
1856 o = get_origin(sb->final, path);
1857 if (fill_blob_sha1_and_mode(sb->repo, o))
1858 die(_("no such path %s in %s"), path, final_commit_name);
1860 if (sb->revs->diffopt.flags.allow_textconv &&
1861 textconv_object(sb->repo, path, o->mode, &o->blob_oid, 1, (char **) &sb->final_buf,
1862 &sb->final_buf_size))
1864 else
1865 sb->final_buf = read_object_file(&o->blob_oid, &type,
1866 &sb->final_buf_size);
1868 if (!sb->final_buf)
1869 die(_("cannot read blob %s for path %s"),
1870 oid_to_hex(&o->blob_oid),
1871 path);
1873 sb->num_read_blob++;
1874 prepare_lines(sb);
1876 if (orig)
1877 *orig = o;
1879 free((char *)final_commit_name);
1884 struct blame_entry *blame_entry_prepend(struct blame_entry *head,
1885 long start, long end,
1886 struct blame_origin *o)
1888 struct blame_entry *new_head = xcalloc(1, sizeof(struct blame_entry));
1889 new_head->lno = start;
1890 new_head->num_lines = end - start;
1891 new_head->suspect = o;
1892 new_head->s_lno = start;
1893 new_head->next = head;
1894 blame_origin_incref(o);
1895 return new_head;