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