mingw: special-case arguments to `sh`
[git.git] / blame.c
blob43861437f749849e85d448eba692b42488ec459d
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 repository *r,
120 struct commit_list **tail,
121 const struct object_id *oid)
123 struct commit *parent;
125 parent = lookup_commit_reference(r, oid);
126 if (!parent)
127 die("no such commit %s", oid_to_hex(oid));
128 return &commit_list_insert(parent, tail)->next;
131 static void append_merge_parents(struct repository *r,
132 struct commit_list **tail)
134 int merge_head;
135 struct strbuf line = STRBUF_INIT;
137 merge_head = open(git_path_merge_head(r), O_RDONLY);
138 if (merge_head < 0) {
139 if (errno == ENOENT)
140 return;
141 die("cannot open '%s' for reading",
142 git_path_merge_head(r));
145 while (!strbuf_getwholeline_fd(&line, merge_head, '\n')) {
146 struct object_id oid;
147 if (line.len < GIT_SHA1_HEXSZ || get_oid_hex(line.buf, &oid))
148 die("unknown line in '%s': %s",
149 git_path_merge_head(r), line.buf);
150 tail = append_parent(r, tail, &oid);
152 close(merge_head);
153 strbuf_release(&line);
157 * This isn't as simple as passing sb->buf and sb->len, because we
158 * want to transfer ownership of the buffer to the commit (so we
159 * must use detach).
161 static void set_commit_buffer_from_strbuf(struct repository *r,
162 struct commit *c,
163 struct strbuf *sb)
165 size_t len;
166 void *buf = strbuf_detach(sb, &len);
167 set_commit_buffer(r, c, buf, len);
171 * Prepare a dummy commit that represents the work tree (or staged) item.
172 * Note that annotating work tree item never works in the reverse.
174 static struct commit *fake_working_tree_commit(struct repository *r,
175 struct diff_options *opt,
176 const char *path,
177 const char *contents_from)
179 struct commit *commit;
180 struct blame_origin *origin;
181 struct commit_list **parent_tail, *parent;
182 struct object_id head_oid;
183 struct strbuf buf = STRBUF_INIT;
184 const char *ident;
185 time_t now;
186 int len;
187 struct cache_entry *ce;
188 unsigned mode;
189 struct strbuf msg = STRBUF_INIT;
191 read_index(r->index);
192 time(&now);
193 commit = alloc_commit_node(r);
194 commit->object.parsed = 1;
195 commit->date = now;
196 parent_tail = &commit->parents;
198 if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, &head_oid, NULL))
199 die("no such ref: HEAD");
201 parent_tail = append_parent(r, parent_tail, &head_oid);
202 append_merge_parents(r, parent_tail);
203 verify_working_tree_path(r, commit, path);
205 origin = make_origin(commit, path);
207 ident = fmt_ident("Not Committed Yet", "not.committed.yet", NULL, 0);
208 strbuf_addstr(&msg, "tree 0000000000000000000000000000000000000000\n");
209 for (parent = commit->parents; parent; parent = parent->next)
210 strbuf_addf(&msg, "parent %s\n",
211 oid_to_hex(&parent->item->object.oid));
212 strbuf_addf(&msg,
213 "author %s\n"
214 "committer %s\n\n"
215 "Version of %s from %s\n",
216 ident, ident, path,
217 (!contents_from ? path :
218 (!strcmp(contents_from, "-") ? "standard input" : contents_from)));
219 set_commit_buffer_from_strbuf(r, commit, &msg);
221 if (!contents_from || strcmp("-", contents_from)) {
222 struct stat st;
223 const char *read_from;
224 char *buf_ptr;
225 unsigned long buf_len;
227 if (contents_from) {
228 if (stat(contents_from, &st) < 0)
229 die_errno("Cannot stat '%s'", contents_from);
230 read_from = contents_from;
232 else {
233 if (lstat(path, &st) < 0)
234 die_errno("Cannot lstat '%s'", path);
235 read_from = path;
237 mode = canon_mode(st.st_mode);
239 switch (st.st_mode & S_IFMT) {
240 case S_IFREG:
241 if (opt->flags.allow_textconv &&
242 textconv_object(r, read_from, mode, &null_oid, 0, &buf_ptr, &buf_len))
243 strbuf_attach(&buf, buf_ptr, buf_len, buf_len + 1);
244 else if (strbuf_read_file(&buf, read_from, st.st_size) != st.st_size)
245 die_errno("cannot open or read '%s'", read_from);
246 break;
247 case S_IFLNK:
248 if (strbuf_readlink(&buf, read_from, st.st_size) < 0)
249 die_errno("cannot readlink '%s'", read_from);
250 break;
251 default:
252 die("unsupported file type %s", read_from);
255 else {
256 /* Reading from stdin */
257 mode = 0;
258 if (strbuf_read(&buf, 0, 0) < 0)
259 die_errno("failed to read from stdin");
261 convert_to_git(r->index, path, buf.buf, buf.len, &buf, 0);
262 origin->file.ptr = buf.buf;
263 origin->file.size = buf.len;
264 pretend_object_file(buf.buf, buf.len, OBJ_BLOB, &origin->blob_oid);
267 * Read the current index, replace the path entry with
268 * origin->blob_sha1 without mucking with its mode or type
269 * bits; we are not going to write this index out -- we just
270 * want to run "diff-index --cached".
272 discard_index(r->index);
273 read_index(r->index);
275 len = strlen(path);
276 if (!mode) {
277 int pos = index_name_pos(r->index, path, len);
278 if (0 <= pos)
279 mode = r->index->cache[pos]->ce_mode;
280 else
281 /* Let's not bother reading from HEAD tree */
282 mode = S_IFREG | 0644;
284 ce = make_empty_cache_entry(r->index, len);
285 oidcpy(&ce->oid, &origin->blob_oid);
286 memcpy(ce->name, path, len);
287 ce->ce_flags = create_ce_flags(0);
288 ce->ce_namelen = len;
289 ce->ce_mode = create_ce_mode(mode);
290 add_index_entry(r->index, ce,
291 ADD_CACHE_OK_TO_ADD | ADD_CACHE_OK_TO_REPLACE);
293 cache_tree_invalidate_path(r->index, path);
295 return commit;
300 static int diff_hunks(mmfile_t *file_a, mmfile_t *file_b,
301 xdl_emit_hunk_consume_func_t hunk_func, void *cb_data, int xdl_opts)
303 xpparam_t xpp = {0};
304 xdemitconf_t xecfg = {0};
305 xdemitcb_t ecb = {NULL};
307 xpp.flags = xdl_opts;
308 xecfg.hunk_func = hunk_func;
309 ecb.priv = cb_data;
310 return xdi_diff(file_a, file_b, &xpp, &xecfg, &ecb);
314 * Given an origin, prepare mmfile_t structure to be used by the
315 * diff machinery
317 static void fill_origin_blob(struct diff_options *opt,
318 struct blame_origin *o, mmfile_t *file, int *num_read_blob)
320 if (!o->file.ptr) {
321 enum object_type type;
322 unsigned long file_size;
324 (*num_read_blob)++;
325 if (opt->flags.allow_textconv &&
326 textconv_object(opt->repo, o->path, o->mode,
327 &o->blob_oid, 1, &file->ptr, &file_size))
329 else
330 file->ptr = read_object_file(&o->blob_oid, &type,
331 &file_size);
332 file->size = file_size;
334 if (!file->ptr)
335 die("Cannot read blob %s for path %s",
336 oid_to_hex(&o->blob_oid),
337 o->path);
338 o->file = *file;
340 else
341 *file = o->file;
344 static void drop_origin_blob(struct blame_origin *o)
346 FREE_AND_NULL(o->file.ptr);
350 * Any merge of blames happens on lists of blames that arrived via
351 * different parents in a single suspect. In this case, we want to
352 * sort according to the suspect line numbers as opposed to the final
353 * image line numbers. The function body is somewhat longish because
354 * it avoids unnecessary writes.
357 static struct blame_entry *blame_merge(struct blame_entry *list1,
358 struct blame_entry *list2)
360 struct blame_entry *p1 = list1, *p2 = list2,
361 **tail = &list1;
363 if (!p1)
364 return p2;
365 if (!p2)
366 return p1;
368 if (p1->s_lno <= p2->s_lno) {
369 do {
370 tail = &p1->next;
371 if ((p1 = *tail) == NULL) {
372 *tail = p2;
373 return list1;
375 } while (p1->s_lno <= p2->s_lno);
377 for (;;) {
378 *tail = p2;
379 do {
380 tail = &p2->next;
381 if ((p2 = *tail) == NULL) {
382 *tail = p1;
383 return list1;
385 } while (p1->s_lno > p2->s_lno);
386 *tail = p1;
387 do {
388 tail = &p1->next;
389 if ((p1 = *tail) == NULL) {
390 *tail = p2;
391 return list1;
393 } while (p1->s_lno <= p2->s_lno);
397 static void *get_next_blame(const void *p)
399 return ((struct blame_entry *)p)->next;
402 static void set_next_blame(void *p1, void *p2)
404 ((struct blame_entry *)p1)->next = p2;
408 * Final image line numbers are all different, so we don't need a
409 * three-way comparison here.
412 static int compare_blame_final(const void *p1, const void *p2)
414 return ((struct blame_entry *)p1)->lno > ((struct blame_entry *)p2)->lno
415 ? 1 : -1;
418 static int compare_blame_suspect(const void *p1, const void *p2)
420 const struct blame_entry *s1 = p1, *s2 = p2;
422 * to allow for collating suspects, we sort according to the
423 * respective pointer value as the primary sorting criterion.
424 * The actual relation is pretty unimportant as long as it
425 * establishes a total order. Comparing as integers gives us
426 * that.
428 if (s1->suspect != s2->suspect)
429 return (intptr_t)s1->suspect > (intptr_t)s2->suspect ? 1 : -1;
430 if (s1->s_lno == s2->s_lno)
431 return 0;
432 return s1->s_lno > s2->s_lno ? 1 : -1;
435 void blame_sort_final(struct blame_scoreboard *sb)
437 sb->ent = llist_mergesort(sb->ent, get_next_blame, set_next_blame,
438 compare_blame_final);
441 static int compare_commits_by_reverse_commit_date(const void *a,
442 const void *b,
443 void *c)
445 return -compare_commits_by_commit_date(a, b, c);
449 * For debugging -- origin is refcounted, and this asserts that
450 * we do not underflow.
452 static void sanity_check_refcnt(struct blame_scoreboard *sb)
454 int baa = 0;
455 struct blame_entry *ent;
457 for (ent = sb->ent; ent; ent = ent->next) {
458 /* Nobody should have zero or negative refcnt */
459 if (ent->suspect->refcnt <= 0) {
460 fprintf(stderr, "%s in %s has negative refcnt %d\n",
461 ent->suspect->path,
462 oid_to_hex(&ent->suspect->commit->object.oid),
463 ent->suspect->refcnt);
464 baa = 1;
467 if (baa)
468 sb->on_sanity_fail(sb, baa);
472 * If two blame entries that are next to each other came from
473 * contiguous lines in the same origin (i.e. <commit, path> pair),
474 * merge them together.
476 void blame_coalesce(struct blame_scoreboard *sb)
478 struct blame_entry *ent, *next;
480 for (ent = sb->ent; ent && (next = ent->next); ent = next) {
481 if (ent->suspect == next->suspect &&
482 ent->s_lno + ent->num_lines == next->s_lno) {
483 ent->num_lines += next->num_lines;
484 ent->next = next->next;
485 blame_origin_decref(next->suspect);
486 free(next);
487 ent->score = 0;
488 next = ent; /* again */
492 if (sb->debug) /* sanity */
493 sanity_check_refcnt(sb);
497 * Merge the given sorted list of blames into a preexisting origin.
498 * If there were no previous blames to that commit, it is entered into
499 * the commit priority queue of the score board.
502 static void queue_blames(struct blame_scoreboard *sb, struct blame_origin *porigin,
503 struct blame_entry *sorted)
505 if (porigin->suspects)
506 porigin->suspects = blame_merge(porigin->suspects, sorted);
507 else {
508 struct blame_origin *o;
509 for (o = get_blame_suspects(porigin->commit); o; o = o->next) {
510 if (o->suspects) {
511 porigin->suspects = sorted;
512 return;
515 porigin->suspects = sorted;
516 prio_queue_put(&sb->commits, porigin->commit);
521 * Fill the blob_sha1 field of an origin if it hasn't, so that later
522 * call to fill_origin_blob() can use it to locate the data. blob_sha1
523 * for an origin is also used to pass the blame for the entire file to
524 * the parent to detect the case where a child's blob is identical to
525 * that of its parent's.
527 * This also fills origin->mode for corresponding tree path.
529 static int fill_blob_sha1_and_mode(struct repository *r,
530 struct blame_origin *origin)
532 if (!is_null_oid(&origin->blob_oid))
533 return 0;
534 if (get_tree_entry(&origin->commit->object.oid, origin->path, &origin->blob_oid, &origin->mode))
535 goto error_out;
536 if (oid_object_info(r, &origin->blob_oid, NULL) != OBJ_BLOB)
537 goto error_out;
538 return 0;
539 error_out:
540 oidclr(&origin->blob_oid);
541 origin->mode = S_IFINVALID;
542 return -1;
546 * We have an origin -- check if the same path exists in the
547 * parent and return an origin structure to represent it.
549 static struct blame_origin *find_origin(struct repository *r,
550 struct commit *parent,
551 struct blame_origin *origin)
553 struct blame_origin *porigin;
554 struct diff_options diff_opts;
555 const char *paths[2];
557 /* First check any existing origins */
558 for (porigin = get_blame_suspects(parent); porigin; porigin = porigin->next)
559 if (!strcmp(porigin->path, origin->path)) {
561 * The same path between origin and its parent
562 * without renaming -- the most common case.
564 return blame_origin_incref (porigin);
567 /* See if the origin->path is different between parent
568 * and origin first. Most of the time they are the
569 * same and diff-tree is fairly efficient about this.
571 repo_diff_setup(r, &diff_opts);
572 diff_opts.flags.recursive = 1;
573 diff_opts.detect_rename = 0;
574 diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;
575 paths[0] = origin->path;
576 paths[1] = NULL;
578 parse_pathspec(&diff_opts.pathspec,
579 PATHSPEC_ALL_MAGIC & ~PATHSPEC_LITERAL,
580 PATHSPEC_LITERAL_PATH, "", paths);
581 diff_setup_done(&diff_opts);
583 if (is_null_oid(&origin->commit->object.oid))
584 do_diff_cache(get_commit_tree_oid(parent), &diff_opts);
585 else
586 diff_tree_oid(get_commit_tree_oid(parent),
587 get_commit_tree_oid(origin->commit),
588 "", &diff_opts);
589 diffcore_std(&diff_opts);
591 if (!diff_queued_diff.nr) {
592 /* The path is the same as parent */
593 porigin = get_origin(parent, origin->path);
594 oidcpy(&porigin->blob_oid, &origin->blob_oid);
595 porigin->mode = origin->mode;
596 } else {
598 * Since origin->path is a pathspec, if the parent
599 * commit had it as a directory, we will see a whole
600 * bunch of deletion of files in the directory that we
601 * do not care about.
603 int i;
604 struct diff_filepair *p = NULL;
605 for (i = 0; i < diff_queued_diff.nr; i++) {
606 const char *name;
607 p = diff_queued_diff.queue[i];
608 name = p->one->path ? p->one->path : p->two->path;
609 if (!strcmp(name, origin->path))
610 break;
612 if (!p)
613 die("internal error in blame::find_origin");
614 switch (p->status) {
615 default:
616 die("internal error in blame::find_origin (%c)",
617 p->status);
618 case 'M':
619 porigin = get_origin(parent, origin->path);
620 oidcpy(&porigin->blob_oid, &p->one->oid);
621 porigin->mode = p->one->mode;
622 break;
623 case 'A':
624 case 'T':
625 /* Did not exist in parent, or type changed */
626 break;
629 diff_flush(&diff_opts);
630 clear_pathspec(&diff_opts.pathspec);
631 return porigin;
635 * We have an origin -- find the path that corresponds to it in its
636 * parent and return an origin structure to represent it.
638 static struct blame_origin *find_rename(struct repository *r,
639 struct commit *parent,
640 struct blame_origin *origin)
642 struct blame_origin *porigin = NULL;
643 struct diff_options diff_opts;
644 int i;
646 repo_diff_setup(r, &diff_opts);
647 diff_opts.flags.recursive = 1;
648 diff_opts.detect_rename = DIFF_DETECT_RENAME;
649 diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;
650 diff_opts.single_follow = origin->path;
651 diff_setup_done(&diff_opts);
653 if (is_null_oid(&origin->commit->object.oid))
654 do_diff_cache(get_commit_tree_oid(parent), &diff_opts);
655 else
656 diff_tree_oid(get_commit_tree_oid(parent),
657 get_commit_tree_oid(origin->commit),
658 "", &diff_opts);
659 diffcore_std(&diff_opts);
661 for (i = 0; i < diff_queued_diff.nr; i++) {
662 struct diff_filepair *p = diff_queued_diff.queue[i];
663 if ((p->status == 'R' || p->status == 'C') &&
664 !strcmp(p->two->path, origin->path)) {
665 porigin = get_origin(parent, p->one->path);
666 oidcpy(&porigin->blob_oid, &p->one->oid);
667 porigin->mode = p->one->mode;
668 break;
671 diff_flush(&diff_opts);
672 clear_pathspec(&diff_opts.pathspec);
673 return porigin;
677 * Append a new blame entry to a given output queue.
679 static void add_blame_entry(struct blame_entry ***queue,
680 const struct blame_entry *src)
682 struct blame_entry *e = xmalloc(sizeof(*e));
683 memcpy(e, src, sizeof(*e));
684 blame_origin_incref(e->suspect);
686 e->next = **queue;
687 **queue = e;
688 *queue = &e->next;
692 * src typically is on-stack; we want to copy the information in it to
693 * a malloced blame_entry that gets added to the given queue. The
694 * origin of dst loses a refcnt.
696 static void dup_entry(struct blame_entry ***queue,
697 struct blame_entry *dst, struct blame_entry *src)
699 blame_origin_incref(src->suspect);
700 blame_origin_decref(dst->suspect);
701 memcpy(dst, src, sizeof(*src));
702 dst->next = **queue;
703 **queue = dst;
704 *queue = &dst->next;
707 const char *blame_nth_line(struct blame_scoreboard *sb, long lno)
709 return sb->final_buf + sb->lineno[lno];
713 * It is known that lines between tlno to same came from parent, and e
714 * has an overlap with that range. it also is known that parent's
715 * line plno corresponds to e's line tlno.
717 * <---- e ----->
718 * <------>
719 * <------------>
720 * <------------>
721 * <------------------>
723 * Split e into potentially three parts; before this chunk, the chunk
724 * to be blamed for the parent, and after that portion.
726 static void split_overlap(struct blame_entry *split,
727 struct blame_entry *e,
728 int tlno, int plno, int same,
729 struct blame_origin *parent)
731 int chunk_end_lno;
732 memset(split, 0, sizeof(struct blame_entry [3]));
734 if (e->s_lno < tlno) {
735 /* there is a pre-chunk part not blamed on parent */
736 split[0].suspect = blame_origin_incref(e->suspect);
737 split[0].lno = e->lno;
738 split[0].s_lno = e->s_lno;
739 split[0].num_lines = tlno - e->s_lno;
740 split[1].lno = e->lno + tlno - e->s_lno;
741 split[1].s_lno = plno;
743 else {
744 split[1].lno = e->lno;
745 split[1].s_lno = plno + (e->s_lno - tlno);
748 if (same < e->s_lno + e->num_lines) {
749 /* there is a post-chunk part not blamed on parent */
750 split[2].suspect = blame_origin_incref(e->suspect);
751 split[2].lno = e->lno + (same - e->s_lno);
752 split[2].s_lno = e->s_lno + (same - e->s_lno);
753 split[2].num_lines = e->s_lno + e->num_lines - same;
754 chunk_end_lno = split[2].lno;
756 else
757 chunk_end_lno = e->lno + e->num_lines;
758 split[1].num_lines = chunk_end_lno - split[1].lno;
761 * if it turns out there is nothing to blame the parent for,
762 * forget about the splitting. !split[1].suspect signals this.
764 if (split[1].num_lines < 1)
765 return;
766 split[1].suspect = blame_origin_incref(parent);
770 * split_overlap() divided an existing blame e into up to three parts
771 * in split. Any assigned blame is moved to queue to
772 * reflect the split.
774 static void split_blame(struct blame_entry ***blamed,
775 struct blame_entry ***unblamed,
776 struct blame_entry *split,
777 struct blame_entry *e)
779 if (split[0].suspect && split[2].suspect) {
780 /* The first part (reuse storage for the existing entry e) */
781 dup_entry(unblamed, e, &split[0]);
783 /* The last part -- me */
784 add_blame_entry(unblamed, &split[2]);
786 /* ... and the middle part -- parent */
787 add_blame_entry(blamed, &split[1]);
789 else if (!split[0].suspect && !split[2].suspect)
791 * The parent covers the entire area; reuse storage for
792 * e and replace it with the parent.
794 dup_entry(blamed, e, &split[1]);
795 else if (split[0].suspect) {
796 /* me and then parent */
797 dup_entry(unblamed, e, &split[0]);
798 add_blame_entry(blamed, &split[1]);
800 else {
801 /* parent and then me */
802 dup_entry(blamed, e, &split[1]);
803 add_blame_entry(unblamed, &split[2]);
808 * After splitting the blame, the origins used by the
809 * on-stack blame_entry should lose one refcnt each.
811 static void decref_split(struct blame_entry *split)
813 int i;
815 for (i = 0; i < 3; i++)
816 blame_origin_decref(split[i].suspect);
820 * reverse_blame reverses the list given in head, appending tail.
821 * That allows us to build lists in reverse order, then reverse them
822 * afterwards. This can be faster than building the list in proper
823 * order right away. The reason is that building in proper order
824 * requires writing a link in the _previous_ element, while building
825 * in reverse order just requires placing the list head into the
826 * _current_ element.
829 static struct blame_entry *reverse_blame(struct blame_entry *head,
830 struct blame_entry *tail)
832 while (head) {
833 struct blame_entry *next = head->next;
834 head->next = tail;
835 tail = head;
836 head = next;
838 return tail;
842 * Process one hunk from the patch between the current suspect for
843 * blame_entry e and its parent. This first blames any unfinished
844 * entries before the chunk (which is where target and parent start
845 * differing) on the parent, and then splits blame entries at the
846 * start and at the end of the difference region. Since use of -M and
847 * -C options may lead to overlapping/duplicate source line number
848 * ranges, all we can rely on from sorting/merging is the order of the
849 * first suspect line number.
851 static void blame_chunk(struct blame_entry ***dstq, struct blame_entry ***srcq,
852 int tlno, int offset, int same,
853 struct blame_origin *parent)
855 struct blame_entry *e = **srcq;
856 struct blame_entry *samep = NULL, *diffp = NULL;
858 while (e && e->s_lno < tlno) {
859 struct blame_entry *next = e->next;
861 * current record starts before differing portion. If
862 * it reaches into it, we need to split it up and
863 * examine the second part separately.
865 if (e->s_lno + e->num_lines > tlno) {
866 /* Move second half to a new record */
867 int len = tlno - e->s_lno;
868 struct blame_entry *n = xcalloc(1, sizeof (struct blame_entry));
869 n->suspect = e->suspect;
870 n->lno = e->lno + len;
871 n->s_lno = e->s_lno + len;
872 n->num_lines = e->num_lines - len;
873 e->num_lines = len;
874 e->score = 0;
875 /* Push new record to diffp */
876 n->next = diffp;
877 diffp = n;
878 } else
879 blame_origin_decref(e->suspect);
880 /* Pass blame for everything before the differing
881 * chunk to the parent */
882 e->suspect = blame_origin_incref(parent);
883 e->s_lno += offset;
884 e->next = samep;
885 samep = e;
886 e = next;
889 * As we don't know how much of a common stretch after this
890 * diff will occur, the currently blamed parts are all that we
891 * can assign to the parent for now.
894 if (samep) {
895 **dstq = reverse_blame(samep, **dstq);
896 *dstq = &samep->next;
899 * Prepend the split off portions: everything after e starts
900 * after the blameable portion.
902 e = reverse_blame(diffp, e);
905 * Now retain records on the target while parts are different
906 * from the parent.
908 samep = NULL;
909 diffp = NULL;
910 while (e && e->s_lno < same) {
911 struct blame_entry *next = e->next;
914 * If current record extends into sameness, need to split.
916 if (e->s_lno + e->num_lines > same) {
918 * Move second half to a new record to be
919 * processed by later chunks
921 int len = same - e->s_lno;
922 struct blame_entry *n = xcalloc(1, sizeof (struct blame_entry));
923 n->suspect = blame_origin_incref(e->suspect);
924 n->lno = e->lno + len;
925 n->s_lno = e->s_lno + len;
926 n->num_lines = e->num_lines - len;
927 e->num_lines = len;
928 e->score = 0;
929 /* Push new record to samep */
930 n->next = samep;
931 samep = n;
933 e->next = diffp;
934 diffp = e;
935 e = next;
937 **srcq = reverse_blame(diffp, reverse_blame(samep, e));
938 /* Move across elements that are in the unblamable portion */
939 if (diffp)
940 *srcq = &diffp->next;
943 struct blame_chunk_cb_data {
944 struct blame_origin *parent;
945 long offset;
946 struct blame_entry **dstq;
947 struct blame_entry **srcq;
950 /* diff chunks are from parent to target */
951 static int blame_chunk_cb(long start_a, long count_a,
952 long start_b, long count_b, void *data)
954 struct blame_chunk_cb_data *d = data;
955 if (start_a - start_b != d->offset)
956 die("internal error in blame::blame_chunk_cb");
957 blame_chunk(&d->dstq, &d->srcq, start_b, start_a - start_b,
958 start_b + count_b, d->parent);
959 d->offset = start_a + count_a - (start_b + count_b);
960 return 0;
964 * We are looking at the origin 'target' and aiming to pass blame
965 * for the lines it is suspected to its parent. Run diff to find
966 * which lines came from parent and pass blame for them.
968 static void pass_blame_to_parent(struct blame_scoreboard *sb,
969 struct blame_origin *target,
970 struct blame_origin *parent)
972 mmfile_t file_p, file_o;
973 struct blame_chunk_cb_data d;
974 struct blame_entry *newdest = NULL;
976 if (!target->suspects)
977 return; /* nothing remains for this target */
979 d.parent = parent;
980 d.offset = 0;
981 d.dstq = &newdest; d.srcq = &target->suspects;
983 fill_origin_blob(&sb->revs->diffopt, parent, &file_p, &sb->num_read_blob);
984 fill_origin_blob(&sb->revs->diffopt, target, &file_o, &sb->num_read_blob);
985 sb->num_get_patch++;
987 if (diff_hunks(&file_p, &file_o, blame_chunk_cb, &d, sb->xdl_opts))
988 die("unable to generate diff (%s -> %s)",
989 oid_to_hex(&parent->commit->object.oid),
990 oid_to_hex(&target->commit->object.oid));
991 /* The rest are the same as the parent */
992 blame_chunk(&d.dstq, &d.srcq, INT_MAX, d.offset, INT_MAX, parent);
993 *d.dstq = NULL;
994 queue_blames(sb, parent, newdest);
996 return;
1000 * The lines in blame_entry after splitting blames many times can become
1001 * very small and trivial, and at some point it becomes pointless to
1002 * blame the parents. E.g. "\t\t}\n\t}\n\n" appears everywhere in any
1003 * ordinary C program, and it is not worth to say it was copied from
1004 * totally unrelated file in the parent.
1006 * Compute how trivial the lines in the blame_entry are.
1008 unsigned blame_entry_score(struct blame_scoreboard *sb, struct blame_entry *e)
1010 unsigned score;
1011 const char *cp, *ep;
1013 if (e->score)
1014 return e->score;
1016 score = 1;
1017 cp = blame_nth_line(sb, e->lno);
1018 ep = blame_nth_line(sb, e->lno + e->num_lines);
1019 while (cp < ep) {
1020 unsigned ch = *((unsigned char *)cp);
1021 if (isalnum(ch))
1022 score++;
1023 cp++;
1025 e->score = score;
1026 return score;
1030 * best_so_far[] and potential[] are both a split of an existing blame_entry
1031 * that passes blame to the parent. Maintain best_so_far the best split so
1032 * far, by comparing potential and best_so_far and copying potential into
1033 * bst_so_far as needed.
1035 static void copy_split_if_better(struct blame_scoreboard *sb,
1036 struct blame_entry *best_so_far,
1037 struct blame_entry *potential)
1039 int i;
1041 if (!potential[1].suspect)
1042 return;
1043 if (best_so_far[1].suspect) {
1044 if (blame_entry_score(sb, &potential[1]) <
1045 blame_entry_score(sb, &best_so_far[1]))
1046 return;
1049 for (i = 0; i < 3; i++)
1050 blame_origin_incref(potential[i].suspect);
1051 decref_split(best_so_far);
1052 memcpy(best_so_far, potential, sizeof(struct blame_entry[3]));
1056 * We are looking at a part of the final image represented by
1057 * ent (tlno and same are offset by ent->s_lno).
1058 * tlno is where we are looking at in the final image.
1059 * up to (but not including) same match preimage.
1060 * plno is where we are looking at in the preimage.
1062 * <-------------- final image ---------------------->
1063 * <------ent------>
1064 * ^tlno ^same
1065 * <---------preimage----->
1066 * ^plno
1068 * All line numbers are 0-based.
1070 static void handle_split(struct blame_scoreboard *sb,
1071 struct blame_entry *ent,
1072 int tlno, int plno, int same,
1073 struct blame_origin *parent,
1074 struct blame_entry *split)
1076 if (ent->num_lines <= tlno)
1077 return;
1078 if (tlno < same) {
1079 struct blame_entry potential[3];
1080 tlno += ent->s_lno;
1081 same += ent->s_lno;
1082 split_overlap(potential, ent, tlno, plno, same, parent);
1083 copy_split_if_better(sb, split, potential);
1084 decref_split(potential);
1088 struct handle_split_cb_data {
1089 struct blame_scoreboard *sb;
1090 struct blame_entry *ent;
1091 struct blame_origin *parent;
1092 struct blame_entry *split;
1093 long plno;
1094 long tlno;
1097 static int handle_split_cb(long start_a, long count_a,
1098 long start_b, long count_b, void *data)
1100 struct handle_split_cb_data *d = data;
1101 handle_split(d->sb, d->ent, d->tlno, d->plno, start_b, d->parent,
1102 d->split);
1103 d->plno = start_a + count_a;
1104 d->tlno = start_b + count_b;
1105 return 0;
1109 * Find the lines from parent that are the same as ent so that
1110 * we can pass blames to it. file_p has the blob contents for
1111 * the parent.
1113 static void find_copy_in_blob(struct blame_scoreboard *sb,
1114 struct blame_entry *ent,
1115 struct blame_origin *parent,
1116 struct blame_entry *split,
1117 mmfile_t *file_p)
1119 const char *cp;
1120 mmfile_t file_o;
1121 struct handle_split_cb_data d;
1123 memset(&d, 0, sizeof(d));
1124 d.sb = sb; d.ent = ent; d.parent = parent; d.split = split;
1126 * Prepare mmfile that contains only the lines in ent.
1128 cp = blame_nth_line(sb, ent->lno);
1129 file_o.ptr = (char *) cp;
1130 file_o.size = blame_nth_line(sb, ent->lno + ent->num_lines) - cp;
1133 * file_o is a part of final image we are annotating.
1134 * file_p partially may match that image.
1136 memset(split, 0, sizeof(struct blame_entry [3]));
1137 if (diff_hunks(file_p, &file_o, handle_split_cb, &d, sb->xdl_opts))
1138 die("unable to generate diff (%s)",
1139 oid_to_hex(&parent->commit->object.oid));
1140 /* remainder, if any, all match the preimage */
1141 handle_split(sb, ent, d.tlno, d.plno, ent->num_lines, parent, split);
1144 /* Move all blame entries from list *source that have a score smaller
1145 * than score_min to the front of list *small.
1146 * Returns a pointer to the link pointing to the old head of the small list.
1149 static struct blame_entry **filter_small(struct blame_scoreboard *sb,
1150 struct blame_entry **small,
1151 struct blame_entry **source,
1152 unsigned score_min)
1154 struct blame_entry *p = *source;
1155 struct blame_entry *oldsmall = *small;
1156 while (p) {
1157 if (blame_entry_score(sb, p) <= score_min) {
1158 *small = p;
1159 small = &p->next;
1160 p = *small;
1161 } else {
1162 *source = p;
1163 source = &p->next;
1164 p = *source;
1167 *small = oldsmall;
1168 *source = NULL;
1169 return small;
1173 * See if lines currently target is suspected for can be attributed to
1174 * parent.
1176 static void find_move_in_parent(struct blame_scoreboard *sb,
1177 struct blame_entry ***blamed,
1178 struct blame_entry **toosmall,
1179 struct blame_origin *target,
1180 struct blame_origin *parent)
1182 struct blame_entry *e, split[3];
1183 struct blame_entry *unblamed = target->suspects;
1184 struct blame_entry *leftover = NULL;
1185 mmfile_t file_p;
1187 if (!unblamed)
1188 return; /* nothing remains for this target */
1190 fill_origin_blob(&sb->revs->diffopt, parent, &file_p, &sb->num_read_blob);
1191 if (!file_p.ptr)
1192 return;
1194 /* At each iteration, unblamed has a NULL-terminated list of
1195 * entries that have not yet been tested for blame. leftover
1196 * contains the reversed list of entries that have been tested
1197 * without being assignable to the parent.
1199 do {
1200 struct blame_entry **unblamedtail = &unblamed;
1201 struct blame_entry *next;
1202 for (e = unblamed; e; e = next) {
1203 next = e->next;
1204 find_copy_in_blob(sb, e, parent, split, &file_p);
1205 if (split[1].suspect &&
1206 sb->move_score < blame_entry_score(sb, &split[1])) {
1207 split_blame(blamed, &unblamedtail, split, e);
1208 } else {
1209 e->next = leftover;
1210 leftover = e;
1212 decref_split(split);
1214 *unblamedtail = NULL;
1215 toosmall = filter_small(sb, toosmall, &unblamed, sb->move_score);
1216 } while (unblamed);
1217 target->suspects = reverse_blame(leftover, NULL);
1220 struct blame_list {
1221 struct blame_entry *ent;
1222 struct blame_entry split[3];
1226 * Count the number of entries the target is suspected for,
1227 * and prepare a list of entry and the best split.
1229 static struct blame_list *setup_blame_list(struct blame_entry *unblamed,
1230 int *num_ents_p)
1232 struct blame_entry *e;
1233 int num_ents, i;
1234 struct blame_list *blame_list = NULL;
1236 for (e = unblamed, num_ents = 0; e; e = e->next)
1237 num_ents++;
1238 if (num_ents) {
1239 blame_list = xcalloc(num_ents, sizeof(struct blame_list));
1240 for (e = unblamed, i = 0; e; e = e->next)
1241 blame_list[i++].ent = e;
1243 *num_ents_p = num_ents;
1244 return blame_list;
1248 * For lines target is suspected for, see if we can find code movement
1249 * across file boundary from the parent commit. porigin is the path
1250 * in the parent we already tried.
1252 static void find_copy_in_parent(struct blame_scoreboard *sb,
1253 struct blame_entry ***blamed,
1254 struct blame_entry **toosmall,
1255 struct blame_origin *target,
1256 struct commit *parent,
1257 struct blame_origin *porigin,
1258 int opt)
1260 struct diff_options diff_opts;
1261 int i, j;
1262 struct blame_list *blame_list;
1263 int num_ents;
1264 struct blame_entry *unblamed = target->suspects;
1265 struct blame_entry *leftover = NULL;
1267 if (!unblamed)
1268 return; /* nothing remains for this target */
1270 repo_diff_setup(sb->repo, &diff_opts);
1271 diff_opts.flags.recursive = 1;
1272 diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;
1274 diff_setup_done(&diff_opts);
1276 /* Try "find copies harder" on new path if requested;
1277 * we do not want to use diffcore_rename() actually to
1278 * match things up; find_copies_harder is set only to
1279 * force diff_tree_oid() to feed all filepairs to diff_queue,
1280 * and this code needs to be after diff_setup_done(), which
1281 * usually makes find-copies-harder imply copy detection.
1283 if ((opt & PICKAXE_BLAME_COPY_HARDEST)
1284 || ((opt & PICKAXE_BLAME_COPY_HARDER)
1285 && (!porigin || strcmp(target->path, porigin->path))))
1286 diff_opts.flags.find_copies_harder = 1;
1288 if (is_null_oid(&target->commit->object.oid))
1289 do_diff_cache(get_commit_tree_oid(parent), &diff_opts);
1290 else
1291 diff_tree_oid(get_commit_tree_oid(parent),
1292 get_commit_tree_oid(target->commit),
1293 "", &diff_opts);
1295 if (!diff_opts.flags.find_copies_harder)
1296 diffcore_std(&diff_opts);
1298 do {
1299 struct blame_entry **unblamedtail = &unblamed;
1300 blame_list = setup_blame_list(unblamed, &num_ents);
1302 for (i = 0; i < diff_queued_diff.nr; i++) {
1303 struct diff_filepair *p = diff_queued_diff.queue[i];
1304 struct blame_origin *norigin;
1305 mmfile_t file_p;
1306 struct blame_entry potential[3];
1308 if (!DIFF_FILE_VALID(p->one))
1309 continue; /* does not exist in parent */
1310 if (S_ISGITLINK(p->one->mode))
1311 continue; /* ignore git links */
1312 if (porigin && !strcmp(p->one->path, porigin->path))
1313 /* find_move already dealt with this path */
1314 continue;
1316 norigin = get_origin(parent, p->one->path);
1317 oidcpy(&norigin->blob_oid, &p->one->oid);
1318 norigin->mode = p->one->mode;
1319 fill_origin_blob(&sb->revs->diffopt, norigin, &file_p, &sb->num_read_blob);
1320 if (!file_p.ptr)
1321 continue;
1323 for (j = 0; j < num_ents; j++) {
1324 find_copy_in_blob(sb, blame_list[j].ent,
1325 norigin, potential, &file_p);
1326 copy_split_if_better(sb, blame_list[j].split,
1327 potential);
1328 decref_split(potential);
1330 blame_origin_decref(norigin);
1333 for (j = 0; j < num_ents; j++) {
1334 struct blame_entry *split = blame_list[j].split;
1335 if (split[1].suspect &&
1336 sb->copy_score < blame_entry_score(sb, &split[1])) {
1337 split_blame(blamed, &unblamedtail, split,
1338 blame_list[j].ent);
1339 } else {
1340 blame_list[j].ent->next = leftover;
1341 leftover = blame_list[j].ent;
1343 decref_split(split);
1345 free(blame_list);
1346 *unblamedtail = NULL;
1347 toosmall = filter_small(sb, toosmall, &unblamed, sb->copy_score);
1348 } while (unblamed);
1349 target->suspects = reverse_blame(leftover, NULL);
1350 diff_flush(&diff_opts);
1351 clear_pathspec(&diff_opts.pathspec);
1355 * The blobs of origin and porigin exactly match, so everything
1356 * origin is suspected for can be blamed on the parent.
1358 static void pass_whole_blame(struct blame_scoreboard *sb,
1359 struct blame_origin *origin, struct blame_origin *porigin)
1361 struct blame_entry *e, *suspects;
1363 if (!porigin->file.ptr && origin->file.ptr) {
1364 /* Steal its file */
1365 porigin->file = origin->file;
1366 origin->file.ptr = NULL;
1368 suspects = origin->suspects;
1369 origin->suspects = NULL;
1370 for (e = suspects; e; e = e->next) {
1371 blame_origin_incref(porigin);
1372 blame_origin_decref(e->suspect);
1373 e->suspect = porigin;
1375 queue_blames(sb, porigin, suspects);
1379 * We pass blame from the current commit to its parents. We keep saying
1380 * "parent" (and "porigin"), but what we mean is to find scapegoat to
1381 * exonerate ourselves.
1383 static struct commit_list *first_scapegoat(struct rev_info *revs, struct commit *commit,
1384 int reverse)
1386 if (!reverse) {
1387 if (revs->first_parent_only &&
1388 commit->parents &&
1389 commit->parents->next) {
1390 free_commit_list(commit->parents->next);
1391 commit->parents->next = NULL;
1393 return commit->parents;
1395 return lookup_decoration(&revs->children, &commit->object);
1398 static int num_scapegoats(struct rev_info *revs, struct commit *commit, int reverse)
1400 struct commit_list *l = first_scapegoat(revs, commit, reverse);
1401 return commit_list_count(l);
1404 /* Distribute collected unsorted blames to the respected sorted lists
1405 * in the various origins.
1407 static void distribute_blame(struct blame_scoreboard *sb, struct blame_entry *blamed)
1409 blamed = llist_mergesort(blamed, get_next_blame, set_next_blame,
1410 compare_blame_suspect);
1411 while (blamed)
1413 struct blame_origin *porigin = blamed->suspect;
1414 struct blame_entry *suspects = NULL;
1415 do {
1416 struct blame_entry *next = blamed->next;
1417 blamed->next = suspects;
1418 suspects = blamed;
1419 blamed = next;
1420 } while (blamed && blamed->suspect == porigin);
1421 suspects = reverse_blame(suspects, NULL);
1422 queue_blames(sb, porigin, suspects);
1426 #define MAXSG 16
1428 static void pass_blame(struct blame_scoreboard *sb, struct blame_origin *origin, int opt)
1430 struct rev_info *revs = sb->revs;
1431 int i, pass, num_sg;
1432 struct commit *commit = origin->commit;
1433 struct commit_list *sg;
1434 struct blame_origin *sg_buf[MAXSG];
1435 struct blame_origin *porigin, **sg_origin = sg_buf;
1436 struct blame_entry *toosmall = NULL;
1437 struct blame_entry *blames, **blametail = &blames;
1439 num_sg = num_scapegoats(revs, commit, sb->reverse);
1440 if (!num_sg)
1441 goto finish;
1442 else if (num_sg < ARRAY_SIZE(sg_buf))
1443 memset(sg_buf, 0, sizeof(sg_buf));
1444 else
1445 sg_origin = xcalloc(num_sg, sizeof(*sg_origin));
1448 * The first pass looks for unrenamed path to optimize for
1449 * common cases, then we look for renames in the second pass.
1451 for (pass = 0; pass < 2 - sb->no_whole_file_rename; pass++) {
1452 struct blame_origin *(*find)(struct repository *, struct commit *, struct blame_origin *);
1453 find = pass ? find_rename : find_origin;
1455 for (i = 0, sg = first_scapegoat(revs, commit, sb->reverse);
1456 i < num_sg && sg;
1457 sg = sg->next, i++) {
1458 struct commit *p = sg->item;
1459 int j, same;
1461 if (sg_origin[i])
1462 continue;
1463 if (parse_commit(p))
1464 continue;
1465 porigin = find(sb->repo, p, origin);
1466 if (!porigin)
1467 continue;
1468 if (oideq(&porigin->blob_oid, &origin->blob_oid)) {
1469 pass_whole_blame(sb, origin, porigin);
1470 blame_origin_decref(porigin);
1471 goto finish;
1473 for (j = same = 0; j < i; j++)
1474 if (sg_origin[j] &&
1475 oideq(&sg_origin[j]->blob_oid, &porigin->blob_oid)) {
1476 same = 1;
1477 break;
1479 if (!same)
1480 sg_origin[i] = porigin;
1481 else
1482 blame_origin_decref(porigin);
1486 sb->num_commits++;
1487 for (i = 0, sg = first_scapegoat(revs, commit, sb->reverse);
1488 i < num_sg && sg;
1489 sg = sg->next, i++) {
1490 struct blame_origin *porigin = sg_origin[i];
1491 if (!porigin)
1492 continue;
1493 if (!origin->previous) {
1494 blame_origin_incref(porigin);
1495 origin->previous = porigin;
1497 pass_blame_to_parent(sb, origin, porigin);
1498 if (!origin->suspects)
1499 goto finish;
1503 * Optionally find moves in parents' files.
1505 if (opt & PICKAXE_BLAME_MOVE) {
1506 filter_small(sb, &toosmall, &origin->suspects, sb->move_score);
1507 if (origin->suspects) {
1508 for (i = 0, sg = first_scapegoat(revs, commit, sb->reverse);
1509 i < num_sg && sg;
1510 sg = sg->next, i++) {
1511 struct blame_origin *porigin = sg_origin[i];
1512 if (!porigin)
1513 continue;
1514 find_move_in_parent(sb, &blametail, &toosmall, origin, porigin);
1515 if (!origin->suspects)
1516 break;
1522 * Optionally find copies from parents' files.
1524 if (opt & PICKAXE_BLAME_COPY) {
1525 if (sb->copy_score > sb->move_score)
1526 filter_small(sb, &toosmall, &origin->suspects, sb->copy_score);
1527 else if (sb->copy_score < sb->move_score) {
1528 origin->suspects = blame_merge(origin->suspects, toosmall);
1529 toosmall = NULL;
1530 filter_small(sb, &toosmall, &origin->suspects, sb->copy_score);
1532 if (!origin->suspects)
1533 goto finish;
1535 for (i = 0, sg = first_scapegoat(revs, commit, sb->reverse);
1536 i < num_sg && sg;
1537 sg = sg->next, i++) {
1538 struct blame_origin *porigin = sg_origin[i];
1539 find_copy_in_parent(sb, &blametail, &toosmall,
1540 origin, sg->item, porigin, opt);
1541 if (!origin->suspects)
1542 goto finish;
1546 finish:
1547 *blametail = NULL;
1548 distribute_blame(sb, blames);
1550 * prepend toosmall to origin->suspects
1552 * There is no point in sorting: this ends up on a big
1553 * unsorted list in the caller anyway.
1555 if (toosmall) {
1556 struct blame_entry **tail = &toosmall;
1557 while (*tail)
1558 tail = &(*tail)->next;
1559 *tail = origin->suspects;
1560 origin->suspects = toosmall;
1562 for (i = 0; i < num_sg; i++) {
1563 if (sg_origin[i]) {
1564 drop_origin_blob(sg_origin[i]);
1565 blame_origin_decref(sg_origin[i]);
1568 drop_origin_blob(origin);
1569 if (sg_buf != sg_origin)
1570 free(sg_origin);
1574 * The main loop -- while we have blobs with lines whose true origin
1575 * is still unknown, pick one blob, and allow its lines to pass blames
1576 * to its parents. */
1577 void assign_blame(struct blame_scoreboard *sb, int opt)
1579 struct rev_info *revs = sb->revs;
1580 struct commit *commit = prio_queue_get(&sb->commits);
1582 while (commit) {
1583 struct blame_entry *ent;
1584 struct blame_origin *suspect = get_blame_suspects(commit);
1586 /* find one suspect to break down */
1587 while (suspect && !suspect->suspects)
1588 suspect = suspect->next;
1590 if (!suspect) {
1591 commit = prio_queue_get(&sb->commits);
1592 continue;
1595 assert(commit == suspect->commit);
1598 * We will use this suspect later in the loop,
1599 * so hold onto it in the meantime.
1601 blame_origin_incref(suspect);
1602 parse_commit(commit);
1603 if (sb->reverse ||
1604 (!(commit->object.flags & UNINTERESTING) &&
1605 !(revs->max_age != -1 && commit->date < revs->max_age)))
1606 pass_blame(sb, suspect, opt);
1607 else {
1608 commit->object.flags |= UNINTERESTING;
1609 if (commit->object.parsed)
1610 mark_parents_uninteresting(commit);
1612 /* treat root commit as boundary */
1613 if (!commit->parents && !sb->show_root)
1614 commit->object.flags |= UNINTERESTING;
1616 /* Take responsibility for the remaining entries */
1617 ent = suspect->suspects;
1618 if (ent) {
1619 suspect->guilty = 1;
1620 for (;;) {
1621 struct blame_entry *next = ent->next;
1622 if (sb->found_guilty_entry)
1623 sb->found_guilty_entry(ent, sb->found_guilty_entry_data);
1624 if (next) {
1625 ent = next;
1626 continue;
1628 ent->next = sb->ent;
1629 sb->ent = suspect->suspects;
1630 suspect->suspects = NULL;
1631 break;
1634 blame_origin_decref(suspect);
1636 if (sb->debug) /* sanity */
1637 sanity_check_refcnt(sb);
1641 static const char *get_next_line(const char *start, const char *end)
1643 const char *nl = memchr(start, '\n', end - start);
1644 return nl ? nl + 1 : end;
1648 * To allow quick access to the contents of nth line in the
1649 * final image, prepare an index in the scoreboard.
1651 static int prepare_lines(struct blame_scoreboard *sb)
1653 const char *buf = sb->final_buf;
1654 unsigned long len = sb->final_buf_size;
1655 const char *end = buf + len;
1656 const char *p;
1657 int *lineno;
1658 int num = 0;
1660 for (p = buf; p < end; p = get_next_line(p, end))
1661 num++;
1663 ALLOC_ARRAY(sb->lineno, num + 1);
1664 lineno = sb->lineno;
1666 for (p = buf; p < end; p = get_next_line(p, end))
1667 *lineno++ = p - buf;
1669 *lineno = len;
1671 sb->num_lines = num;
1672 return sb->num_lines;
1675 static struct commit *find_single_final(struct rev_info *revs,
1676 const char **name_p)
1678 int i;
1679 struct commit *found = NULL;
1680 const char *name = NULL;
1682 for (i = 0; i < revs->pending.nr; i++) {
1683 struct object *obj = revs->pending.objects[i].item;
1684 if (obj->flags & UNINTERESTING)
1685 continue;
1686 obj = deref_tag(revs->repo, obj, NULL, 0);
1687 if (obj->type != OBJ_COMMIT)
1688 die("Non commit %s?", revs->pending.objects[i].name);
1689 if (found)
1690 die("More than one commit to dig from %s and %s?",
1691 revs->pending.objects[i].name, name);
1692 found = (struct commit *)obj;
1693 name = revs->pending.objects[i].name;
1695 if (name_p)
1696 *name_p = xstrdup_or_null(name);
1697 return found;
1700 static struct commit *dwim_reverse_initial(struct rev_info *revs,
1701 const char **name_p)
1704 * DWIM "git blame --reverse ONE -- PATH" as
1705 * "git blame --reverse ONE..HEAD -- PATH" but only do so
1706 * when it makes sense.
1708 struct object *obj;
1709 struct commit *head_commit;
1710 struct object_id head_oid;
1712 if (revs->pending.nr != 1)
1713 return NULL;
1715 /* Is that sole rev a committish? */
1716 obj = revs->pending.objects[0].item;
1717 obj = deref_tag(revs->repo, obj, NULL, 0);
1718 if (obj->type != OBJ_COMMIT)
1719 return NULL;
1721 /* Do we have HEAD? */
1722 if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, &head_oid, NULL))
1723 return NULL;
1724 head_commit = lookup_commit_reference_gently(revs->repo,
1725 &head_oid, 1);
1726 if (!head_commit)
1727 return NULL;
1729 /* Turn "ONE" into "ONE..HEAD" then */
1730 obj->flags |= UNINTERESTING;
1731 add_pending_object(revs, &head_commit->object, "HEAD");
1733 if (name_p)
1734 *name_p = revs->pending.objects[0].name;
1735 return (struct commit *)obj;
1738 static struct commit *find_single_initial(struct rev_info *revs,
1739 const char **name_p)
1741 int i;
1742 struct commit *found = NULL;
1743 const char *name = NULL;
1746 * There must be one and only one negative commit, and it must be
1747 * the boundary.
1749 for (i = 0; i < revs->pending.nr; i++) {
1750 struct object *obj = revs->pending.objects[i].item;
1751 if (!(obj->flags & UNINTERESTING))
1752 continue;
1753 obj = deref_tag(revs->repo, obj, NULL, 0);
1754 if (obj->type != OBJ_COMMIT)
1755 die("Non commit %s?", revs->pending.objects[i].name);
1756 if (found)
1757 die("More than one commit to dig up from, %s and %s?",
1758 revs->pending.objects[i].name, name);
1759 found = (struct commit *) obj;
1760 name = revs->pending.objects[i].name;
1763 if (!name)
1764 found = dwim_reverse_initial(revs, &name);
1765 if (!name)
1766 die("No commit to dig up from?");
1768 if (name_p)
1769 *name_p = xstrdup(name);
1770 return found;
1773 void init_scoreboard(struct blame_scoreboard *sb)
1775 memset(sb, 0, sizeof(struct blame_scoreboard));
1776 sb->move_score = BLAME_DEFAULT_MOVE_SCORE;
1777 sb->copy_score = BLAME_DEFAULT_COPY_SCORE;
1780 void setup_scoreboard(struct blame_scoreboard *sb,
1781 const char *path,
1782 struct blame_origin **orig)
1784 const char *final_commit_name = NULL;
1785 struct blame_origin *o;
1786 struct commit *final_commit = NULL;
1787 enum object_type type;
1789 init_blame_suspects(&blame_suspects);
1791 if (sb->reverse && sb->contents_from)
1792 die(_("--contents and --reverse do not blend well."));
1794 if (!sb->repo)
1795 BUG("repo is NULL");
1797 if (!sb->reverse) {
1798 sb->final = find_single_final(sb->revs, &final_commit_name);
1799 sb->commits.compare = compare_commits_by_commit_date;
1800 } else {
1801 sb->final = find_single_initial(sb->revs, &final_commit_name);
1802 sb->commits.compare = compare_commits_by_reverse_commit_date;
1805 if (sb->final && sb->contents_from)
1806 die(_("cannot use --contents with final commit object name"));
1808 if (sb->reverse && sb->revs->first_parent_only)
1809 sb->revs->children.name = NULL;
1811 if (!sb->final) {
1813 * "--not A B -- path" without anything positive;
1814 * do not default to HEAD, but use the working tree
1815 * or "--contents".
1817 setup_work_tree();
1818 sb->final = fake_working_tree_commit(sb->repo,
1819 &sb->revs->diffopt,
1820 path, sb->contents_from);
1821 add_pending_object(sb->revs, &(sb->final->object), ":");
1824 if (sb->reverse && sb->revs->first_parent_only) {
1825 final_commit = find_single_final(sb->revs, NULL);
1826 if (!final_commit)
1827 die(_("--reverse and --first-parent together require specified latest commit"));
1831 * If we have bottom, this will mark the ancestors of the
1832 * bottom commits we would reach while traversing as
1833 * uninteresting.
1835 if (prepare_revision_walk(sb->revs))
1836 die(_("revision walk setup failed"));
1838 if (sb->reverse && sb->revs->first_parent_only) {
1839 struct commit *c = final_commit;
1841 sb->revs->children.name = "children";
1842 while (c->parents &&
1843 !oideq(&c->object.oid, &sb->final->object.oid)) {
1844 struct commit_list *l = xcalloc(1, sizeof(*l));
1846 l->item = c;
1847 if (add_decoration(&sb->revs->children,
1848 &c->parents->item->object, l))
1849 BUG("not unique item in first-parent chain");
1850 c = c->parents->item;
1853 if (!oideq(&c->object.oid, &sb->final->object.oid))
1854 die(_("--reverse --first-parent together require range along first-parent chain"));
1857 if (is_null_oid(&sb->final->object.oid)) {
1858 o = get_blame_suspects(sb->final);
1859 sb->final_buf = xmemdupz(o->file.ptr, o->file.size);
1860 sb->final_buf_size = o->file.size;
1862 else {
1863 o = get_origin(sb->final, path);
1864 if (fill_blob_sha1_and_mode(sb->repo, o))
1865 die(_("no such path %s in %s"), path, final_commit_name);
1867 if (sb->revs->diffopt.flags.allow_textconv &&
1868 textconv_object(sb->repo, path, o->mode, &o->blob_oid, 1, (char **) &sb->final_buf,
1869 &sb->final_buf_size))
1871 else
1872 sb->final_buf = read_object_file(&o->blob_oid, &type,
1873 &sb->final_buf_size);
1875 if (!sb->final_buf)
1876 die(_("cannot read blob %s for path %s"),
1877 oid_to_hex(&o->blob_oid),
1878 path);
1880 sb->num_read_blob++;
1881 prepare_lines(sb);
1883 if (orig)
1884 *orig = o;
1886 free((char *)final_commit_name);
1891 struct blame_entry *blame_entry_prepend(struct blame_entry *head,
1892 long start, long end,
1893 struct blame_origin *o)
1895 struct blame_entry *new_head = xcalloc(1, sizeof(struct blame_entry));
1896 new_head->lno = start;
1897 new_head->num_lines = end - start;
1898 new_head->suspect = o;
1899 new_head->s_lno = start;
1900 new_head->next = head;
1901 blame_origin_incref(o);
1902 return new_head;