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