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