4 * Copyright (c) 2006, 2014 by its authors
5 * See COPYING for licensing conditions
14 #include "tree-walk.h"
19 #include "xdiff-interface.h"
20 #include "cache-tree.h"
21 #include "string-list.h"
23 #include "mergesort.h"
24 #include "parse-options.h"
25 #include "prio-queue.h"
28 #include "line-range.h"
32 static char blame_usage[] = N_("git blame [<options>] [<rev-opts>] [<rev>] [--] <file>");
34 static const char *blame_opt_usage[] = {
37 N_("<rev-opts> are documented in git-rev-list(1)"),
41 static int longest_file;
42 static int longest_author;
43 static int max_orig_digits;
44 static int max_digits;
45 static int max_score_digits;
48 static int blank_boundary;
49 static int incremental;
51 static int abbrev = -1;
52 static int no_whole_file_rename;
54 static struct date_mode blame_date_mode = { DATE_ISO8601 };
55 static size_t blame_date_width;
57 static struct string_list mailmap;
64 static int num_read_blob;
65 static int num_get_patch;
66 static int num_commits;
68 #define PICKAXE_BLAME_MOVE 01
69 #define PICKAXE_BLAME_COPY 02
70 #define PICKAXE_BLAME_COPY_HARDER 04
71 #define PICKAXE_BLAME_COPY_HARDEST 010
74 * blame for a blame_entry with score lower than these thresholds
75 * is not passed to the parent using move/copy logic.
77 static unsigned blame_move_score;
78 static unsigned blame_copy_score;
79 #define BLAME_DEFAULT_MOVE_SCORE 20
80 #define BLAME_DEFAULT_COPY_SCORE 40
82 /* Remember to update object flag allocation in object.h */
83 #define METAINFO_SHOWN (1u<<12)
84 #define MORE_THAN_ONE_PATH (1u<<13)
87 * One blob in a commit that is being suspected
91 /* Record preceding blame record for this blob */
92 struct origin *previous;
93 /* origins are put in a list linked via `next' hanging off the
94 * corresponding commit's util field in order to make finding
95 * them fast. The presence in this chain does not count
96 * towards the origin's reference count. It is tempting to
97 * let it count as long as the commit is pending examination,
98 * but even under circumstances where the commit will be
99 * present multiple times in the priority queue of unexamined
100 * commits, processing the first instance will not leave any
101 * work requiring the origin data for the second instance. An
102 * interspersed commit changing that would have to be
103 * preexisting with a different ancestry and with the same
104 * commit date in order to wedge itself between two instances
105 * of the same commit in the priority queue _and_ produce
106 * blame entries relevant for it. While we don't want to let
107 * us get tripped up by this case, it certainly does not seem
108 * worth optimizing for.
111 struct commit *commit;
112 /* `suspects' contains blame entries that may be attributed to
113 * this origin's commit or to parent commits. When a commit
114 * is being processed, all suspects will be moved, either by
115 * assigning them to an origin in a different commit, or by
116 * shipping them to the scoreboard's ent list because they
117 * cannot be attributed to a different commit.
119 struct blame_entry *suspects;
121 unsigned char blob_sha1[20];
123 /* guilty gets set when shipping any suspects to the final
124 * blame list instead of other commits
127 char path[FLEX_ARRAY];
130 static int diff_hunks(mmfile_t *file_a, mmfile_t *file_b, long ctxlen,
131 xdl_emit_hunk_consume_func_t hunk_func, void *cb_data)
134 xdemitconf_t xecfg = {0};
135 xdemitcb_t ecb = {NULL};
137 xpp.flags = xdl_opts;
138 xecfg.ctxlen = ctxlen;
139 xecfg.hunk_func = hunk_func;
141 return xdi_diff(file_a, file_b, &xpp, &xecfg, &ecb);
145 * Prepare diff_filespec and convert it using diff textconv API
146 * if the textconv driver exists.
147 * Return 1 if the conversion succeeds, 0 otherwise.
149 int textconv_object(const char *path,
151 const unsigned char *sha1,
154 unsigned long *buf_size)
156 struct diff_filespec *df;
157 struct userdiff_driver *textconv;
159 df = alloc_filespec(path);
160 fill_filespec(df, sha1, sha1_valid, mode);
161 textconv = get_textconv(df);
167 *buf_size = fill_textconv(textconv, df, buf);
173 * Given an origin, prepare mmfile_t structure to be used by the
176 static void fill_origin_blob(struct diff_options *opt,
177 struct origin *o, mmfile_t *file)
180 enum object_type type;
181 unsigned long file_size;
184 if (DIFF_OPT_TST(opt, ALLOW_TEXTCONV) &&
185 textconv_object(o->path, o->mode, o->blob_sha1, 1, &file->ptr, &file_size))
188 file->ptr = read_sha1_file(o->blob_sha1, &type, &file_size);
189 file->size = file_size;
192 die("Cannot read blob %s for path %s",
193 sha1_to_hex(o->blob_sha1),
202 * Origin is refcounted and usually we keep the blob contents to be
205 static inline struct origin *origin_incref(struct origin *o)
212 static void origin_decref(struct origin *o)
214 if (o && --o->refcnt <= 0) {
215 struct origin *p, *l = NULL;
217 origin_decref(o->previous);
219 /* Should be present exactly once in commit chain */
220 for (p = o->commit->util; p; l = p, p = p->next) {
225 o->commit->util = p->next;
230 die("internal error in blame::origin_decref");
234 static void drop_origin_blob(struct origin *o)
243 * Each group of lines is described by a blame_entry; it can be split
244 * as we pass blame to the parents. They are arranged in linked lists
245 * kept as `suspects' of some unprocessed origin, or entered (when the
246 * blame origin has been finalized) into the scoreboard structure.
247 * While the scoreboard structure is only sorted at the end of
248 * processing (according to final image line number), the lists
249 * attached to an origin are sorted by the target line number.
252 struct blame_entry *next;
254 /* the first line of this group in the final image;
255 * internally all line numbers are 0 based.
259 /* how many lines this group has */
262 /* the commit that introduced this group into the final image */
263 struct origin *suspect;
265 /* the line number of the first line of this group in the
266 * suspect's file; internally all line numbers are 0 based.
270 /* how significant this entry is -- cached to avoid
271 * scanning the lines over and over.
277 * Any merge of blames happens on lists of blames that arrived via
278 * different parents in a single suspect. In this case, we want to
279 * sort according to the suspect line numbers as opposed to the final
280 * image line numbers. The function body is somewhat longish because
281 * it avoids unnecessary writes.
284 static struct blame_entry *blame_merge(struct blame_entry *list1,
285 struct blame_entry *list2)
287 struct blame_entry *p1 = list1, *p2 = list2,
295 if (p1->s_lno <= p2->s_lno) {
298 if ((p1 = *tail) == NULL) {
302 } while (p1->s_lno <= p2->s_lno);
308 if ((p2 = *tail) == NULL) {
312 } while (p1->s_lno > p2->s_lno);
316 if ((p1 = *tail) == NULL) {
320 } while (p1->s_lno <= p2->s_lno);
324 static void *get_next_blame(const void *p)
326 return ((struct blame_entry *)p)->next;
329 static void set_next_blame(void *p1, void *p2)
331 ((struct blame_entry *)p1)->next = p2;
335 * Final image line numbers are all different, so we don't need a
336 * three-way comparison here.
339 static int compare_blame_final(const void *p1, const void *p2)
341 return ((struct blame_entry *)p1)->lno > ((struct blame_entry *)p2)->lno
345 static int compare_blame_suspect(const void *p1, const void *p2)
347 const struct blame_entry *s1 = p1, *s2 = p2;
349 * to allow for collating suspects, we sort according to the
350 * respective pointer value as the primary sorting criterion.
351 * The actual relation is pretty unimportant as long as it
352 * establishes a total order. Comparing as integers gives us
355 if (s1->suspect != s2->suspect)
356 return (intptr_t)s1->suspect > (intptr_t)s2->suspect ? 1 : -1;
357 if (s1->s_lno == s2->s_lno)
359 return s1->s_lno > s2->s_lno ? 1 : -1;
362 static struct blame_entry *blame_sort(struct blame_entry *head,
363 int (*compare_fn)(const void *, const void *))
365 return llist_mergesort (head, get_next_blame, set_next_blame, compare_fn);
368 static int compare_commits_by_reverse_commit_date(const void *a,
372 return -compare_commits_by_commit_date(a, b, c);
376 * The current state of the blame assignment.
379 /* the final commit (i.e. where we started digging from) */
380 struct commit *final;
381 /* Priority queue for commits with unassigned blame records */
382 struct prio_queue commits;
383 struct rev_info *revs;
387 * The contents in the final image.
388 * Used by many functions to obtain contents of the nth line,
389 * indexed with scoreboard.lineno[blame_entry.lno].
391 const char *final_buf;
392 unsigned long final_buf_size;
394 /* linked list of blames */
395 struct blame_entry *ent;
397 /* look-up a line in the final buffer */
402 static void sanity_check_refcnt(struct scoreboard *);
405 * If two blame entries that are next to each other came from
406 * contiguous lines in the same origin (i.e. <commit, path> pair),
407 * merge them together.
409 static void coalesce(struct scoreboard *sb)
411 struct blame_entry *ent, *next;
413 for (ent = sb->ent; ent && (next = ent->next); ent = next) {
414 if (ent->suspect == next->suspect &&
415 ent->s_lno + ent->num_lines == next->s_lno) {
416 ent->num_lines += next->num_lines;
417 ent->next = next->next;
418 origin_decref(next->suspect);
421 next = ent; /* again */
425 if (DEBUG) /* sanity */
426 sanity_check_refcnt(sb);
430 * Merge the given sorted list of blames into a preexisting origin.
431 * If there were no previous blames to that commit, it is entered into
432 * the commit priority queue of the score board.
435 static void queue_blames(struct scoreboard *sb, struct origin *porigin,
436 struct blame_entry *sorted)
438 if (porigin->suspects)
439 porigin->suspects = blame_merge(porigin->suspects, sorted);
442 for (o = porigin->commit->util; o; o = o->next) {
444 porigin->suspects = sorted;
448 porigin->suspects = sorted;
449 prio_queue_put(&sb->commits, porigin->commit);
454 * Given a commit and a path in it, create a new origin structure.
455 * The callers that add blame to the scoreboard should use
456 * get_origin() to obtain shared, refcounted copy instead of calling
457 * this function directly.
459 static struct origin *make_origin(struct commit *commit, const char *path)
462 size_t pathlen = strlen(path) + 1;
463 o = xcalloc(1, sizeof(*o) + pathlen);
466 o->next = commit->util;
468 memcpy(o->path, path, pathlen); /* includes NUL */
473 * Locate an existing origin or create a new one.
474 * This moves the origin to front position in the commit util list.
476 static struct origin *get_origin(struct scoreboard *sb,
477 struct commit *commit,
480 struct origin *o, *l;
482 for (o = commit->util, l = NULL; o; l = o, o = o->next) {
483 if (!strcmp(o->path, path)) {
487 o->next = commit->util;
490 return origin_incref(o);
493 return make_origin(commit, path);
497 * Fill the blob_sha1 field of an origin if it hasn't, so that later
498 * call to fill_origin_blob() can use it to locate the data. blob_sha1
499 * for an origin is also used to pass the blame for the entire file to
500 * the parent to detect the case where a child's blob is identical to
501 * that of its parent's.
503 * This also fills origin->mode for corresponding tree path.
505 static int fill_blob_sha1_and_mode(struct origin *origin)
507 if (!is_null_sha1(origin->blob_sha1))
509 if (get_tree_entry(origin->commit->object.oid.hash,
511 origin->blob_sha1, &origin->mode))
513 if (sha1_object_info(origin->blob_sha1, NULL) != OBJ_BLOB)
517 hashclr(origin->blob_sha1);
518 origin->mode = S_IFINVALID;
523 * We have an origin -- check if the same path exists in the
524 * parent and return an origin structure to represent it.
526 static struct origin *find_origin(struct scoreboard *sb,
527 struct commit *parent,
528 struct origin *origin)
530 struct origin *porigin;
531 struct diff_options diff_opts;
532 const char *paths[2];
534 /* First check any existing origins */
535 for (porigin = parent->util; porigin; porigin = porigin->next)
536 if (!strcmp(porigin->path, origin->path)) {
538 * The same path between origin and its parent
539 * without renaming -- the most common case.
541 return origin_incref (porigin);
544 /* See if the origin->path is different between parent
545 * and origin first. Most of the time they are the
546 * same and diff-tree is fairly efficient about this.
548 diff_setup(&diff_opts);
549 DIFF_OPT_SET(&diff_opts, RECURSIVE);
550 diff_opts.detect_rename = 0;
551 diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;
552 paths[0] = origin->path;
555 parse_pathspec(&diff_opts.pathspec,
556 PATHSPEC_ALL_MAGIC & ~PATHSPEC_LITERAL,
557 PATHSPEC_LITERAL_PATH, "", paths);
558 diff_setup_done(&diff_opts);
560 if (is_null_oid(&origin->commit->object.oid))
561 do_diff_cache(parent->tree->object.oid.hash, &diff_opts);
563 diff_tree_sha1(parent->tree->object.oid.hash,
564 origin->commit->tree->object.oid.hash,
566 diffcore_std(&diff_opts);
568 if (!diff_queued_diff.nr) {
569 /* The path is the same as parent */
570 porigin = get_origin(sb, parent, origin->path);
571 hashcpy(porigin->blob_sha1, origin->blob_sha1);
572 porigin->mode = origin->mode;
575 * Since origin->path is a pathspec, if the parent
576 * commit had it as a directory, we will see a whole
577 * bunch of deletion of files in the directory that we
581 struct diff_filepair *p = NULL;
582 for (i = 0; i < diff_queued_diff.nr; i++) {
584 p = diff_queued_diff.queue[i];
585 name = p->one->path ? p->one->path : p->two->path;
586 if (!strcmp(name, origin->path))
590 die("internal error in blame::find_origin");
593 die("internal error in blame::find_origin (%c)",
596 porigin = get_origin(sb, parent, origin->path);
597 hashcpy(porigin->blob_sha1, p->one->sha1);
598 porigin->mode = p->one->mode;
602 /* Did not exist in parent, or type changed */
606 diff_flush(&diff_opts);
607 free_pathspec(&diff_opts.pathspec);
612 * We have an origin -- find the path that corresponds to it in its
613 * parent and return an origin structure to represent it.
615 static struct origin *find_rename(struct scoreboard *sb,
616 struct commit *parent,
617 struct origin *origin)
619 struct origin *porigin = NULL;
620 struct diff_options diff_opts;
623 diff_setup(&diff_opts);
624 DIFF_OPT_SET(&diff_opts, RECURSIVE);
625 diff_opts.detect_rename = DIFF_DETECT_RENAME;
626 diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;
627 diff_opts.single_follow = origin->path;
628 diff_setup_done(&diff_opts);
630 if (is_null_oid(&origin->commit->object.oid))
631 do_diff_cache(parent->tree->object.oid.hash, &diff_opts);
633 diff_tree_sha1(parent->tree->object.oid.hash,
634 origin->commit->tree->object.oid.hash,
636 diffcore_std(&diff_opts);
638 for (i = 0; i < diff_queued_diff.nr; i++) {
639 struct diff_filepair *p = diff_queued_diff.queue[i];
640 if ((p->status == 'R' || p->status == 'C') &&
641 !strcmp(p->two->path, origin->path)) {
642 porigin = get_origin(sb, parent, p->one->path);
643 hashcpy(porigin->blob_sha1, p->one->sha1);
644 porigin->mode = p->one->mode;
648 diff_flush(&diff_opts);
649 free_pathspec(&diff_opts.pathspec);
654 * Append a new blame entry to a given output queue.
656 static void add_blame_entry(struct blame_entry ***queue, struct blame_entry *e)
658 origin_incref(e->suspect);
666 * src typically is on-stack; we want to copy the information in it to
667 * a malloced blame_entry that gets added to the given queue. The
668 * origin of dst loses a refcnt.
670 static void dup_entry(struct blame_entry ***queue,
671 struct blame_entry *dst, struct blame_entry *src)
673 origin_incref(src->suspect);
674 origin_decref(dst->suspect);
675 memcpy(dst, src, sizeof(*src));
681 static const char *nth_line(struct scoreboard *sb, long lno)
683 return sb->final_buf + sb->lineno[lno];
686 static const char *nth_line_cb(void *data, long lno)
688 return nth_line((struct scoreboard *)data, lno);
692 * It is known that lines between tlno to same came from parent, and e
693 * has an overlap with that range. it also is known that parent's
694 * line plno corresponds to e's line tlno.
700 * <------------------>
702 * Split e into potentially three parts; before this chunk, the chunk
703 * to be blamed for the parent, and after that portion.
705 static void split_overlap(struct blame_entry *split,
706 struct blame_entry *e,
707 int tlno, int plno, int same,
708 struct origin *parent)
711 memset(split, 0, sizeof(struct blame_entry [3]));
713 if (e->s_lno < tlno) {
714 /* there is a pre-chunk part not blamed on parent */
715 split[0].suspect = origin_incref(e->suspect);
716 split[0].lno = e->lno;
717 split[0].s_lno = e->s_lno;
718 split[0].num_lines = tlno - e->s_lno;
719 split[1].lno = e->lno + tlno - e->s_lno;
720 split[1].s_lno = plno;
723 split[1].lno = e->lno;
724 split[1].s_lno = plno + (e->s_lno - tlno);
727 if (same < e->s_lno + e->num_lines) {
728 /* there is a post-chunk part not blamed on parent */
729 split[2].suspect = origin_incref(e->suspect);
730 split[2].lno = e->lno + (same - e->s_lno);
731 split[2].s_lno = e->s_lno + (same - e->s_lno);
732 split[2].num_lines = e->s_lno + e->num_lines - same;
733 chunk_end_lno = split[2].lno;
736 chunk_end_lno = e->lno + e->num_lines;
737 split[1].num_lines = chunk_end_lno - split[1].lno;
740 * if it turns out there is nothing to blame the parent for,
741 * forget about the splitting. !split[1].suspect signals this.
743 if (split[1].num_lines < 1)
745 split[1].suspect = origin_incref(parent);
749 * split_overlap() divided an existing blame e into up to three parts
750 * in split. Any assigned blame is moved to queue to
753 static void split_blame(struct blame_entry ***blamed,
754 struct blame_entry ***unblamed,
755 struct blame_entry *split,
756 struct blame_entry *e)
758 struct blame_entry *new_entry;
760 if (split[0].suspect && split[2].suspect) {
761 /* The first part (reuse storage for the existing entry e) */
762 dup_entry(unblamed, e, &split[0]);
764 /* The last part -- me */
765 new_entry = xmalloc(sizeof(*new_entry));
766 memcpy(new_entry, &(split[2]), sizeof(struct blame_entry));
767 add_blame_entry(unblamed, new_entry);
769 /* ... and the middle part -- parent */
770 new_entry = xmalloc(sizeof(*new_entry));
771 memcpy(new_entry, &(split[1]), sizeof(struct blame_entry));
772 add_blame_entry(blamed, new_entry);
774 else if (!split[0].suspect && !split[2].suspect)
776 * The parent covers the entire area; reuse storage for
777 * e and replace it with the parent.
779 dup_entry(blamed, e, &split[1]);
780 else if (split[0].suspect) {
781 /* me and then parent */
782 dup_entry(unblamed, e, &split[0]);
784 new_entry = xmalloc(sizeof(*new_entry));
785 memcpy(new_entry, &(split[1]), sizeof(struct blame_entry));
786 add_blame_entry(blamed, new_entry);
789 /* parent and then me */
790 dup_entry(blamed, e, &split[1]);
792 new_entry = xmalloc(sizeof(*new_entry));
793 memcpy(new_entry, &(split[2]), sizeof(struct blame_entry));
794 add_blame_entry(unblamed, new_entry);
799 * After splitting the blame, the origins used by the
800 * on-stack blame_entry should lose one refcnt each.
802 static void decref_split(struct blame_entry *split)
806 for (i = 0; i < 3; i++)
807 origin_decref(split[i].suspect);
811 * reverse_blame reverses the list given in head, appending tail.
812 * That allows us to build lists in reverse order, then reverse them
813 * afterwards. This can be faster than building the list in proper
814 * order right away. The reason is that building in proper order
815 * requires writing a link in the _previous_ element, while building
816 * in reverse order just requires placing the list head into the
820 static struct blame_entry *reverse_blame(struct blame_entry *head,
821 struct blame_entry *tail)
824 struct blame_entry *next = head->next;
833 * Process one hunk from the patch between the current suspect for
834 * blame_entry e and its parent. This first blames any unfinished
835 * entries before the chunk (which is where target and parent start
836 * differing) on the parent, and then splits blame entries at the
837 * start and at the end of the difference region. Since use of -M and
838 * -C options may lead to overlapping/duplicate source line number
839 * ranges, all we can rely on from sorting/merging is the order of the
840 * first suspect line number.
842 static void blame_chunk(struct blame_entry ***dstq, struct blame_entry ***srcq,
843 int tlno, int offset, int same,
844 struct origin *parent)
846 struct blame_entry *e = **srcq;
847 struct blame_entry *samep = NULL, *diffp = NULL;
849 while (e && e->s_lno < tlno) {
850 struct blame_entry *next = e->next;
852 * current record starts before differing portion. If
853 * it reaches into it, we need to split it up and
854 * examine the second part separately.
856 if (e->s_lno + e->num_lines > tlno) {
857 /* Move second half to a new record */
858 int len = tlno - e->s_lno;
859 struct blame_entry *n = xcalloc(1, sizeof (struct blame_entry));
860 n->suspect = e->suspect;
861 n->lno = e->lno + len;
862 n->s_lno = e->s_lno + len;
863 n->num_lines = e->num_lines - len;
866 /* Push new record to diffp */
870 origin_decref(e->suspect);
871 /* Pass blame for everything before the differing
872 * chunk to the parent */
873 e->suspect = origin_incref(parent);
880 * As we don't know how much of a common stretch after this
881 * diff will occur, the currently blamed parts are all that we
882 * can assign to the parent for now.
886 **dstq = reverse_blame(samep, **dstq);
887 *dstq = &samep->next;
890 * Prepend the split off portions: everything after e starts
891 * after the blameable portion.
893 e = reverse_blame(diffp, e);
896 * Now retain records on the target while parts are different
901 while (e && e->s_lno < same) {
902 struct blame_entry *next = e->next;
905 * If current record extends into sameness, need to split.
907 if (e->s_lno + e->num_lines > same) {
909 * Move second half to a new record to be
910 * processed by later chunks
912 int len = same - e->s_lno;
913 struct blame_entry *n = xcalloc(1, sizeof (struct blame_entry));
914 n->suspect = origin_incref(e->suspect);
915 n->lno = e->lno + len;
916 n->s_lno = e->s_lno + len;
917 n->num_lines = e->num_lines - len;
920 /* Push new record to samep */
928 **srcq = reverse_blame(diffp, reverse_blame(samep, e));
929 /* Move across elements that are in the unblamable portion */
931 *srcq = &diffp->next;
934 struct blame_chunk_cb_data {
935 struct origin *parent;
937 struct blame_entry **dstq;
938 struct blame_entry **srcq;
941 /* diff chunks are from parent to target */
942 static int blame_chunk_cb(long start_a, long count_a,
943 long start_b, long count_b, void *data)
945 struct blame_chunk_cb_data *d = data;
946 if (start_a - start_b != d->offset)
947 die("internal error in blame::blame_chunk_cb");
948 blame_chunk(&d->dstq, &d->srcq, start_b, start_a - start_b,
949 start_b + count_b, d->parent);
950 d->offset = start_a + count_a - (start_b + count_b);
955 * We are looking at the origin 'target' and aiming to pass blame
956 * for the lines it is suspected to its parent. Run diff to find
957 * which lines came from parent and pass blame for them.
959 static void pass_blame_to_parent(struct scoreboard *sb,
960 struct origin *target,
961 struct origin *parent)
963 mmfile_t file_p, file_o;
964 struct blame_chunk_cb_data d;
965 struct blame_entry *newdest = NULL;
967 if (!target->suspects)
968 return; /* nothing remains for this target */
972 d.dstq = &newdest; d.srcq = &target->suspects;
974 fill_origin_blob(&sb->revs->diffopt, parent, &file_p);
975 fill_origin_blob(&sb->revs->diffopt, target, &file_o);
978 if (diff_hunks(&file_p, &file_o, 0, blame_chunk_cb, &d))
979 die("unable to generate diff (%s -> %s)",
980 oid_to_hex(&parent->commit->object.oid),
981 oid_to_hex(&target->commit->object.oid));
982 /* The rest are the same as the parent */
983 blame_chunk(&d.dstq, &d.srcq, INT_MAX, d.offset, INT_MAX, parent);
985 queue_blames(sb, parent, newdest);
991 * The lines in blame_entry after splitting blames many times can become
992 * very small and trivial, and at some point it becomes pointless to
993 * blame the parents. E.g. "\t\t}\n\t}\n\n" appears everywhere in any
994 * ordinary C program, and it is not worth to say it was copied from
995 * totally unrelated file in the parent.
997 * Compute how trivial the lines in the blame_entry are.
999 static unsigned ent_score(struct scoreboard *sb, struct blame_entry *e)
1002 const char *cp, *ep;
1008 cp = nth_line(sb, e->lno);
1009 ep = nth_line(sb, e->lno + e->num_lines);
1011 unsigned ch = *((unsigned char *)cp);
1021 * best_so_far[] and this[] are both a split of an existing blame_entry
1022 * that passes blame to the parent. Maintain best_so_far the best split
1023 * so far, by comparing this and best_so_far and copying this into
1024 * bst_so_far as needed.
1026 static void copy_split_if_better(struct scoreboard *sb,
1027 struct blame_entry *best_so_far,
1028 struct blame_entry *this)
1032 if (!this[1].suspect)
1034 if (best_so_far[1].suspect) {
1035 if (ent_score(sb, &this[1]) < ent_score(sb, &best_so_far[1]))
1039 for (i = 0; i < 3; i++)
1040 origin_incref(this[i].suspect);
1041 decref_split(best_so_far);
1042 memcpy(best_so_far, this, sizeof(struct blame_entry [3]));
1046 * We are looking at a part of the final image represented by
1047 * ent (tlno and same are offset by ent->s_lno).
1048 * tlno is where we are looking at in the final image.
1049 * up to (but not including) same match preimage.
1050 * plno is where we are looking at in the preimage.
1052 * <-------------- final image ---------------------->
1055 * <---------preimage----->
1058 * All line numbers are 0-based.
1060 static void handle_split(struct scoreboard *sb,
1061 struct blame_entry *ent,
1062 int tlno, int plno, int same,
1063 struct origin *parent,
1064 struct blame_entry *split)
1066 if (ent->num_lines <= tlno)
1069 struct blame_entry this[3];
1072 split_overlap(this, ent, tlno, plno, same, parent);
1073 copy_split_if_better(sb, split, this);
1078 struct handle_split_cb_data {
1079 struct scoreboard *sb;
1080 struct blame_entry *ent;
1081 struct origin *parent;
1082 struct blame_entry *split;
1087 static int handle_split_cb(long start_a, long count_a,
1088 long start_b, long count_b, void *data)
1090 struct handle_split_cb_data *d = data;
1091 handle_split(d->sb, d->ent, d->tlno, d->plno, start_b, d->parent,
1093 d->plno = start_a + count_a;
1094 d->tlno = start_b + count_b;
1099 * Find the lines from parent that are the same as ent so that
1100 * we can pass blames to it. file_p has the blob contents for
1103 static void find_copy_in_blob(struct scoreboard *sb,
1104 struct blame_entry *ent,
1105 struct origin *parent,
1106 struct blame_entry *split,
1111 struct handle_split_cb_data d;
1113 memset(&d, 0, sizeof(d));
1114 d.sb = sb; d.ent = ent; d.parent = parent; d.split = split;
1116 * Prepare mmfile that contains only the lines in ent.
1118 cp = nth_line(sb, ent->lno);
1119 file_o.ptr = (char *) cp;
1120 file_o.size = nth_line(sb, ent->lno + ent->num_lines) - cp;
1123 * file_o is a part of final image we are annotating.
1124 * file_p partially may match that image.
1126 memset(split, 0, sizeof(struct blame_entry [3]));
1127 if (diff_hunks(file_p, &file_o, 1, handle_split_cb, &d))
1128 die("unable to generate diff (%s)",
1129 oid_to_hex(&parent->commit->object.oid));
1130 /* remainder, if any, all match the preimage */
1131 handle_split(sb, ent, d.tlno, d.plno, ent->num_lines, parent, split);
1134 /* Move all blame entries from list *source that have a score smaller
1135 * than score_min to the front of list *small.
1136 * Returns a pointer to the link pointing to the old head of the small list.
1139 static struct blame_entry **filter_small(struct scoreboard *sb,
1140 struct blame_entry **small,
1141 struct blame_entry **source,
1144 struct blame_entry *p = *source;
1145 struct blame_entry *oldsmall = *small;
1147 if (ent_score(sb, p) <= score_min) {
1163 * See if lines currently target is suspected for can be attributed to
1166 static void find_move_in_parent(struct scoreboard *sb,
1167 struct blame_entry ***blamed,
1168 struct blame_entry **toosmall,
1169 struct origin *target,
1170 struct origin *parent)
1172 struct blame_entry *e, split[3];
1173 struct blame_entry *unblamed = target->suspects;
1174 struct blame_entry *leftover = NULL;
1178 return; /* nothing remains for this target */
1180 fill_origin_blob(&sb->revs->diffopt, parent, &file_p);
1184 /* At each iteration, unblamed has a NULL-terminated list of
1185 * entries that have not yet been tested for blame. leftover
1186 * contains the reversed list of entries that have been tested
1187 * without being assignable to the parent.
1190 struct blame_entry **unblamedtail = &unblamed;
1191 struct blame_entry *next;
1192 for (e = unblamed; e; e = next) {
1194 find_copy_in_blob(sb, e, parent, split, &file_p);
1195 if (split[1].suspect &&
1196 blame_move_score < ent_score(sb, &split[1])) {
1197 split_blame(blamed, &unblamedtail, split, e);
1202 decref_split(split);
1204 *unblamedtail = NULL;
1205 toosmall = filter_small(sb, toosmall, &unblamed, blame_move_score);
1207 target->suspects = reverse_blame(leftover, NULL);
1211 struct blame_entry *ent;
1212 struct blame_entry split[3];
1216 * Count the number of entries the target is suspected for,
1217 * and prepare a list of entry and the best split.
1219 static struct blame_list *setup_blame_list(struct blame_entry *unblamed,
1222 struct blame_entry *e;
1224 struct blame_list *blame_list = NULL;
1226 for (e = unblamed, num_ents = 0; e; e = e->next)
1229 blame_list = xcalloc(num_ents, sizeof(struct blame_list));
1230 for (e = unblamed, i = 0; e; e = e->next)
1231 blame_list[i++].ent = e;
1233 *num_ents_p = num_ents;
1238 * For lines target is suspected for, see if we can find code movement
1239 * across file boundary from the parent commit. porigin is the path
1240 * in the parent we already tried.
1242 static void find_copy_in_parent(struct scoreboard *sb,
1243 struct blame_entry ***blamed,
1244 struct blame_entry **toosmall,
1245 struct origin *target,
1246 struct commit *parent,
1247 struct origin *porigin,
1250 struct diff_options diff_opts;
1252 struct blame_list *blame_list;
1254 struct blame_entry *unblamed = target->suspects;
1255 struct blame_entry *leftover = NULL;
1258 return; /* nothing remains for this target */
1260 diff_setup(&diff_opts);
1261 DIFF_OPT_SET(&diff_opts, RECURSIVE);
1262 diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;
1264 diff_setup_done(&diff_opts);
1266 /* Try "find copies harder" on new path if requested;
1267 * we do not want to use diffcore_rename() actually to
1268 * match things up; find_copies_harder is set only to
1269 * force diff_tree_sha1() to feed all filepairs to diff_queue,
1270 * and this code needs to be after diff_setup_done(), which
1271 * usually makes find-copies-harder imply copy detection.
1273 if ((opt & PICKAXE_BLAME_COPY_HARDEST)
1274 || ((opt & PICKAXE_BLAME_COPY_HARDER)
1275 && (!porigin || strcmp(target->path, porigin->path))))
1276 DIFF_OPT_SET(&diff_opts, FIND_COPIES_HARDER);
1278 if (is_null_oid(&target->commit->object.oid))
1279 do_diff_cache(parent->tree->object.oid.hash, &diff_opts);
1281 diff_tree_sha1(parent->tree->object.oid.hash,
1282 target->commit->tree->object.oid.hash,
1285 if (!DIFF_OPT_TST(&diff_opts, FIND_COPIES_HARDER))
1286 diffcore_std(&diff_opts);
1289 struct blame_entry **unblamedtail = &unblamed;
1290 blame_list = setup_blame_list(unblamed, &num_ents);
1292 for (i = 0; i < diff_queued_diff.nr; i++) {
1293 struct diff_filepair *p = diff_queued_diff.queue[i];
1294 struct origin *norigin;
1296 struct blame_entry this[3];
1298 if (!DIFF_FILE_VALID(p->one))
1299 continue; /* does not exist in parent */
1300 if (S_ISGITLINK(p->one->mode))
1301 continue; /* ignore git links */
1302 if (porigin && !strcmp(p->one->path, porigin->path))
1303 /* find_move already dealt with this path */
1306 norigin = get_origin(sb, parent, p->one->path);
1307 hashcpy(norigin->blob_sha1, p->one->sha1);
1308 norigin->mode = p->one->mode;
1309 fill_origin_blob(&sb->revs->diffopt, norigin, &file_p);
1313 for (j = 0; j < num_ents; j++) {
1314 find_copy_in_blob(sb, blame_list[j].ent,
1315 norigin, this, &file_p);
1316 copy_split_if_better(sb, blame_list[j].split,
1320 origin_decref(norigin);
1323 for (j = 0; j < num_ents; j++) {
1324 struct blame_entry *split = blame_list[j].split;
1325 if (split[1].suspect &&
1326 blame_copy_score < ent_score(sb, &split[1])) {
1327 split_blame(blamed, &unblamedtail, split,
1330 blame_list[j].ent->next = leftover;
1331 leftover = blame_list[j].ent;
1333 decref_split(split);
1336 *unblamedtail = NULL;
1337 toosmall = filter_small(sb, toosmall, &unblamed, blame_copy_score);
1339 target->suspects = reverse_blame(leftover, NULL);
1340 diff_flush(&diff_opts);
1341 free_pathspec(&diff_opts.pathspec);
1345 * The blobs of origin and porigin exactly match, so everything
1346 * origin is suspected for can be blamed on the parent.
1348 static void pass_whole_blame(struct scoreboard *sb,
1349 struct origin *origin, struct origin *porigin)
1351 struct blame_entry *e, *suspects;
1353 if (!porigin->file.ptr && origin->file.ptr) {
1354 /* Steal its file */
1355 porigin->file = origin->file;
1356 origin->file.ptr = NULL;
1358 suspects = origin->suspects;
1359 origin->suspects = NULL;
1360 for (e = suspects; e; e = e->next) {
1361 origin_incref(porigin);
1362 origin_decref(e->suspect);
1363 e->suspect = porigin;
1365 queue_blames(sb, porigin, suspects);
1369 * We pass blame from the current commit to its parents. We keep saying
1370 * "parent" (and "porigin"), but what we mean is to find scapegoat to
1371 * exonerate ourselves.
1373 static struct commit_list *first_scapegoat(struct rev_info *revs, struct commit *commit)
1376 if (revs->first_parent_only &&
1378 commit->parents->next) {
1379 free_commit_list(commit->parents->next);
1380 commit->parents->next = NULL;
1382 return commit->parents;
1384 return lookup_decoration(&revs->children, &commit->object);
1387 static int num_scapegoats(struct rev_info *revs, struct commit *commit)
1389 struct commit_list *l = first_scapegoat(revs, commit);
1390 return commit_list_count(l);
1393 /* Distribute collected unsorted blames to the respected sorted lists
1394 * in the various origins.
1396 static void distribute_blame(struct scoreboard *sb, struct blame_entry *blamed)
1398 blamed = blame_sort(blamed, compare_blame_suspect);
1401 struct origin *porigin = blamed->suspect;
1402 struct blame_entry *suspects = NULL;
1404 struct blame_entry *next = blamed->next;
1405 blamed->next = suspects;
1408 } while (blamed && blamed->suspect == porigin);
1409 suspects = reverse_blame(suspects, NULL);
1410 queue_blames(sb, porigin, suspects);
1416 static void pass_blame(struct scoreboard *sb, struct origin *origin, int opt)
1418 struct rev_info *revs = sb->revs;
1419 int i, pass, num_sg;
1420 struct commit *commit = origin->commit;
1421 struct commit_list *sg;
1422 struct origin *sg_buf[MAXSG];
1423 struct origin *porigin, **sg_origin = sg_buf;
1424 struct blame_entry *toosmall = NULL;
1425 struct blame_entry *blames, **blametail = &blames;
1427 num_sg = num_scapegoats(revs, commit);
1430 else if (num_sg < ARRAY_SIZE(sg_buf))
1431 memset(sg_buf, 0, sizeof(sg_buf));
1433 sg_origin = xcalloc(num_sg, sizeof(*sg_origin));
1436 * The first pass looks for unrenamed path to optimize for
1437 * common cases, then we look for renames in the second pass.
1439 for (pass = 0; pass < 2 - no_whole_file_rename; pass++) {
1440 struct origin *(*find)(struct scoreboard *,
1441 struct commit *, struct origin *);
1442 find = pass ? find_rename : find_origin;
1444 for (i = 0, sg = first_scapegoat(revs, commit);
1446 sg = sg->next, i++) {
1447 struct commit *p = sg->item;
1452 if (parse_commit(p))
1454 porigin = find(sb, p, origin);
1457 if (!hashcmp(porigin->blob_sha1, origin->blob_sha1)) {
1458 pass_whole_blame(sb, origin, porigin);
1459 origin_decref(porigin);
1462 for (j = same = 0; j < i; j++)
1464 !hashcmp(sg_origin[j]->blob_sha1,
1465 porigin->blob_sha1)) {
1470 sg_origin[i] = porigin;
1472 origin_decref(porigin);
1477 for (i = 0, sg = first_scapegoat(revs, commit);
1479 sg = sg->next, i++) {
1480 struct origin *porigin = sg_origin[i];
1483 if (!origin->previous) {
1484 origin_incref(porigin);
1485 origin->previous = porigin;
1487 pass_blame_to_parent(sb, origin, porigin);
1488 if (!origin->suspects)
1493 * Optionally find moves in parents' files.
1495 if (opt & PICKAXE_BLAME_MOVE) {
1496 filter_small(sb, &toosmall, &origin->suspects, blame_move_score);
1497 if (origin->suspects) {
1498 for (i = 0, sg = first_scapegoat(revs, commit);
1500 sg = sg->next, i++) {
1501 struct origin *porigin = sg_origin[i];
1504 find_move_in_parent(sb, &blametail, &toosmall, origin, porigin);
1505 if (!origin->suspects)
1512 * Optionally find copies from parents' files.
1514 if (opt & PICKAXE_BLAME_COPY) {
1515 if (blame_copy_score > blame_move_score)
1516 filter_small(sb, &toosmall, &origin->suspects, blame_copy_score);
1517 else if (blame_copy_score < blame_move_score) {
1518 origin->suspects = blame_merge(origin->suspects, toosmall);
1520 filter_small(sb, &toosmall, &origin->suspects, blame_copy_score);
1522 if (!origin->suspects)
1525 for (i = 0, sg = first_scapegoat(revs, commit);
1527 sg = sg->next, i++) {
1528 struct origin *porigin = sg_origin[i];
1529 find_copy_in_parent(sb, &blametail, &toosmall,
1530 origin, sg->item, porigin, opt);
1531 if (!origin->suspects)
1538 distribute_blame(sb, blames);
1540 * prepend toosmall to origin->suspects
1542 * There is no point in sorting: this ends up on a big
1543 * unsorted list in the caller anyway.
1546 struct blame_entry **tail = &toosmall;
1548 tail = &(*tail)->next;
1549 *tail = origin->suspects;
1550 origin->suspects = toosmall;
1552 for (i = 0; i < num_sg; i++) {
1554 drop_origin_blob(sg_origin[i]);
1555 origin_decref(sg_origin[i]);
1558 drop_origin_blob(origin);
1559 if (sg_buf != sg_origin)
1564 * Information on commits, used for output.
1566 struct commit_info {
1567 struct strbuf author;
1568 struct strbuf author_mail;
1569 unsigned long author_time;
1570 struct strbuf author_tz;
1572 /* filled only when asked for details */
1573 struct strbuf committer;
1574 struct strbuf committer_mail;
1575 unsigned long committer_time;
1576 struct strbuf committer_tz;
1578 struct strbuf summary;
1582 * Parse author/committer line in the commit object buffer
1584 static void get_ac_line(const char *inbuf, const char *what,
1585 struct strbuf *name, struct strbuf *mail,
1586 unsigned long *time, struct strbuf *tz)
1588 struct ident_split ident;
1589 size_t len, maillen, namelen;
1591 const char *namebuf, *mailbuf;
1593 tmp = strstr(inbuf, what);
1596 tmp += strlen(what);
1597 endp = strchr(tmp, '\n');
1603 if (split_ident_line(&ident, tmp, len)) {
1607 strbuf_addstr(name, tmp);
1608 strbuf_addstr(mail, tmp);
1609 strbuf_addstr(tz, tmp);
1614 namelen = ident.name_end - ident.name_begin;
1615 namebuf = ident.name_begin;
1617 maillen = ident.mail_end - ident.mail_begin;
1618 mailbuf = ident.mail_begin;
1620 if (ident.date_begin && ident.date_end)
1621 *time = strtoul(ident.date_begin, NULL, 10);
1625 if (ident.tz_begin && ident.tz_end)
1626 strbuf_add(tz, ident.tz_begin, ident.tz_end - ident.tz_begin);
1628 strbuf_addstr(tz, "(unknown)");
1631 * Now, convert both name and e-mail using mailmap
1633 map_user(&mailmap, &mailbuf, &maillen,
1634 &namebuf, &namelen);
1636 strbuf_addf(mail, "<%.*s>", (int)maillen, mailbuf);
1637 strbuf_add(name, namebuf, namelen);
1640 static void commit_info_init(struct commit_info *ci)
1643 strbuf_init(&ci->author, 0);
1644 strbuf_init(&ci->author_mail, 0);
1645 strbuf_init(&ci->author_tz, 0);
1646 strbuf_init(&ci->committer, 0);
1647 strbuf_init(&ci->committer_mail, 0);
1648 strbuf_init(&ci->committer_tz, 0);
1649 strbuf_init(&ci->summary, 0);
1652 static void commit_info_destroy(struct commit_info *ci)
1655 strbuf_release(&ci->author);
1656 strbuf_release(&ci->author_mail);
1657 strbuf_release(&ci->author_tz);
1658 strbuf_release(&ci->committer);
1659 strbuf_release(&ci->committer_mail);
1660 strbuf_release(&ci->committer_tz);
1661 strbuf_release(&ci->summary);
1664 static void get_commit_info(struct commit *commit,
1665 struct commit_info *ret,
1669 const char *subject, *encoding;
1670 const char *message;
1672 commit_info_init(ret);
1674 encoding = get_log_output_encoding();
1675 message = logmsg_reencode(commit, NULL, encoding);
1676 get_ac_line(message, "\nauthor ",
1677 &ret->author, &ret->author_mail,
1678 &ret->author_time, &ret->author_tz);
1681 unuse_commit_buffer(commit, message);
1685 get_ac_line(message, "\ncommitter ",
1686 &ret->committer, &ret->committer_mail,
1687 &ret->committer_time, &ret->committer_tz);
1689 len = find_commit_subject(message, &subject);
1691 strbuf_add(&ret->summary, subject, len);
1693 strbuf_addf(&ret->summary, "(%s)", oid_to_hex(&commit->object.oid));
1695 unuse_commit_buffer(commit, message);
1699 * To allow LF and other nonportable characters in pathnames,
1700 * they are c-style quoted as needed.
1702 static void write_filename_info(const char *path)
1704 printf("filename ");
1705 write_name_quoted(path, stdout, '\n');
1709 * Porcelain/Incremental format wants to show a lot of details per
1710 * commit. Instead of repeating this every line, emit it only once,
1711 * the first time each commit appears in the output (unless the
1712 * user has specifically asked for us to repeat).
1714 static int emit_one_suspect_detail(struct origin *suspect, int repeat)
1716 struct commit_info ci;
1718 if (!repeat && (suspect->commit->object.flags & METAINFO_SHOWN))
1721 suspect->commit->object.flags |= METAINFO_SHOWN;
1722 get_commit_info(suspect->commit, &ci, 1);
1723 printf("author %s\n", ci.author.buf);
1724 printf("author-mail %s\n", ci.author_mail.buf);
1725 printf("author-time %lu\n", ci.author_time);
1726 printf("author-tz %s\n", ci.author_tz.buf);
1727 printf("committer %s\n", ci.committer.buf);
1728 printf("committer-mail %s\n", ci.committer_mail.buf);
1729 printf("committer-time %lu\n", ci.committer_time);
1730 printf("committer-tz %s\n", ci.committer_tz.buf);
1731 printf("summary %s\n", ci.summary.buf);
1732 if (suspect->commit->object.flags & UNINTERESTING)
1733 printf("boundary\n");
1734 if (suspect->previous) {
1735 struct origin *prev = suspect->previous;
1736 printf("previous %s ", oid_to_hex(&prev->commit->object.oid));
1737 write_name_quoted(prev->path, stdout, '\n');
1740 commit_info_destroy(&ci);
1746 * The blame_entry is found to be guilty for the range.
1747 * Show it in incremental output.
1749 static void found_guilty_entry(struct blame_entry *ent)
1752 struct origin *suspect = ent->suspect;
1754 printf("%s %d %d %d\n",
1755 oid_to_hex(&suspect->commit->object.oid),
1756 ent->s_lno + 1, ent->lno + 1, ent->num_lines);
1757 emit_one_suspect_detail(suspect, 0);
1758 write_filename_info(suspect->path);
1759 maybe_flush_or_die(stdout, "stdout");
1764 * The main loop -- while we have blobs with lines whose true origin
1765 * is still unknown, pick one blob, and allow its lines to pass blames
1766 * to its parents. */
1767 static void assign_blame(struct scoreboard *sb, int opt)
1769 struct rev_info *revs = sb->revs;
1770 struct commit *commit = prio_queue_get(&sb->commits);
1773 struct blame_entry *ent;
1774 struct origin *suspect = commit->util;
1776 /* find one suspect to break down */
1777 while (suspect && !suspect->suspects)
1778 suspect = suspect->next;
1781 commit = prio_queue_get(&sb->commits);
1785 assert(commit == suspect->commit);
1788 * We will use this suspect later in the loop,
1789 * so hold onto it in the meantime.
1791 origin_incref(suspect);
1792 parse_commit(commit);
1794 (!(commit->object.flags & UNINTERESTING) &&
1795 !(revs->max_age != -1 && commit->date < revs->max_age)))
1796 pass_blame(sb, suspect, opt);
1798 commit->object.flags |= UNINTERESTING;
1799 if (commit->object.parsed)
1800 mark_parents_uninteresting(commit);
1802 /* treat root commit as boundary */
1803 if (!commit->parents && !show_root)
1804 commit->object.flags |= UNINTERESTING;
1806 /* Take responsibility for the remaining entries */
1807 ent = suspect->suspects;
1809 suspect->guilty = 1;
1811 struct blame_entry *next = ent->next;
1812 found_guilty_entry(ent);
1817 ent->next = sb->ent;
1818 sb->ent = suspect->suspects;
1819 suspect->suspects = NULL;
1823 origin_decref(suspect);
1825 if (DEBUG) /* sanity */
1826 sanity_check_refcnt(sb);
1830 static const char *format_time(unsigned long time, const char *tz_str,
1833 static struct strbuf time_buf = STRBUF_INIT;
1835 strbuf_reset(&time_buf);
1836 if (show_raw_time) {
1837 strbuf_addf(&time_buf, "%lu %s", time, tz_str);
1840 const char *time_str;
1844 time_str = show_date(time, tz, &blame_date_mode);
1845 strbuf_addstr(&time_buf, time_str);
1847 * Add space paddings to time_buf to display a fixed width
1848 * string, and use time_width for display width calibration.
1850 for (time_width = utf8_strwidth(time_str);
1851 time_width < blame_date_width;
1853 strbuf_addch(&time_buf, ' ');
1855 return time_buf.buf;
1858 #define OUTPUT_ANNOTATE_COMPAT 001
1859 #define OUTPUT_LONG_OBJECT_NAME 002
1860 #define OUTPUT_RAW_TIMESTAMP 004
1861 #define OUTPUT_PORCELAIN 010
1862 #define OUTPUT_SHOW_NAME 020
1863 #define OUTPUT_SHOW_NUMBER 040
1864 #define OUTPUT_SHOW_SCORE 0100
1865 #define OUTPUT_NO_AUTHOR 0200
1866 #define OUTPUT_SHOW_EMAIL 0400
1867 #define OUTPUT_LINE_PORCELAIN 01000
1869 static void emit_porcelain_details(struct origin *suspect, int repeat)
1871 if (emit_one_suspect_detail(suspect, repeat) ||
1872 (suspect->commit->object.flags & MORE_THAN_ONE_PATH))
1873 write_filename_info(suspect->path);
1876 static void emit_porcelain(struct scoreboard *sb, struct blame_entry *ent,
1879 int repeat = opt & OUTPUT_LINE_PORCELAIN;
1882 struct origin *suspect = ent->suspect;
1883 char hex[GIT_SHA1_HEXSZ + 1];
1885 sha1_to_hex_r(hex, suspect->commit->object.oid.hash);
1886 printf("%s %d %d %d\n",
1891 emit_porcelain_details(suspect, repeat);
1893 cp = nth_line(sb, ent->lno);
1894 for (cnt = 0; cnt < ent->num_lines; cnt++) {
1897 printf("%s %d %d\n", hex,
1898 ent->s_lno + 1 + cnt,
1899 ent->lno + 1 + cnt);
1901 emit_porcelain_details(suspect, 1);
1907 } while (ch != '\n' &&
1908 cp < sb->final_buf + sb->final_buf_size);
1911 if (sb->final_buf_size && cp[-1] != '\n')
1915 static void emit_other(struct scoreboard *sb, struct blame_entry *ent, int opt)
1919 struct origin *suspect = ent->suspect;
1920 struct commit_info ci;
1921 char hex[GIT_SHA1_HEXSZ + 1];
1922 int show_raw_time = !!(opt & OUTPUT_RAW_TIMESTAMP);
1924 get_commit_info(suspect->commit, &ci, 1);
1925 sha1_to_hex_r(hex, suspect->commit->object.oid.hash);
1927 cp = nth_line(sb, ent->lno);
1928 for (cnt = 0; cnt < ent->num_lines; cnt++) {
1930 int length = (opt & OUTPUT_LONG_OBJECT_NAME) ? 40 : abbrev;
1932 if (suspect->commit->object.flags & UNINTERESTING) {
1934 memset(hex, ' ', length);
1935 else if (!(opt & OUTPUT_ANNOTATE_COMPAT)) {
1941 printf("%.*s", length, hex);
1942 if (opt & OUTPUT_ANNOTATE_COMPAT) {
1944 if (opt & OUTPUT_SHOW_EMAIL)
1945 name = ci.author_mail.buf;
1947 name = ci.author.buf;
1948 printf("\t(%10s\t%10s\t%d)", name,
1949 format_time(ci.author_time, ci.author_tz.buf,
1951 ent->lno + 1 + cnt);
1953 if (opt & OUTPUT_SHOW_SCORE)
1955 max_score_digits, ent->score,
1956 ent->suspect->refcnt);
1957 if (opt & OUTPUT_SHOW_NAME)
1958 printf(" %-*.*s", longest_file, longest_file,
1960 if (opt & OUTPUT_SHOW_NUMBER)
1961 printf(" %*d", max_orig_digits,
1962 ent->s_lno + 1 + cnt);
1964 if (!(opt & OUTPUT_NO_AUTHOR)) {
1967 if (opt & OUTPUT_SHOW_EMAIL)
1968 name = ci.author_mail.buf;
1970 name = ci.author.buf;
1971 pad = longest_author - utf8_strwidth(name);
1972 printf(" (%s%*s %10s",
1974 format_time(ci.author_time,
1979 max_digits, ent->lno + 1 + cnt);
1984 } while (ch != '\n' &&
1985 cp < sb->final_buf + sb->final_buf_size);
1988 if (sb->final_buf_size && cp[-1] != '\n')
1991 commit_info_destroy(&ci);
1994 static void output(struct scoreboard *sb, int option)
1996 struct blame_entry *ent;
1998 if (option & OUTPUT_PORCELAIN) {
1999 for (ent = sb->ent; ent; ent = ent->next) {
2001 struct origin *suspect;
2002 struct commit *commit = ent->suspect->commit;
2003 if (commit->object.flags & MORE_THAN_ONE_PATH)
2005 for (suspect = commit->util; suspect; suspect = suspect->next) {
2006 if (suspect->guilty && count++) {
2007 commit->object.flags |= MORE_THAN_ONE_PATH;
2014 for (ent = sb->ent; ent; ent = ent->next) {
2015 if (option & OUTPUT_PORCELAIN)
2016 emit_porcelain(sb, ent, option);
2018 emit_other(sb, ent, option);
2023 static const char *get_next_line(const char *start, const char *end)
2025 const char *nl = memchr(start, '\n', end - start);
2026 return nl ? nl + 1 : end;
2030 * To allow quick access to the contents of nth line in the
2031 * final image, prepare an index in the scoreboard.
2033 static int prepare_lines(struct scoreboard *sb)
2035 const char *buf = sb->final_buf;
2036 unsigned long len = sb->final_buf_size;
2037 const char *end = buf + len;
2042 for (p = buf; p < end; p = get_next_line(p, end))
2045 sb->lineno = lineno = xmalloc(sizeof(*sb->lineno) * (num + 1));
2047 for (p = buf; p < end; p = get_next_line(p, end))
2048 *lineno++ = p - buf;
2052 sb->num_lines = num;
2053 return sb->num_lines;
2057 * Add phony grafts for use with -S; this is primarily to
2058 * support git's cvsserver that wants to give a linear history
2061 static int read_ancestry(const char *graft_file)
2063 FILE *fp = fopen(graft_file, "r");
2064 struct strbuf buf = STRBUF_INIT;
2067 while (!strbuf_getwholeline(&buf, fp, '\n')) {
2068 /* The format is just "Commit Parent1 Parent2 ...\n" */
2069 struct commit_graft *graft = read_graft_line(buf.buf, buf.len);
2071 register_commit_graft(graft, 0);
2074 strbuf_release(&buf);
2078 static int update_auto_abbrev(int auto_abbrev, struct origin *suspect)
2080 const char *uniq = find_unique_abbrev(suspect->commit->object.oid.hash,
2082 int len = strlen(uniq);
2083 if (auto_abbrev < len)
2089 * How many columns do we need to show line numbers, authors,
2092 static void find_alignment(struct scoreboard *sb, int *option)
2094 int longest_src_lines = 0;
2095 int longest_dst_lines = 0;
2096 unsigned largest_score = 0;
2097 struct blame_entry *e;
2098 int compute_auto_abbrev = (abbrev < 0);
2099 int auto_abbrev = default_abbrev;
2101 for (e = sb->ent; e; e = e->next) {
2102 struct origin *suspect = e->suspect;
2105 if (compute_auto_abbrev)
2106 auto_abbrev = update_auto_abbrev(auto_abbrev, suspect);
2107 if (strcmp(suspect->path, sb->path))
2108 *option |= OUTPUT_SHOW_NAME;
2109 num = strlen(suspect->path);
2110 if (longest_file < num)
2112 if (!(suspect->commit->object.flags & METAINFO_SHOWN)) {
2113 struct commit_info ci;
2114 suspect->commit->object.flags |= METAINFO_SHOWN;
2115 get_commit_info(suspect->commit, &ci, 1);
2116 if (*option & OUTPUT_SHOW_EMAIL)
2117 num = utf8_strwidth(ci.author_mail.buf);
2119 num = utf8_strwidth(ci.author.buf);
2120 if (longest_author < num)
2121 longest_author = num;
2122 commit_info_destroy(&ci);
2124 num = e->s_lno + e->num_lines;
2125 if (longest_src_lines < num)
2126 longest_src_lines = num;
2127 num = e->lno + e->num_lines;
2128 if (longest_dst_lines < num)
2129 longest_dst_lines = num;
2130 if (largest_score < ent_score(sb, e))
2131 largest_score = ent_score(sb, e);
2133 max_orig_digits = decimal_width(longest_src_lines);
2134 max_digits = decimal_width(longest_dst_lines);
2135 max_score_digits = decimal_width(largest_score);
2137 if (compute_auto_abbrev)
2138 /* one more abbrev length is needed for the boundary commit */
2139 abbrev = auto_abbrev + 1;
2143 * For debugging -- origin is refcounted, and this asserts that
2144 * we do not underflow.
2146 static void sanity_check_refcnt(struct scoreboard *sb)
2149 struct blame_entry *ent;
2151 for (ent = sb->ent; ent; ent = ent->next) {
2152 /* Nobody should have zero or negative refcnt */
2153 if (ent->suspect->refcnt <= 0) {
2154 fprintf(stderr, "%s in %s has negative refcnt %d\n",
2156 oid_to_hex(&ent->suspect->commit->object.oid),
2157 ent->suspect->refcnt);
2163 find_alignment(sb, &opt);
2165 die("Baa %d!", baa);
2169 static unsigned parse_score(const char *arg)
2172 unsigned long score = strtoul(arg, &end, 10);
2178 static const char *add_prefix(const char *prefix, const char *path)
2180 return prefix_path(prefix, prefix ? strlen(prefix) : 0, path);
2183 static int git_blame_config(const char *var, const char *value, void *cb)
2185 if (!strcmp(var, "blame.showroot")) {
2186 show_root = git_config_bool(var, value);
2189 if (!strcmp(var, "blame.blankboundary")) {
2190 blank_boundary = git_config_bool(var, value);
2193 if (!strcmp(var, "blame.showemail")) {
2194 int *output_option = cb;
2195 if (git_config_bool(var, value))
2196 *output_option |= OUTPUT_SHOW_EMAIL;
2198 *output_option &= ~OUTPUT_SHOW_EMAIL;
2201 if (!strcmp(var, "blame.date")) {
2203 return config_error_nonbool(var);
2204 parse_date_format(value, &blame_date_mode);
2208 if (userdiff_config(var, value) < 0)
2211 return git_default_config(var, value, cb);
2214 static void verify_working_tree_path(struct commit *work_tree, const char *path)
2216 struct commit_list *parents;
2218 for (parents = work_tree->parents; parents; parents = parents->next) {
2219 const unsigned char *commit_sha1 = parents->item->object.oid.hash;
2220 unsigned char blob_sha1[20];
2223 if (!get_tree_entry(commit_sha1, path, blob_sha1, &mode) &&
2224 sha1_object_info(blob_sha1, NULL) == OBJ_BLOB)
2227 die("no such path '%s' in HEAD", path);
2230 static struct commit_list **append_parent(struct commit_list **tail, const unsigned char *sha1)
2232 struct commit *parent;
2234 parent = lookup_commit_reference(sha1);
2236 die("no such commit %s", sha1_to_hex(sha1));
2237 return &commit_list_insert(parent, tail)->next;
2240 static void append_merge_parents(struct commit_list **tail)
2243 struct strbuf line = STRBUF_INIT;
2245 merge_head = open(git_path_merge_head(), O_RDONLY);
2246 if (merge_head < 0) {
2247 if (errno == ENOENT)
2249 die("cannot open '%s' for reading", git_path_merge_head());
2252 while (!strbuf_getwholeline_fd(&line, merge_head, '\n')) {
2253 unsigned char sha1[20];
2254 if (line.len < 40 || get_sha1_hex(line.buf, sha1))
2255 die("unknown line in '%s': %s", git_path_merge_head(), line.buf);
2256 tail = append_parent(tail, sha1);
2259 strbuf_release(&line);
2263 * This isn't as simple as passing sb->buf and sb->len, because we
2264 * want to transfer ownership of the buffer to the commit (so we
2267 static void set_commit_buffer_from_strbuf(struct commit *c, struct strbuf *sb)
2270 void *buf = strbuf_detach(sb, &len);
2271 set_commit_buffer(c, buf, len);
2275 * Prepare a dummy commit that represents the work tree (or staged) item.
2276 * Note that annotating work tree item never works in the reverse.
2278 static struct commit *fake_working_tree_commit(struct diff_options *opt,
2280 const char *contents_from)
2282 struct commit *commit;
2283 struct origin *origin;
2284 struct commit_list **parent_tail, *parent;
2285 unsigned char head_sha1[20];
2286 struct strbuf buf = STRBUF_INIT;
2290 struct cache_entry *ce;
2292 struct strbuf msg = STRBUF_INIT;
2295 commit = alloc_commit_node();
2296 commit->object.parsed = 1;
2298 parent_tail = &commit->parents;
2300 if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, head_sha1, NULL))
2301 die("no such ref: HEAD");
2303 parent_tail = append_parent(parent_tail, head_sha1);
2304 append_merge_parents(parent_tail);
2305 verify_working_tree_path(commit, path);
2307 origin = make_origin(commit, path);
2309 ident = fmt_ident("Not Committed Yet", "not.committed.yet", NULL, 0);
2310 strbuf_addstr(&msg, "tree 0000000000000000000000000000000000000000\n");
2311 for (parent = commit->parents; parent; parent = parent->next)
2312 strbuf_addf(&msg, "parent %s\n",
2313 oid_to_hex(&parent->item->object.oid));
2317 "Version of %s from %s\n",
2319 (!contents_from ? path :
2320 (!strcmp(contents_from, "-") ? "standard input" : contents_from)));
2321 set_commit_buffer_from_strbuf(commit, &msg);
2323 if (!contents_from || strcmp("-", contents_from)) {
2325 const char *read_from;
2327 unsigned long buf_len;
2329 if (contents_from) {
2330 if (stat(contents_from, &st) < 0)
2331 die_errno("Cannot stat '%s'", contents_from);
2332 read_from = contents_from;
2335 if (lstat(path, &st) < 0)
2336 die_errno("Cannot lstat '%s'", path);
2339 mode = canon_mode(st.st_mode);
2341 switch (st.st_mode & S_IFMT) {
2343 if (DIFF_OPT_TST(opt, ALLOW_TEXTCONV) &&
2344 textconv_object(read_from, mode, null_sha1, 0, &buf_ptr, &buf_len))
2345 strbuf_attach(&buf, buf_ptr, buf_len, buf_len + 1);
2346 else if (strbuf_read_file(&buf, read_from, st.st_size) != st.st_size)
2347 die_errno("cannot open or read '%s'", read_from);
2350 if (strbuf_readlink(&buf, read_from, st.st_size) < 0)
2351 die_errno("cannot readlink '%s'", read_from);
2354 die("unsupported file type %s", read_from);
2358 /* Reading from stdin */
2360 if (strbuf_read(&buf, 0, 0) < 0)
2361 die_errno("failed to read from stdin");
2363 convert_to_git(path, buf.buf, buf.len, &buf, 0);
2364 origin->file.ptr = buf.buf;
2365 origin->file.size = buf.len;
2366 pretend_sha1_file(buf.buf, buf.len, OBJ_BLOB, origin->blob_sha1);
2369 * Read the current index, replace the path entry with
2370 * origin->blob_sha1 without mucking with its mode or type
2371 * bits; we are not going to write this index out -- we just
2372 * want to run "diff-index --cached".
2379 int pos = cache_name_pos(path, len);
2381 mode = active_cache[pos]->ce_mode;
2383 /* Let's not bother reading from HEAD tree */
2384 mode = S_IFREG | 0644;
2386 size = cache_entry_size(len);
2387 ce = xcalloc(1, size);
2388 hashcpy(ce->sha1, origin->blob_sha1);
2389 memcpy(ce->name, path, len);
2390 ce->ce_flags = create_ce_flags(0);
2391 ce->ce_namelen = len;
2392 ce->ce_mode = create_ce_mode(mode);
2393 add_cache_entry(ce, ADD_CACHE_OK_TO_ADD|ADD_CACHE_OK_TO_REPLACE);
2396 * We are not going to write this out, so this does not matter
2397 * right now, but someday we might optimize diff-index --cached
2398 * with cache-tree information.
2400 cache_tree_invalidate_path(&the_index, path);
2405 static struct commit *find_single_final(struct rev_info *revs,
2406 const char **name_p)
2409 struct commit *found = NULL;
2410 const char *name = NULL;
2412 for (i = 0; i < revs->pending.nr; i++) {
2413 struct object *obj = revs->pending.objects[i].item;
2414 if (obj->flags & UNINTERESTING)
2416 while (obj->type == OBJ_TAG)
2417 obj = deref_tag(obj, NULL, 0);
2418 if (obj->type != OBJ_COMMIT)
2419 die("Non commit %s?", revs->pending.objects[i].name);
2421 die("More than one commit to dig from %s and %s?",
2422 revs->pending.objects[i].name, name);
2423 found = (struct commit *)obj;
2424 name = revs->pending.objects[i].name;
2431 static char *prepare_final(struct scoreboard *sb)
2434 sb->final = find_single_final(sb->revs, &name);
2435 return xstrdup_or_null(name);
2438 static char *prepare_initial(struct scoreboard *sb)
2441 const char *final_commit_name = NULL;
2442 struct rev_info *revs = sb->revs;
2445 * There must be one and only one negative commit, and it must be
2448 for (i = 0; i < revs->pending.nr; i++) {
2449 struct object *obj = revs->pending.objects[i].item;
2450 if (!(obj->flags & UNINTERESTING))
2452 while (obj->type == OBJ_TAG)
2453 obj = deref_tag(obj, NULL, 0);
2454 if (obj->type != OBJ_COMMIT)
2455 die("Non commit %s?", revs->pending.objects[i].name);
2457 die("More than one commit to dig down to %s and %s?",
2458 revs->pending.objects[i].name,
2460 sb->final = (struct commit *) obj;
2461 final_commit_name = revs->pending.objects[i].name;
2463 if (!final_commit_name)
2464 die("No commit to dig down to?");
2465 return xstrdup(final_commit_name);
2468 static int blame_copy_callback(const struct option *option, const char *arg, int unset)
2470 int *opt = option->value;
2473 * -C enables copy from removed files;
2474 * -C -C enables copy from existing files, but only
2475 * when blaming a new file;
2476 * -C -C -C enables copy from existing files for
2479 if (*opt & PICKAXE_BLAME_COPY_HARDER)
2480 *opt |= PICKAXE_BLAME_COPY_HARDEST;
2481 if (*opt & PICKAXE_BLAME_COPY)
2482 *opt |= PICKAXE_BLAME_COPY_HARDER;
2483 *opt |= PICKAXE_BLAME_COPY | PICKAXE_BLAME_MOVE;
2486 blame_copy_score = parse_score(arg);
2490 static int blame_move_callback(const struct option *option, const char *arg, int unset)
2492 int *opt = option->value;
2494 *opt |= PICKAXE_BLAME_MOVE;
2497 blame_move_score = parse_score(arg);
2501 int cmd_blame(int argc, const char **argv, const char *prefix)
2503 struct rev_info revs;
2505 struct scoreboard sb;
2507 struct blame_entry *ent = NULL;
2508 long dashdash_pos, lno;
2509 char *final_commit_name = NULL;
2510 enum object_type type;
2511 struct commit *final_commit = NULL;
2513 static struct string_list range_list;
2514 static int output_option = 0, opt = 0;
2515 static int show_stats = 0;
2516 static const char *revs_file = NULL;
2517 static const char *contents_from = NULL;
2518 static const struct option options[] = {
2519 OPT_BOOL(0, "incremental", &incremental, N_("Show blame entries as we find them, incrementally")),
2520 OPT_BOOL('b', NULL, &blank_boundary, N_("Show blank SHA-1 for boundary commits (Default: off)")),
2521 OPT_BOOL(0, "root", &show_root, N_("Do not treat root commits as boundaries (Default: off)")),
2522 OPT_BOOL(0, "show-stats", &show_stats, N_("Show work cost statistics")),
2523 OPT_BIT(0, "score-debug", &output_option, N_("Show output score for blame entries"), OUTPUT_SHOW_SCORE),
2524 OPT_BIT('f', "show-name", &output_option, N_("Show original filename (Default: auto)"), OUTPUT_SHOW_NAME),
2525 OPT_BIT('n', "show-number", &output_option, N_("Show original linenumber (Default: off)"), OUTPUT_SHOW_NUMBER),
2526 OPT_BIT('p', "porcelain", &output_option, N_("Show in a format designed for machine consumption"), OUTPUT_PORCELAIN),
2527 OPT_BIT(0, "line-porcelain", &output_option, N_("Show porcelain format with per-line commit information"), OUTPUT_PORCELAIN|OUTPUT_LINE_PORCELAIN),
2528 OPT_BIT('c', NULL, &output_option, N_("Use the same output mode as git-annotate (Default: off)"), OUTPUT_ANNOTATE_COMPAT),
2529 OPT_BIT('t', NULL, &output_option, N_("Show raw timestamp (Default: off)"), OUTPUT_RAW_TIMESTAMP),
2530 OPT_BIT('l', NULL, &output_option, N_("Show long commit SHA1 (Default: off)"), OUTPUT_LONG_OBJECT_NAME),
2531 OPT_BIT('s', NULL, &output_option, N_("Suppress author name and timestamp (Default: off)"), OUTPUT_NO_AUTHOR),
2532 OPT_BIT('e', "show-email", &output_option, N_("Show author email instead of name (Default: off)"), OUTPUT_SHOW_EMAIL),
2533 OPT_BIT('w', NULL, &xdl_opts, N_("Ignore whitespace differences"), XDF_IGNORE_WHITESPACE),
2534 OPT_BIT(0, "minimal", &xdl_opts, N_("Spend extra cycles to find better match"), XDF_NEED_MINIMAL),
2535 OPT_STRING('S', NULL, &revs_file, N_("file"), N_("Use revisions from <file> instead of calling git-rev-list")),
2536 OPT_STRING(0, "contents", &contents_from, N_("file"), N_("Use <file>'s contents as the final image")),
2537 { OPTION_CALLBACK, 'C', NULL, &opt, N_("score"), N_("Find line copies within and across files"), PARSE_OPT_OPTARG, blame_copy_callback },
2538 { OPTION_CALLBACK, 'M', NULL, &opt, N_("score"), N_("Find line movements within and across files"), PARSE_OPT_OPTARG, blame_move_callback },
2539 OPT_STRING_LIST('L', NULL, &range_list, N_("n,m"), N_("Process only line range n,m, counting from 1")),
2540 OPT__ABBREV(&abbrev),
2544 struct parse_opt_ctx_t ctx;
2545 int cmd_is_annotate = !strcmp(argv[0], "annotate");
2546 struct range_set ranges;
2547 unsigned int range_i;
2550 git_config(git_blame_config, &output_option);
2551 init_revisions(&revs, NULL);
2552 revs.date_mode = blame_date_mode;
2553 DIFF_OPT_SET(&revs.diffopt, ALLOW_TEXTCONV);
2554 DIFF_OPT_SET(&revs.diffopt, FOLLOW_RENAMES);
2556 save_commit_buffer = 0;
2559 parse_options_start(&ctx, argc, argv, prefix, options,
2560 PARSE_OPT_KEEP_DASHDASH | PARSE_OPT_KEEP_ARGV0);
2562 switch (parse_options_step(&ctx, options, blame_opt_usage)) {
2563 case PARSE_OPT_HELP:
2565 case PARSE_OPT_DONE:
2567 dashdash_pos = ctx.cpidx;
2571 if (!strcmp(ctx.argv[0], "--reverse")) {
2572 ctx.argv[0] = "--children";
2575 parse_revision_opt(&revs, &ctx, options, blame_opt_usage);
2578 no_whole_file_rename = !DIFF_OPT_TST(&revs.diffopt, FOLLOW_RENAMES);
2579 DIFF_OPT_CLR(&revs.diffopt, FOLLOW_RENAMES);
2580 argc = parse_options_end(&ctx);
2583 /* one more abbrev length is needed for the boundary commit */
2586 if (revs_file && read_ancestry(revs_file))
2587 die_errno("reading graft file '%s' failed", revs_file);
2589 if (cmd_is_annotate) {
2590 output_option |= OUTPUT_ANNOTATE_COMPAT;
2591 blame_date_mode.type = DATE_ISO8601;
2593 blame_date_mode = revs.date_mode;
2596 /* The maximum width used to show the dates */
2597 switch (blame_date_mode.type) {
2599 blame_date_width = sizeof("Thu, 19 Oct 2006 16:00:04 -0700");
2601 case DATE_ISO8601_STRICT:
2602 blame_date_width = sizeof("2006-10-19T16:00:04-07:00");
2605 blame_date_width = sizeof("2006-10-19 16:00:04 -0700");
2608 blame_date_width = sizeof("1161298804 -0700");
2611 blame_date_width = sizeof("2006-10-19");
2614 /* TRANSLATORS: This string is used to tell us the maximum
2615 display width for a relative timestamp in "git blame"
2616 output. For C locale, "4 years, 11 months ago", which
2617 takes 22 places, is the longest among various forms of
2618 relative timestamps, but your language may need more or
2619 fewer display columns. */
2620 blame_date_width = utf8_strwidth(_("4 years, 11 months ago")) + 1; /* add the null */
2623 blame_date_width = sizeof("Thu Oct 19 16:00:04 2006 -0700");
2626 blame_date_width = strlen(show_date(0, 0, &blame_date_mode)) + 1; /* add the null */
2629 blame_date_width -= 1; /* strip the null */
2631 if (DIFF_OPT_TST(&revs.diffopt, FIND_COPIES_HARDER))
2632 opt |= (PICKAXE_BLAME_COPY | PICKAXE_BLAME_MOVE |
2633 PICKAXE_BLAME_COPY_HARDER);
2635 if (!blame_move_score)
2636 blame_move_score = BLAME_DEFAULT_MOVE_SCORE;
2637 if (!blame_copy_score)
2638 blame_copy_score = BLAME_DEFAULT_COPY_SCORE;
2641 * We have collected options unknown to us in argv[1..unk]
2642 * which are to be passed to revision machinery if we are
2643 * going to do the "bottom" processing.
2645 * The remaining are:
2647 * (1) if dashdash_pos != 0, it is either
2648 * "blame [revisions] -- <path>" or
2649 * "blame -- <path> <rev>"
2651 * (2) otherwise, it is one of the two:
2652 * "blame [revisions] <path>"
2653 * "blame <path> <rev>"
2655 * Note that we must strip out <path> from the arguments: we do not
2656 * want the path pruning but we may want "bottom" processing.
2659 switch (argc - dashdash_pos - 1) {
2662 usage_with_options(blame_opt_usage, options);
2663 /* reorder for the new way: <rev> -- <path> */
2669 path = add_prefix(prefix, argv[--argc]);
2673 usage_with_options(blame_opt_usage, options);
2677 usage_with_options(blame_opt_usage, options);
2678 path = add_prefix(prefix, argv[argc - 1]);
2679 if (argc == 3 && !file_exists(path)) { /* (2b) */
2680 path = add_prefix(prefix, argv[1]);
2683 argv[argc - 1] = "--";
2686 if (!file_exists(path))
2687 die_errno("cannot stat path '%s'", path);
2690 revs.disable_stdin = 1;
2691 setup_revisions(argc, argv, &revs, NULL);
2692 memset(&sb, 0, sizeof(sb));
2696 final_commit_name = prepare_final(&sb);
2697 sb.commits.compare = compare_commits_by_commit_date;
2699 else if (contents_from)
2700 die("--contents and --reverse do not blend well.");
2702 final_commit_name = prepare_initial(&sb);
2703 sb.commits.compare = compare_commits_by_reverse_commit_date;
2704 if (revs.first_parent_only)
2705 revs.children.name = NULL;
2710 * "--not A B -- path" without anything positive;
2711 * do not default to HEAD, but use the working tree
2715 sb.final = fake_working_tree_commit(&sb.revs->diffopt,
2716 path, contents_from);
2717 add_pending_object(&revs, &(sb.final->object), ":");
2719 else if (contents_from)
2720 die("Cannot use --contents with final commit object name");
2722 if (reverse && revs.first_parent_only) {
2723 final_commit = find_single_final(sb.revs, NULL);
2725 die("--reverse and --first-parent together require specified latest commit");
2729 * If we have bottom, this will mark the ancestors of the
2730 * bottom commits we would reach while traversing as
2733 if (prepare_revision_walk(&revs))
2734 die(_("revision walk setup failed"));
2736 if (reverse && revs.first_parent_only) {
2737 struct commit *c = final_commit;
2739 sb.revs->children.name = "children";
2740 while (c->parents &&
2741 oidcmp(&c->object.oid, &sb.final->object.oid)) {
2742 struct commit_list *l = xcalloc(1, sizeof(*l));
2745 if (add_decoration(&sb.revs->children,
2746 &c->parents->item->object, l))
2747 die("BUG: not unique item in first-parent chain");
2748 c = c->parents->item;
2751 if (oidcmp(&c->object.oid, &sb.final->object.oid))
2752 die("--reverse --first-parent together require range along first-parent chain");
2755 if (is_null_oid(&sb.final->object.oid)) {
2757 sb.final_buf = xmemdupz(o->file.ptr, o->file.size);
2758 sb.final_buf_size = o->file.size;
2761 o = get_origin(&sb, sb.final, path);
2762 if (fill_blob_sha1_and_mode(o))
2763 die("no such path %s in %s", path, final_commit_name);
2765 if (DIFF_OPT_TST(&sb.revs->diffopt, ALLOW_TEXTCONV) &&
2766 textconv_object(path, o->mode, o->blob_sha1, 1, (char **) &sb.final_buf,
2767 &sb.final_buf_size))
2770 sb.final_buf = read_sha1_file(o->blob_sha1, &type,
2771 &sb.final_buf_size);
2774 die("Cannot read blob %s for path %s",
2775 sha1_to_hex(o->blob_sha1),
2779 lno = prepare_lines(&sb);
2781 if (lno && !range_list.nr)
2782 string_list_append(&range_list, xstrdup("1"));
2785 range_set_init(&ranges, range_list.nr);
2786 for (range_i = 0; range_i < range_list.nr; ++range_i) {
2788 if (parse_range_arg(range_list.items[range_i].string,
2789 nth_line_cb, &sb, lno, anchor,
2790 &bottom, &top, sb.path))
2792 if (lno < top || ((lno || bottom) && lno < bottom))
2793 die("file %s has only %lu lines", path, lno);
2799 range_set_append_unsafe(&ranges, bottom, top);
2802 sort_and_merge_range_set(&ranges);
2804 for (range_i = ranges.nr; range_i > 0; --range_i) {
2805 const struct range *r = &ranges.ranges[range_i - 1];
2806 long bottom = r->start;
2808 struct blame_entry *next = ent;
2809 ent = xcalloc(1, sizeof(*ent));
2811 ent->num_lines = top - bottom;
2813 ent->s_lno = bottom;
2819 prio_queue_put(&sb.commits, o->commit);
2823 range_set_release(&ranges);
2824 string_list_clear(&range_list, 0);
2829 read_mailmap(&mailmap, NULL);
2834 assign_blame(&sb, opt);
2836 free(final_commit_name);
2841 sb.ent = blame_sort(sb.ent, compare_blame_final);
2845 if (!(output_option & OUTPUT_PORCELAIN))
2846 find_alignment(&sb, &output_option);
2848 output(&sb, output_option);
2849 free((void *)sb.final_buf);
2850 for (ent = sb.ent; ent; ) {
2851 struct blame_entry *e = ent->next;
2857 printf("num read blob: %d\n", num_read_blob);
2858 printf("num get patch: %d\n", num_get_patch);
2859 printf("num commits: %d\n", num_commits);