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