blame: move textconv_object with related functions
[git/git-svn.git] / builtin / blame.c
blobfbd757e58368dd76a1adeb00341b2eb7a9e66efc
1 /*
2 * Blame
4 * Copyright (c) 2006, 2014 by its authors
5 * See COPYING for licensing conditions
6 */
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"
32 static char blame_usage[] = N_("git blame [<options>] [<rev-opts>] [<rev>] [--] <file>");
34 static const char *blame_opt_usage[] = {
35 blame_usage,
36 "",
37 N_("<rev-opts> are documented in git-rev-list(1)"),
38 NULL
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;
46 static int show_root;
47 static int reverse;
48 static int blank_boundary;
49 static int incremental;
50 static int xdl_opts;
51 static int abbrev = -1;
52 static int no_whole_file_rename;
53 static int show_progress;
55 static struct date_mode blame_date_mode = { DATE_ISO8601 };
56 static size_t blame_date_width;
58 static struct string_list mailmap = STRING_LIST_INIT_NODUP;
60 #ifndef DEBUG
61 #define DEBUG 0
62 #endif
64 /* stats */
65 static int num_read_blob;
66 static int num_get_patch;
67 static int num_commits;
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
75 * blame for a blame_entry with score lower than these thresholds
76 * is not passed to the parent using move/copy logic.
78 static unsigned blame_move_score;
79 static unsigned blame_copy_score;
80 #define BLAME_DEFAULT_MOVE_SCORE 20
81 #define BLAME_DEFAULT_COPY_SCORE 40
83 /* Remember to update object flag allocation in object.h */
84 #define METAINFO_SHOWN (1u<<12)
85 #define MORE_THAN_ONE_PATH (1u<<13)
88 * One blob in a commit that is being suspected
90 struct origin {
91 int refcnt;
92 /* Record preceding blame record for this blob */
93 struct 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.
111 struct 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.
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
127 char guilty;
128 char path[FLEX_ARRAY];
131 struct progress_info {
132 struct progress *progress;
133 int blamed_lines;
136 static int diff_hunks(mmfile_t *file_a, mmfile_t *file_b,
137 xdl_emit_hunk_consume_func_t hunk_func, void *cb_data)
139 xpparam_t xpp = {0};
140 xdemitconf_t xecfg = {0};
141 xdemitcb_t ecb = {NULL};
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);
150 * Given an origin, prepare mmfile_t structure to be used by the
151 * diff machinery
153 static void fill_origin_blob(struct diff_options *opt,
154 struct origin *o, mmfile_t *file)
156 if (!o->file.ptr) {
157 enum object_type type;
158 unsigned long file_size;
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))
164 else
165 file->ptr = read_sha1_file(o->blob_oid.hash, &type,
166 &file_size);
167 file->size = file_size;
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;
175 else
176 *file = o->file;
180 * Origin is refcounted and usually we keep the blob contents to be
181 * reused.
183 static inline struct origin *origin_incref(struct origin *o)
185 if (o)
186 o->refcnt++;
187 return o;
190 static void origin_decref(struct origin *o)
192 if (o && --o->refcnt <= 0) {
193 struct origin *p, *l = NULL;
194 if (o->previous)
195 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;
208 die("internal error in blame::origin_decref");
212 static void drop_origin_blob(struct origin *o)
214 if (o->file.ptr) {
215 free(o->file.ptr);
216 o->file.ptr = NULL;
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.
229 struct blame_entry {
230 struct blame_entry *next;
232 /* the first line of this group in the final image;
233 * internally all line numbers are 0 based.
235 int lno;
237 /* how many lines this group has */
238 int num_lines;
240 /* the commit that introduced this group into the final image */
241 struct origin *suspect;
243 /* the line number of the first line of this group in the
244 * suspect's file; internally all line numbers are 0 based.
246 int s_lno;
248 /* how significant this entry is -- cached to avoid
249 * scanning the lines over and over.
251 unsigned score;
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.
262 static struct blame_entry *blame_merge(struct blame_entry *list1,
263 struct blame_entry *list2)
265 struct blame_entry *p1 = list1, *p2 = list2,
266 **tail = &list1;
268 if (!p1)
269 return p2;
270 if (!p2)
271 return p1;
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;
280 } while (p1->s_lno <= p2->s_lno);
282 for (;;) {
283 *tail = p2;
284 do {
285 tail = &p2->next;
286 if ((p2 = *tail) == NULL) {
287 *tail = p1;
288 return list1;
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;
298 } while (p1->s_lno <= p2->s_lno);
302 static void *get_next_blame(const void *p)
304 return ((struct blame_entry *)p)->next;
307 static void set_next_blame(void *p1, void *p2)
309 ((struct blame_entry *)p1)->next = p2;
313 * Final image line numbers are all different, so we don't need a
314 * three-way comparison here.
317 static int compare_blame_final(const void *p1, const void *p2)
319 return ((struct blame_entry *)p1)->lno > ((struct blame_entry *)p2)->lno
320 ? 1 : -1;
323 static int compare_blame_suspect(const void *p1, const void *p2)
325 const struct blame_entry *s1 = p1, *s2 = p2;
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.
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;
340 static struct blame_entry *blame_sort(struct blame_entry *head,
341 int (*compare_fn)(const void *, const void *))
343 return llist_mergesort (head, get_next_blame, set_next_blame, compare_fn);
346 static int compare_commits_by_reverse_commit_date(const void *a,
347 const void *b,
348 void *c)
350 return -compare_commits_by_commit_date(a, b, c);
354 * The current state of the blame assignment.
356 struct 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;
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].
369 const char *final_buf;
370 unsigned long final_buf_size;
372 /* linked list of blames */
373 struct blame_entry *ent;
375 /* look-up a line in the final buffer */
376 int num_lines;
377 int *lineno;
380 static void sanity_check_refcnt(struct scoreboard *);
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.
387 static void coalesce(struct scoreboard *sb)
389 struct blame_entry *ent, *next;
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 origin_decref(next->suspect);
397 free(next);
398 ent->score = 0;
399 next = ent; /* again */
403 if (DEBUG) /* sanity */
404 sanity_check_refcnt(sb);
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.
413 static void queue_blames(struct scoreboard *sb, struct origin *porigin,
414 struct blame_entry *sorted)
416 if (porigin->suspects)
417 porigin->suspects = blame_merge(porigin->suspects, sorted);
418 else {
419 struct origin *o;
420 for (o = porigin->commit->util; o; o = o->next) {
421 if (o->suspects) {
422 porigin->suspects = sorted;
423 return;
426 porigin->suspects = sorted;
427 prio_queue_put(&sb->commits, porigin->commit);
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.
437 static struct origin *make_origin(struct commit *commit, const char *path)
439 struct 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;
449 * Locate an existing origin or create a new one.
450 * This moves the origin to front position in the commit util list.
452 static struct origin *get_origin(struct scoreboard *sb,
453 struct commit *commit,
454 const char *path)
456 struct origin *o, *l;
458 for (o = commit->util, l = NULL; o; l = o, o = o->next) {
459 if (!strcmp(o->path, path)) {
460 /* bump to front */
461 if (l) {
462 l->next = o->next;
463 o->next = commit->util;
464 commit->util = o;
466 return origin_incref(o);
469 return make_origin(commit, path);
473 * Fill the blob_sha1 field of an origin if it hasn't, so that later
474 * call to fill_origin_blob() can use it to locate the data. blob_sha1
475 * for an origin is also used to pass the blame for the entire file to
476 * the parent to detect the case where a child's blob is identical to
477 * that of its parent's.
479 * This also fills origin->mode for corresponding tree path.
481 static int fill_blob_sha1_and_mode(struct origin *origin)
483 if (!is_null_oid(&origin->blob_oid))
484 return 0;
485 if (get_tree_entry(origin->commit->object.oid.hash,
486 origin->path,
487 origin->blob_oid.hash, &origin->mode))
488 goto error_out;
489 if (sha1_object_info(origin->blob_oid.hash, NULL) != OBJ_BLOB)
490 goto error_out;
491 return 0;
492 error_out:
493 oidclr(&origin->blob_oid);
494 origin->mode = S_IFINVALID;
495 return -1;
499 * We have an origin -- check if the same path exists in the
500 * parent and return an origin structure to represent it.
502 static struct origin *find_origin(struct scoreboard *sb,
503 struct commit *parent,
504 struct origin *origin)
506 struct origin *porigin;
507 struct diff_options diff_opts;
508 const char *paths[2];
510 /* First check any existing origins */
511 for (porigin = parent->util; porigin; porigin = porigin->next)
512 if (!strcmp(porigin->path, origin->path)) {
514 * The same path between origin and its parent
515 * without renaming -- the most common case.
517 return origin_incref (porigin);
520 /* See if the origin->path is different between parent
521 * and origin first. Most of the time they are the
522 * same and diff-tree is fairly efficient about this.
524 diff_setup(&diff_opts);
525 DIFF_OPT_SET(&diff_opts, RECURSIVE);
526 diff_opts.detect_rename = 0;
527 diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;
528 paths[0] = origin->path;
529 paths[1] = NULL;
531 parse_pathspec(&diff_opts.pathspec,
532 PATHSPEC_ALL_MAGIC & ~PATHSPEC_LITERAL,
533 PATHSPEC_LITERAL_PATH, "", paths);
534 diff_setup_done(&diff_opts);
536 if (is_null_oid(&origin->commit->object.oid))
537 do_diff_cache(parent->tree->object.oid.hash, &diff_opts);
538 else
539 diff_tree_sha1(parent->tree->object.oid.hash,
540 origin->commit->tree->object.oid.hash,
541 "", &diff_opts);
542 diffcore_std(&diff_opts);
544 if (!diff_queued_diff.nr) {
545 /* The path is the same as parent */
546 porigin = get_origin(sb, parent, origin->path);
547 oidcpy(&porigin->blob_oid, &origin->blob_oid);
548 porigin->mode = origin->mode;
549 } else {
551 * Since origin->path is a pathspec, if the parent
552 * commit had it as a directory, we will see a whole
553 * bunch of deletion of files in the directory that we
554 * do not care about.
556 int i;
557 struct diff_filepair *p = NULL;
558 for (i = 0; i < diff_queued_diff.nr; i++) {
559 const char *name;
560 p = diff_queued_diff.queue[i];
561 name = p->one->path ? p->one->path : p->two->path;
562 if (!strcmp(name, origin->path))
563 break;
565 if (!p)
566 die("internal error in blame::find_origin");
567 switch (p->status) {
568 default:
569 die("internal error in blame::find_origin (%c)",
570 p->status);
571 case 'M':
572 porigin = get_origin(sb, parent, origin->path);
573 oidcpy(&porigin->blob_oid, &p->one->oid);
574 porigin->mode = p->one->mode;
575 break;
576 case 'A':
577 case 'T':
578 /* Did not exist in parent, or type changed */
579 break;
582 diff_flush(&diff_opts);
583 clear_pathspec(&diff_opts.pathspec);
584 return porigin;
588 * We have an origin -- find the path that corresponds to it in its
589 * parent and return an origin structure to represent it.
591 static struct origin *find_rename(struct scoreboard *sb,
592 struct commit *parent,
593 struct origin *origin)
595 struct origin *porigin = NULL;
596 struct diff_options diff_opts;
597 int i;
599 diff_setup(&diff_opts);
600 DIFF_OPT_SET(&diff_opts, RECURSIVE);
601 diff_opts.detect_rename = DIFF_DETECT_RENAME;
602 diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;
603 diff_opts.single_follow = origin->path;
604 diff_setup_done(&diff_opts);
606 if (is_null_oid(&origin->commit->object.oid))
607 do_diff_cache(parent->tree->object.oid.hash, &diff_opts);
608 else
609 diff_tree_sha1(parent->tree->object.oid.hash,
610 origin->commit->tree->object.oid.hash,
611 "", &diff_opts);
612 diffcore_std(&diff_opts);
614 for (i = 0; i < diff_queued_diff.nr; i++) {
615 struct diff_filepair *p = diff_queued_diff.queue[i];
616 if ((p->status == 'R' || p->status == 'C') &&
617 !strcmp(p->two->path, origin->path)) {
618 porigin = get_origin(sb, parent, p->one->path);
619 oidcpy(&porigin->blob_oid, &p->one->oid);
620 porigin->mode = p->one->mode;
621 break;
624 diff_flush(&diff_opts);
625 clear_pathspec(&diff_opts.pathspec);
626 return porigin;
630 * Append a new blame entry to a given output queue.
632 static void add_blame_entry(struct blame_entry ***queue,
633 const struct blame_entry *src)
635 struct blame_entry *e = xmalloc(sizeof(*e));
636 memcpy(e, src, sizeof(*e));
637 origin_incref(e->suspect);
639 e->next = **queue;
640 **queue = e;
641 *queue = &e->next;
645 * src typically is on-stack; we want to copy the information in it to
646 * a malloced blame_entry that gets added to the given queue. The
647 * origin of dst loses a refcnt.
649 static void dup_entry(struct blame_entry ***queue,
650 struct blame_entry *dst, struct blame_entry *src)
652 origin_incref(src->suspect);
653 origin_decref(dst->suspect);
654 memcpy(dst, src, sizeof(*src));
655 dst->next = **queue;
656 **queue = dst;
657 *queue = &dst->next;
660 static const char *nth_line(struct scoreboard *sb, long lno)
662 return sb->final_buf + sb->lineno[lno];
665 static const char *nth_line_cb(void *data, long lno)
667 return nth_line((struct scoreboard *)data, lno);
671 * It is known that lines between tlno to same came from parent, and e
672 * has an overlap with that range. it also is known that parent's
673 * line plno corresponds to e's line tlno.
675 * <---- e ----->
676 * <------>
677 * <------------>
678 * <------------>
679 * <------------------>
681 * Split e into potentially three parts; before this chunk, the chunk
682 * to be blamed for the parent, and after that portion.
684 static void split_overlap(struct blame_entry *split,
685 struct blame_entry *e,
686 int tlno, int plno, int same,
687 struct origin *parent)
689 int chunk_end_lno;
690 memset(split, 0, sizeof(struct blame_entry [3]));
692 if (e->s_lno < tlno) {
693 /* there is a pre-chunk part not blamed on parent */
694 split[0].suspect = origin_incref(e->suspect);
695 split[0].lno = e->lno;
696 split[0].s_lno = e->s_lno;
697 split[0].num_lines = tlno - e->s_lno;
698 split[1].lno = e->lno + tlno - e->s_lno;
699 split[1].s_lno = plno;
701 else {
702 split[1].lno = e->lno;
703 split[1].s_lno = plno + (e->s_lno - tlno);
706 if (same < e->s_lno + e->num_lines) {
707 /* there is a post-chunk part not blamed on parent */
708 split[2].suspect = origin_incref(e->suspect);
709 split[2].lno = e->lno + (same - e->s_lno);
710 split[2].s_lno = e->s_lno + (same - e->s_lno);
711 split[2].num_lines = e->s_lno + e->num_lines - same;
712 chunk_end_lno = split[2].lno;
714 else
715 chunk_end_lno = e->lno + e->num_lines;
716 split[1].num_lines = chunk_end_lno - split[1].lno;
719 * if it turns out there is nothing to blame the parent for,
720 * forget about the splitting. !split[1].suspect signals this.
722 if (split[1].num_lines < 1)
723 return;
724 split[1].suspect = origin_incref(parent);
728 * split_overlap() divided an existing blame e into up to three parts
729 * in split. Any assigned blame is moved to queue to
730 * reflect the split.
732 static void split_blame(struct blame_entry ***blamed,
733 struct blame_entry ***unblamed,
734 struct blame_entry *split,
735 struct blame_entry *e)
737 if (split[0].suspect && split[2].suspect) {
738 /* The first part (reuse storage for the existing entry e) */
739 dup_entry(unblamed, e, &split[0]);
741 /* The last part -- me */
742 add_blame_entry(unblamed, &split[2]);
744 /* ... and the middle part -- parent */
745 add_blame_entry(blamed, &split[1]);
747 else if (!split[0].suspect && !split[2].suspect)
749 * The parent covers the entire area; reuse storage for
750 * e and replace it with the parent.
752 dup_entry(blamed, e, &split[1]);
753 else if (split[0].suspect) {
754 /* me and then parent */
755 dup_entry(unblamed, e, &split[0]);
756 add_blame_entry(blamed, &split[1]);
758 else {
759 /* parent and then me */
760 dup_entry(blamed, e, &split[1]);
761 add_blame_entry(unblamed, &split[2]);
766 * After splitting the blame, the origins used by the
767 * on-stack blame_entry should lose one refcnt each.
769 static void decref_split(struct blame_entry *split)
771 int i;
773 for (i = 0; i < 3; i++)
774 origin_decref(split[i].suspect);
778 * reverse_blame reverses the list given in head, appending tail.
779 * That allows us to build lists in reverse order, then reverse them
780 * afterwards. This can be faster than building the list in proper
781 * order right away. The reason is that building in proper order
782 * requires writing a link in the _previous_ element, while building
783 * in reverse order just requires placing the list head into the
784 * _current_ element.
787 static struct blame_entry *reverse_blame(struct blame_entry *head,
788 struct blame_entry *tail)
790 while (head) {
791 struct blame_entry *next = head->next;
792 head->next = tail;
793 tail = head;
794 head = next;
796 return tail;
800 * Process one hunk from the patch between the current suspect for
801 * blame_entry e and its parent. This first blames any unfinished
802 * entries before the chunk (which is where target and parent start
803 * differing) on the parent, and then splits blame entries at the
804 * start and at the end of the difference region. Since use of -M and
805 * -C options may lead to overlapping/duplicate source line number
806 * ranges, all we can rely on from sorting/merging is the order of the
807 * first suspect line number.
809 static void blame_chunk(struct blame_entry ***dstq, struct blame_entry ***srcq,
810 int tlno, int offset, int same,
811 struct origin *parent)
813 struct blame_entry *e = **srcq;
814 struct blame_entry *samep = NULL, *diffp = NULL;
816 while (e && e->s_lno < tlno) {
817 struct blame_entry *next = e->next;
819 * current record starts before differing portion. If
820 * it reaches into it, we need to split it up and
821 * examine the second part separately.
823 if (e->s_lno + e->num_lines > tlno) {
824 /* Move second half to a new record */
825 int len = tlno - e->s_lno;
826 struct blame_entry *n = xcalloc(1, sizeof (struct blame_entry));
827 n->suspect = e->suspect;
828 n->lno = e->lno + len;
829 n->s_lno = e->s_lno + len;
830 n->num_lines = e->num_lines - len;
831 e->num_lines = len;
832 e->score = 0;
833 /* Push new record to diffp */
834 n->next = diffp;
835 diffp = n;
836 } else
837 origin_decref(e->suspect);
838 /* Pass blame for everything before the differing
839 * chunk to the parent */
840 e->suspect = origin_incref(parent);
841 e->s_lno += offset;
842 e->next = samep;
843 samep = e;
844 e = next;
847 * As we don't know how much of a common stretch after this
848 * diff will occur, the currently blamed parts are all that we
849 * can assign to the parent for now.
852 if (samep) {
853 **dstq = reverse_blame(samep, **dstq);
854 *dstq = &samep->next;
857 * Prepend the split off portions: everything after e starts
858 * after the blameable portion.
860 e = reverse_blame(diffp, e);
863 * Now retain records on the target while parts are different
864 * from the parent.
866 samep = NULL;
867 diffp = NULL;
868 while (e && e->s_lno < same) {
869 struct blame_entry *next = e->next;
872 * If current record extends into sameness, need to split.
874 if (e->s_lno + e->num_lines > same) {
876 * Move second half to a new record to be
877 * processed by later chunks
879 int len = same - e->s_lno;
880 struct blame_entry *n = xcalloc(1, sizeof (struct blame_entry));
881 n->suspect = origin_incref(e->suspect);
882 n->lno = e->lno + len;
883 n->s_lno = e->s_lno + len;
884 n->num_lines = e->num_lines - len;
885 e->num_lines = len;
886 e->score = 0;
887 /* Push new record to samep */
888 n->next = samep;
889 samep = n;
891 e->next = diffp;
892 diffp = e;
893 e = next;
895 **srcq = reverse_blame(diffp, reverse_blame(samep, e));
896 /* Move across elements that are in the unblamable portion */
897 if (diffp)
898 *srcq = &diffp->next;
901 struct blame_chunk_cb_data {
902 struct origin *parent;
903 long offset;
904 struct blame_entry **dstq;
905 struct blame_entry **srcq;
908 /* diff chunks are from parent to target */
909 static int blame_chunk_cb(long start_a, long count_a,
910 long start_b, long count_b, void *data)
912 struct blame_chunk_cb_data *d = data;
913 if (start_a - start_b != d->offset)
914 die("internal error in blame::blame_chunk_cb");
915 blame_chunk(&d->dstq, &d->srcq, start_b, start_a - start_b,
916 start_b + count_b, d->parent);
917 d->offset = start_a + count_a - (start_b + count_b);
918 return 0;
922 * We are looking at the origin 'target' and aiming to pass blame
923 * for the lines it is suspected to its parent. Run diff to find
924 * which lines came from parent and pass blame for them.
926 static void pass_blame_to_parent(struct scoreboard *sb,
927 struct origin *target,
928 struct origin *parent)
930 mmfile_t file_p, file_o;
931 struct blame_chunk_cb_data d;
932 struct blame_entry *newdest = NULL;
934 if (!target->suspects)
935 return; /* nothing remains for this target */
937 d.parent = parent;
938 d.offset = 0;
939 d.dstq = &newdest; d.srcq = &target->suspects;
941 fill_origin_blob(&sb->revs->diffopt, parent, &file_p);
942 fill_origin_blob(&sb->revs->diffopt, target, &file_o);
943 num_get_patch++;
945 if (diff_hunks(&file_p, &file_o, blame_chunk_cb, &d))
946 die("unable to generate diff (%s -> %s)",
947 oid_to_hex(&parent->commit->object.oid),
948 oid_to_hex(&target->commit->object.oid));
949 /* The rest are the same as the parent */
950 blame_chunk(&d.dstq, &d.srcq, INT_MAX, d.offset, INT_MAX, parent);
951 *d.dstq = NULL;
952 queue_blames(sb, parent, newdest);
954 return;
958 * The lines in blame_entry after splitting blames many times can become
959 * very small and trivial, and at some point it becomes pointless to
960 * blame the parents. E.g. "\t\t}\n\t}\n\n" appears everywhere in any
961 * ordinary C program, and it is not worth to say it was copied from
962 * totally unrelated file in the parent.
964 * Compute how trivial the lines in the blame_entry are.
966 static unsigned ent_score(struct scoreboard *sb, struct blame_entry *e)
968 unsigned score;
969 const char *cp, *ep;
971 if (e->score)
972 return e->score;
974 score = 1;
975 cp = nth_line(sb, e->lno);
976 ep = nth_line(sb, e->lno + e->num_lines);
977 while (cp < ep) {
978 unsigned ch = *((unsigned char *)cp);
979 if (isalnum(ch))
980 score++;
981 cp++;
983 e->score = score;
984 return score;
988 * best_so_far[] and this[] are both a split of an existing blame_entry
989 * that passes blame to the parent. Maintain best_so_far the best split
990 * so far, by comparing this and best_so_far and copying this into
991 * bst_so_far as needed.
993 static void copy_split_if_better(struct scoreboard *sb,
994 struct blame_entry *best_so_far,
995 struct blame_entry *this)
997 int i;
999 if (!this[1].suspect)
1000 return;
1001 if (best_so_far[1].suspect) {
1002 if (ent_score(sb, &this[1]) < ent_score(sb, &best_so_far[1]))
1003 return;
1006 for (i = 0; i < 3; i++)
1007 origin_incref(this[i].suspect);
1008 decref_split(best_so_far);
1009 memcpy(best_so_far, this, sizeof(struct blame_entry [3]));
1013 * We are looking at a part of the final image represented by
1014 * ent (tlno and same are offset by ent->s_lno).
1015 * tlno is where we are looking at in the final image.
1016 * up to (but not including) same match preimage.
1017 * plno is where we are looking at in the preimage.
1019 * <-------------- final image ---------------------->
1020 * <------ent------>
1021 * ^tlno ^same
1022 * <---------preimage----->
1023 * ^plno
1025 * All line numbers are 0-based.
1027 static void handle_split(struct scoreboard *sb,
1028 struct blame_entry *ent,
1029 int tlno, int plno, int same,
1030 struct origin *parent,
1031 struct blame_entry *split)
1033 if (ent->num_lines <= tlno)
1034 return;
1035 if (tlno < same) {
1036 struct blame_entry this[3];
1037 tlno += ent->s_lno;
1038 same += ent->s_lno;
1039 split_overlap(this, ent, tlno, plno, same, parent);
1040 copy_split_if_better(sb, split, this);
1041 decref_split(this);
1045 struct handle_split_cb_data {
1046 struct scoreboard *sb;
1047 struct blame_entry *ent;
1048 struct origin *parent;
1049 struct blame_entry *split;
1050 long plno;
1051 long tlno;
1054 static int handle_split_cb(long start_a, long count_a,
1055 long start_b, long count_b, void *data)
1057 struct handle_split_cb_data *d = data;
1058 handle_split(d->sb, d->ent, d->tlno, d->plno, start_b, d->parent,
1059 d->split);
1060 d->plno = start_a + count_a;
1061 d->tlno = start_b + count_b;
1062 return 0;
1066 * Find the lines from parent that are the same as ent so that
1067 * we can pass blames to it. file_p has the blob contents for
1068 * the parent.
1070 static void find_copy_in_blob(struct scoreboard *sb,
1071 struct blame_entry *ent,
1072 struct origin *parent,
1073 struct blame_entry *split,
1074 mmfile_t *file_p)
1076 const char *cp;
1077 mmfile_t file_o;
1078 struct handle_split_cb_data d;
1080 memset(&d, 0, sizeof(d));
1081 d.sb = sb; d.ent = ent; d.parent = parent; d.split = split;
1083 * Prepare mmfile that contains only the lines in ent.
1085 cp = nth_line(sb, ent->lno);
1086 file_o.ptr = (char *) cp;
1087 file_o.size = nth_line(sb, ent->lno + ent->num_lines) - cp;
1090 * file_o is a part of final image we are annotating.
1091 * file_p partially may match that image.
1093 memset(split, 0, sizeof(struct blame_entry [3]));
1094 if (diff_hunks(file_p, &file_o, handle_split_cb, &d))
1095 die("unable to generate diff (%s)",
1096 oid_to_hex(&parent->commit->object.oid));
1097 /* remainder, if any, all match the preimage */
1098 handle_split(sb, ent, d.tlno, d.plno, ent->num_lines, parent, split);
1101 /* Move all blame entries from list *source that have a score smaller
1102 * than score_min to the front of list *small.
1103 * Returns a pointer to the link pointing to the old head of the small list.
1106 static struct blame_entry **filter_small(struct scoreboard *sb,
1107 struct blame_entry **small,
1108 struct blame_entry **source,
1109 unsigned score_min)
1111 struct blame_entry *p = *source;
1112 struct blame_entry *oldsmall = *small;
1113 while (p) {
1114 if (ent_score(sb, p) <= score_min) {
1115 *small = p;
1116 small = &p->next;
1117 p = *small;
1118 } else {
1119 *source = p;
1120 source = &p->next;
1121 p = *source;
1124 *small = oldsmall;
1125 *source = NULL;
1126 return small;
1130 * See if lines currently target is suspected for can be attributed to
1131 * parent.
1133 static void find_move_in_parent(struct scoreboard *sb,
1134 struct blame_entry ***blamed,
1135 struct blame_entry **toosmall,
1136 struct origin *target,
1137 struct origin *parent)
1139 struct blame_entry *e, split[3];
1140 struct blame_entry *unblamed = target->suspects;
1141 struct blame_entry *leftover = NULL;
1142 mmfile_t file_p;
1144 if (!unblamed)
1145 return; /* nothing remains for this target */
1147 fill_origin_blob(&sb->revs->diffopt, parent, &file_p);
1148 if (!file_p.ptr)
1149 return;
1151 /* At each iteration, unblamed has a NULL-terminated list of
1152 * entries that have not yet been tested for blame. leftover
1153 * contains the reversed list of entries that have been tested
1154 * without being assignable to the parent.
1156 do {
1157 struct blame_entry **unblamedtail = &unblamed;
1158 struct blame_entry *next;
1159 for (e = unblamed; e; e = next) {
1160 next = e->next;
1161 find_copy_in_blob(sb, e, parent, split, &file_p);
1162 if (split[1].suspect &&
1163 blame_move_score < ent_score(sb, &split[1])) {
1164 split_blame(blamed, &unblamedtail, split, e);
1165 } else {
1166 e->next = leftover;
1167 leftover = e;
1169 decref_split(split);
1171 *unblamedtail = NULL;
1172 toosmall = filter_small(sb, toosmall, &unblamed, blame_move_score);
1173 } while (unblamed);
1174 target->suspects = reverse_blame(leftover, NULL);
1177 struct blame_list {
1178 struct blame_entry *ent;
1179 struct blame_entry split[3];
1183 * Count the number of entries the target is suspected for,
1184 * and prepare a list of entry and the best split.
1186 static struct blame_list *setup_blame_list(struct blame_entry *unblamed,
1187 int *num_ents_p)
1189 struct blame_entry *e;
1190 int num_ents, i;
1191 struct blame_list *blame_list = NULL;
1193 for (e = unblamed, num_ents = 0; e; e = e->next)
1194 num_ents++;
1195 if (num_ents) {
1196 blame_list = xcalloc(num_ents, sizeof(struct blame_list));
1197 for (e = unblamed, i = 0; e; e = e->next)
1198 blame_list[i++].ent = e;
1200 *num_ents_p = num_ents;
1201 return blame_list;
1205 * For lines target is suspected for, see if we can find code movement
1206 * across file boundary from the parent commit. porigin is the path
1207 * in the parent we already tried.
1209 static void find_copy_in_parent(struct scoreboard *sb,
1210 struct blame_entry ***blamed,
1211 struct blame_entry **toosmall,
1212 struct origin *target,
1213 struct commit *parent,
1214 struct origin *porigin,
1215 int opt)
1217 struct diff_options diff_opts;
1218 int i, j;
1219 struct blame_list *blame_list;
1220 int num_ents;
1221 struct blame_entry *unblamed = target->suspects;
1222 struct blame_entry *leftover = NULL;
1224 if (!unblamed)
1225 return; /* nothing remains for this target */
1227 diff_setup(&diff_opts);
1228 DIFF_OPT_SET(&diff_opts, RECURSIVE);
1229 diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;
1231 diff_setup_done(&diff_opts);
1233 /* Try "find copies harder" on new path if requested;
1234 * we do not want to use diffcore_rename() actually to
1235 * match things up; find_copies_harder is set only to
1236 * force diff_tree_sha1() to feed all filepairs to diff_queue,
1237 * and this code needs to be after diff_setup_done(), which
1238 * usually makes find-copies-harder imply copy detection.
1240 if ((opt & PICKAXE_BLAME_COPY_HARDEST)
1241 || ((opt & PICKAXE_BLAME_COPY_HARDER)
1242 && (!porigin || strcmp(target->path, porigin->path))))
1243 DIFF_OPT_SET(&diff_opts, FIND_COPIES_HARDER);
1245 if (is_null_oid(&target->commit->object.oid))
1246 do_diff_cache(parent->tree->object.oid.hash, &diff_opts);
1247 else
1248 diff_tree_sha1(parent->tree->object.oid.hash,
1249 target->commit->tree->object.oid.hash,
1250 "", &diff_opts);
1252 if (!DIFF_OPT_TST(&diff_opts, FIND_COPIES_HARDER))
1253 diffcore_std(&diff_opts);
1255 do {
1256 struct blame_entry **unblamedtail = &unblamed;
1257 blame_list = setup_blame_list(unblamed, &num_ents);
1259 for (i = 0; i < diff_queued_diff.nr; i++) {
1260 struct diff_filepair *p = diff_queued_diff.queue[i];
1261 struct origin *norigin;
1262 mmfile_t file_p;
1263 struct blame_entry this[3];
1265 if (!DIFF_FILE_VALID(p->one))
1266 continue; /* does not exist in parent */
1267 if (S_ISGITLINK(p->one->mode))
1268 continue; /* ignore git links */
1269 if (porigin && !strcmp(p->one->path, porigin->path))
1270 /* find_move already dealt with this path */
1271 continue;
1273 norigin = get_origin(sb, parent, p->one->path);
1274 oidcpy(&norigin->blob_oid, &p->one->oid);
1275 norigin->mode = p->one->mode;
1276 fill_origin_blob(&sb->revs->diffopt, norigin, &file_p);
1277 if (!file_p.ptr)
1278 continue;
1280 for (j = 0; j < num_ents; j++) {
1281 find_copy_in_blob(sb, blame_list[j].ent,
1282 norigin, this, &file_p);
1283 copy_split_if_better(sb, blame_list[j].split,
1284 this);
1285 decref_split(this);
1287 origin_decref(norigin);
1290 for (j = 0; j < num_ents; j++) {
1291 struct blame_entry *split = blame_list[j].split;
1292 if (split[1].suspect &&
1293 blame_copy_score < ent_score(sb, &split[1])) {
1294 split_blame(blamed, &unblamedtail, split,
1295 blame_list[j].ent);
1296 } else {
1297 blame_list[j].ent->next = leftover;
1298 leftover = blame_list[j].ent;
1300 decref_split(split);
1302 free(blame_list);
1303 *unblamedtail = NULL;
1304 toosmall = filter_small(sb, toosmall, &unblamed, blame_copy_score);
1305 } while (unblamed);
1306 target->suspects = reverse_blame(leftover, NULL);
1307 diff_flush(&diff_opts);
1308 clear_pathspec(&diff_opts.pathspec);
1312 * The blobs of origin and porigin exactly match, so everything
1313 * origin is suspected for can be blamed on the parent.
1315 static void pass_whole_blame(struct scoreboard *sb,
1316 struct origin *origin, struct origin *porigin)
1318 struct blame_entry *e, *suspects;
1320 if (!porigin->file.ptr && origin->file.ptr) {
1321 /* Steal its file */
1322 porigin->file = origin->file;
1323 origin->file.ptr = NULL;
1325 suspects = origin->suspects;
1326 origin->suspects = NULL;
1327 for (e = suspects; e; e = e->next) {
1328 origin_incref(porigin);
1329 origin_decref(e->suspect);
1330 e->suspect = porigin;
1332 queue_blames(sb, porigin, suspects);
1336 * We pass blame from the current commit to its parents. We keep saying
1337 * "parent" (and "porigin"), but what we mean is to find scapegoat to
1338 * exonerate ourselves.
1340 static struct commit_list *first_scapegoat(struct rev_info *revs, struct commit *commit)
1342 if (!reverse) {
1343 if (revs->first_parent_only &&
1344 commit->parents &&
1345 commit->parents->next) {
1346 free_commit_list(commit->parents->next);
1347 commit->parents->next = NULL;
1349 return commit->parents;
1351 return lookup_decoration(&revs->children, &commit->object);
1354 static int num_scapegoats(struct rev_info *revs, struct commit *commit)
1356 struct commit_list *l = first_scapegoat(revs, commit);
1357 return commit_list_count(l);
1360 /* Distribute collected unsorted blames to the respected sorted lists
1361 * in the various origins.
1363 static void distribute_blame(struct scoreboard *sb, struct blame_entry *blamed)
1365 blamed = blame_sort(blamed, compare_blame_suspect);
1366 while (blamed)
1368 struct origin *porigin = blamed->suspect;
1369 struct blame_entry *suspects = NULL;
1370 do {
1371 struct blame_entry *next = blamed->next;
1372 blamed->next = suspects;
1373 suspects = blamed;
1374 blamed = next;
1375 } while (blamed && blamed->suspect == porigin);
1376 suspects = reverse_blame(suspects, NULL);
1377 queue_blames(sb, porigin, suspects);
1381 #define MAXSG 16
1383 static void pass_blame(struct scoreboard *sb, struct origin *origin, int opt)
1385 struct rev_info *revs = sb->revs;
1386 int i, pass, num_sg;
1387 struct commit *commit = origin->commit;
1388 struct commit_list *sg;
1389 struct origin *sg_buf[MAXSG];
1390 struct origin *porigin, **sg_origin = sg_buf;
1391 struct blame_entry *toosmall = NULL;
1392 struct blame_entry *blames, **blametail = &blames;
1394 num_sg = num_scapegoats(revs, commit);
1395 if (!num_sg)
1396 goto finish;
1397 else if (num_sg < ARRAY_SIZE(sg_buf))
1398 memset(sg_buf, 0, sizeof(sg_buf));
1399 else
1400 sg_origin = xcalloc(num_sg, sizeof(*sg_origin));
1403 * The first pass looks for unrenamed path to optimize for
1404 * common cases, then we look for renames in the second pass.
1406 for (pass = 0; pass < 2 - no_whole_file_rename; pass++) {
1407 struct origin *(*find)(struct scoreboard *,
1408 struct commit *, struct origin *);
1409 find = pass ? find_rename : find_origin;
1411 for (i = 0, sg = first_scapegoat(revs, commit);
1412 i < num_sg && sg;
1413 sg = sg->next, i++) {
1414 struct commit *p = sg->item;
1415 int j, same;
1417 if (sg_origin[i])
1418 continue;
1419 if (parse_commit(p))
1420 continue;
1421 porigin = find(sb, p, origin);
1422 if (!porigin)
1423 continue;
1424 if (!oidcmp(&porigin->blob_oid, &origin->blob_oid)) {
1425 pass_whole_blame(sb, origin, porigin);
1426 origin_decref(porigin);
1427 goto finish;
1429 for (j = same = 0; j < i; j++)
1430 if (sg_origin[j] &&
1431 !oidcmp(&sg_origin[j]->blob_oid, &porigin->blob_oid)) {
1432 same = 1;
1433 break;
1435 if (!same)
1436 sg_origin[i] = porigin;
1437 else
1438 origin_decref(porigin);
1442 num_commits++;
1443 for (i = 0, sg = first_scapegoat(revs, commit);
1444 i < num_sg && sg;
1445 sg = sg->next, i++) {
1446 struct origin *porigin = sg_origin[i];
1447 if (!porigin)
1448 continue;
1449 if (!origin->previous) {
1450 origin_incref(porigin);
1451 origin->previous = porigin;
1453 pass_blame_to_parent(sb, origin, porigin);
1454 if (!origin->suspects)
1455 goto finish;
1459 * Optionally find moves in parents' files.
1461 if (opt & PICKAXE_BLAME_MOVE) {
1462 filter_small(sb, &toosmall, &origin->suspects, blame_move_score);
1463 if (origin->suspects) {
1464 for (i = 0, sg = first_scapegoat(revs, commit);
1465 i < num_sg && sg;
1466 sg = sg->next, i++) {
1467 struct origin *porigin = sg_origin[i];
1468 if (!porigin)
1469 continue;
1470 find_move_in_parent(sb, &blametail, &toosmall, origin, porigin);
1471 if (!origin->suspects)
1472 break;
1478 * Optionally find copies from parents' files.
1480 if (opt & PICKAXE_BLAME_COPY) {
1481 if (blame_copy_score > blame_move_score)
1482 filter_small(sb, &toosmall, &origin->suspects, blame_copy_score);
1483 else if (blame_copy_score < blame_move_score) {
1484 origin->suspects = blame_merge(origin->suspects, toosmall);
1485 toosmall = NULL;
1486 filter_small(sb, &toosmall, &origin->suspects, blame_copy_score);
1488 if (!origin->suspects)
1489 goto finish;
1491 for (i = 0, sg = first_scapegoat(revs, commit);
1492 i < num_sg && sg;
1493 sg = sg->next, i++) {
1494 struct origin *porigin = sg_origin[i];
1495 find_copy_in_parent(sb, &blametail, &toosmall,
1496 origin, sg->item, porigin, opt);
1497 if (!origin->suspects)
1498 goto finish;
1502 finish:
1503 *blametail = NULL;
1504 distribute_blame(sb, blames);
1506 * prepend toosmall to origin->suspects
1508 * There is no point in sorting: this ends up on a big
1509 * unsorted list in the caller anyway.
1511 if (toosmall) {
1512 struct blame_entry **tail = &toosmall;
1513 while (*tail)
1514 tail = &(*tail)->next;
1515 *tail = origin->suspects;
1516 origin->suspects = toosmall;
1518 for (i = 0; i < num_sg; i++) {
1519 if (sg_origin[i]) {
1520 drop_origin_blob(sg_origin[i]);
1521 origin_decref(sg_origin[i]);
1524 drop_origin_blob(origin);
1525 if (sg_buf != sg_origin)
1526 free(sg_origin);
1530 * Information on commits, used for output.
1532 struct commit_info {
1533 struct strbuf author;
1534 struct strbuf author_mail;
1535 timestamp_t author_time;
1536 struct strbuf author_tz;
1538 /* filled only when asked for details */
1539 struct strbuf committer;
1540 struct strbuf committer_mail;
1541 timestamp_t committer_time;
1542 struct strbuf committer_tz;
1544 struct strbuf summary;
1548 * Parse author/committer line in the commit object buffer
1550 static void get_ac_line(const char *inbuf, const char *what,
1551 struct strbuf *name, struct strbuf *mail,
1552 timestamp_t *time, struct strbuf *tz)
1554 struct ident_split ident;
1555 size_t len, maillen, namelen;
1556 char *tmp, *endp;
1557 const char *namebuf, *mailbuf;
1559 tmp = strstr(inbuf, what);
1560 if (!tmp)
1561 goto error_out;
1562 tmp += strlen(what);
1563 endp = strchr(tmp, '\n');
1564 if (!endp)
1565 len = strlen(tmp);
1566 else
1567 len = endp - tmp;
1569 if (split_ident_line(&ident, tmp, len)) {
1570 error_out:
1571 /* Ugh */
1572 tmp = "(unknown)";
1573 strbuf_addstr(name, tmp);
1574 strbuf_addstr(mail, tmp);
1575 strbuf_addstr(tz, tmp);
1576 *time = 0;
1577 return;
1580 namelen = ident.name_end - ident.name_begin;
1581 namebuf = ident.name_begin;
1583 maillen = ident.mail_end - ident.mail_begin;
1584 mailbuf = ident.mail_begin;
1586 if (ident.date_begin && ident.date_end)
1587 *time = strtoul(ident.date_begin, NULL, 10);
1588 else
1589 *time = 0;
1591 if (ident.tz_begin && ident.tz_end)
1592 strbuf_add(tz, ident.tz_begin, ident.tz_end - ident.tz_begin);
1593 else
1594 strbuf_addstr(tz, "(unknown)");
1597 * Now, convert both name and e-mail using mailmap
1599 map_user(&mailmap, &mailbuf, &maillen,
1600 &namebuf, &namelen);
1602 strbuf_addf(mail, "<%.*s>", (int)maillen, mailbuf);
1603 strbuf_add(name, namebuf, namelen);
1606 static void commit_info_init(struct commit_info *ci)
1609 strbuf_init(&ci->author, 0);
1610 strbuf_init(&ci->author_mail, 0);
1611 strbuf_init(&ci->author_tz, 0);
1612 strbuf_init(&ci->committer, 0);
1613 strbuf_init(&ci->committer_mail, 0);
1614 strbuf_init(&ci->committer_tz, 0);
1615 strbuf_init(&ci->summary, 0);
1618 static void commit_info_destroy(struct commit_info *ci)
1621 strbuf_release(&ci->author);
1622 strbuf_release(&ci->author_mail);
1623 strbuf_release(&ci->author_tz);
1624 strbuf_release(&ci->committer);
1625 strbuf_release(&ci->committer_mail);
1626 strbuf_release(&ci->committer_tz);
1627 strbuf_release(&ci->summary);
1630 static void get_commit_info(struct commit *commit,
1631 struct commit_info *ret,
1632 int detailed)
1634 int len;
1635 const char *subject, *encoding;
1636 const char *message;
1638 commit_info_init(ret);
1640 encoding = get_log_output_encoding();
1641 message = logmsg_reencode(commit, NULL, encoding);
1642 get_ac_line(message, "\nauthor ",
1643 &ret->author, &ret->author_mail,
1644 &ret->author_time, &ret->author_tz);
1646 if (!detailed) {
1647 unuse_commit_buffer(commit, message);
1648 return;
1651 get_ac_line(message, "\ncommitter ",
1652 &ret->committer, &ret->committer_mail,
1653 &ret->committer_time, &ret->committer_tz);
1655 len = find_commit_subject(message, &subject);
1656 if (len)
1657 strbuf_add(&ret->summary, subject, len);
1658 else
1659 strbuf_addf(&ret->summary, "(%s)", oid_to_hex(&commit->object.oid));
1661 unuse_commit_buffer(commit, message);
1665 * Write out any suspect information which depends on the path. This must be
1666 * handled separately from emit_one_suspect_detail(), because a given commit
1667 * may have changes in multiple paths. So this needs to appear each time
1668 * we mention a new group.
1670 * To allow LF and other nonportable characters in pathnames,
1671 * they are c-style quoted as needed.
1673 static void write_filename_info(struct origin *suspect)
1675 if (suspect->previous) {
1676 struct origin *prev = suspect->previous;
1677 printf("previous %s ", oid_to_hex(&prev->commit->object.oid));
1678 write_name_quoted(prev->path, stdout, '\n');
1680 printf("filename ");
1681 write_name_quoted(suspect->path, stdout, '\n');
1685 * Porcelain/Incremental format wants to show a lot of details per
1686 * commit. Instead of repeating this every line, emit it only once,
1687 * the first time each commit appears in the output (unless the
1688 * user has specifically asked for us to repeat).
1690 static int emit_one_suspect_detail(struct origin *suspect, int repeat)
1692 struct commit_info ci;
1694 if (!repeat && (suspect->commit->object.flags & METAINFO_SHOWN))
1695 return 0;
1697 suspect->commit->object.flags |= METAINFO_SHOWN;
1698 get_commit_info(suspect->commit, &ci, 1);
1699 printf("author %s\n", ci.author.buf);
1700 printf("author-mail %s\n", ci.author_mail.buf);
1701 printf("author-time %"PRItime"\n", ci.author_time);
1702 printf("author-tz %s\n", ci.author_tz.buf);
1703 printf("committer %s\n", ci.committer.buf);
1704 printf("committer-mail %s\n", ci.committer_mail.buf);
1705 printf("committer-time %"PRItime"\n", ci.committer_time);
1706 printf("committer-tz %s\n", ci.committer_tz.buf);
1707 printf("summary %s\n", ci.summary.buf);
1708 if (suspect->commit->object.flags & UNINTERESTING)
1709 printf("boundary\n");
1711 commit_info_destroy(&ci);
1713 return 1;
1717 * The blame_entry is found to be guilty for the range.
1718 * Show it in incremental output.
1720 static void found_guilty_entry(struct blame_entry *ent,
1721 struct progress_info *pi)
1723 if (incremental) {
1724 struct origin *suspect = ent->suspect;
1726 printf("%s %d %d %d\n",
1727 oid_to_hex(&suspect->commit->object.oid),
1728 ent->s_lno + 1, ent->lno + 1, ent->num_lines);
1729 emit_one_suspect_detail(suspect, 0);
1730 write_filename_info(suspect);
1731 maybe_flush_or_die(stdout, "stdout");
1733 pi->blamed_lines += ent->num_lines;
1734 display_progress(pi->progress, pi->blamed_lines);
1738 * The main loop -- while we have blobs with lines whose true origin
1739 * is still unknown, pick one blob, and allow its lines to pass blames
1740 * to its parents. */
1741 static void assign_blame(struct scoreboard *sb, int opt)
1743 struct rev_info *revs = sb->revs;
1744 struct commit *commit = prio_queue_get(&sb->commits);
1745 struct progress_info pi = { NULL, 0 };
1747 if (show_progress)
1748 pi.progress = start_progress_delay(_("Blaming lines"),
1749 sb->num_lines, 50, 1);
1751 while (commit) {
1752 struct blame_entry *ent;
1753 struct origin *suspect = commit->util;
1755 /* find one suspect to break down */
1756 while (suspect && !suspect->suspects)
1757 suspect = suspect->next;
1759 if (!suspect) {
1760 commit = prio_queue_get(&sb->commits);
1761 continue;
1764 assert(commit == suspect->commit);
1767 * We will use this suspect later in the loop,
1768 * so hold onto it in the meantime.
1770 origin_incref(suspect);
1771 parse_commit(commit);
1772 if (reverse ||
1773 (!(commit->object.flags & UNINTERESTING) &&
1774 !(revs->max_age != -1 && commit->date < revs->max_age)))
1775 pass_blame(sb, suspect, opt);
1776 else {
1777 commit->object.flags |= UNINTERESTING;
1778 if (commit->object.parsed)
1779 mark_parents_uninteresting(commit);
1781 /* treat root commit as boundary */
1782 if (!commit->parents && !show_root)
1783 commit->object.flags |= UNINTERESTING;
1785 /* Take responsibility for the remaining entries */
1786 ent = suspect->suspects;
1787 if (ent) {
1788 suspect->guilty = 1;
1789 for (;;) {
1790 struct blame_entry *next = ent->next;
1791 found_guilty_entry(ent, &pi);
1792 if (next) {
1793 ent = next;
1794 continue;
1796 ent->next = sb->ent;
1797 sb->ent = suspect->suspects;
1798 suspect->suspects = NULL;
1799 break;
1802 origin_decref(suspect);
1804 if (DEBUG) /* sanity */
1805 sanity_check_refcnt(sb);
1808 stop_progress(&pi.progress);
1811 static const char *format_time(timestamp_t time, const char *tz_str,
1812 int show_raw_time)
1814 static struct strbuf time_buf = STRBUF_INIT;
1816 strbuf_reset(&time_buf);
1817 if (show_raw_time) {
1818 strbuf_addf(&time_buf, "%"PRItime" %s", time, tz_str);
1820 else {
1821 const char *time_str;
1822 size_t time_width;
1823 int tz;
1824 tz = atoi(tz_str);
1825 time_str = show_date(time, tz, &blame_date_mode);
1826 strbuf_addstr(&time_buf, time_str);
1828 * Add space paddings to time_buf to display a fixed width
1829 * string, and use time_width for display width calibration.
1831 for (time_width = utf8_strwidth(time_str);
1832 time_width < blame_date_width;
1833 time_width++)
1834 strbuf_addch(&time_buf, ' ');
1836 return time_buf.buf;
1839 #define OUTPUT_ANNOTATE_COMPAT 001
1840 #define OUTPUT_LONG_OBJECT_NAME 002
1841 #define OUTPUT_RAW_TIMESTAMP 004
1842 #define OUTPUT_PORCELAIN 010
1843 #define OUTPUT_SHOW_NAME 020
1844 #define OUTPUT_SHOW_NUMBER 040
1845 #define OUTPUT_SHOW_SCORE 0100
1846 #define OUTPUT_NO_AUTHOR 0200
1847 #define OUTPUT_SHOW_EMAIL 0400
1848 #define OUTPUT_LINE_PORCELAIN 01000
1850 static void emit_porcelain_details(struct origin *suspect, int repeat)
1852 if (emit_one_suspect_detail(suspect, repeat) ||
1853 (suspect->commit->object.flags & MORE_THAN_ONE_PATH))
1854 write_filename_info(suspect);
1857 static void emit_porcelain(struct scoreboard *sb, struct blame_entry *ent,
1858 int opt)
1860 int repeat = opt & OUTPUT_LINE_PORCELAIN;
1861 int cnt;
1862 const char *cp;
1863 struct origin *suspect = ent->suspect;
1864 char hex[GIT_MAX_HEXSZ + 1];
1866 oid_to_hex_r(hex, &suspect->commit->object.oid);
1867 printf("%s %d %d %d\n",
1868 hex,
1869 ent->s_lno + 1,
1870 ent->lno + 1,
1871 ent->num_lines);
1872 emit_porcelain_details(suspect, repeat);
1874 cp = nth_line(sb, ent->lno);
1875 for (cnt = 0; cnt < ent->num_lines; cnt++) {
1876 char ch;
1877 if (cnt) {
1878 printf("%s %d %d\n", hex,
1879 ent->s_lno + 1 + cnt,
1880 ent->lno + 1 + cnt);
1881 if (repeat)
1882 emit_porcelain_details(suspect, 1);
1884 putchar('\t');
1885 do {
1886 ch = *cp++;
1887 putchar(ch);
1888 } while (ch != '\n' &&
1889 cp < sb->final_buf + sb->final_buf_size);
1892 if (sb->final_buf_size && cp[-1] != '\n')
1893 putchar('\n');
1896 static void emit_other(struct scoreboard *sb, struct blame_entry *ent, int opt)
1898 int cnt;
1899 const char *cp;
1900 struct origin *suspect = ent->suspect;
1901 struct commit_info ci;
1902 char hex[GIT_MAX_HEXSZ + 1];
1903 int show_raw_time = !!(opt & OUTPUT_RAW_TIMESTAMP);
1905 get_commit_info(suspect->commit, &ci, 1);
1906 oid_to_hex_r(hex, &suspect->commit->object.oid);
1908 cp = nth_line(sb, ent->lno);
1909 for (cnt = 0; cnt < ent->num_lines; cnt++) {
1910 char ch;
1911 int length = (opt & OUTPUT_LONG_OBJECT_NAME) ? GIT_SHA1_HEXSZ : abbrev;
1913 if (suspect->commit->object.flags & UNINTERESTING) {
1914 if (blank_boundary)
1915 memset(hex, ' ', length);
1916 else if (!(opt & OUTPUT_ANNOTATE_COMPAT)) {
1917 length--;
1918 putchar('^');
1922 printf("%.*s", length, hex);
1923 if (opt & OUTPUT_ANNOTATE_COMPAT) {
1924 const char *name;
1925 if (opt & OUTPUT_SHOW_EMAIL)
1926 name = ci.author_mail.buf;
1927 else
1928 name = ci.author.buf;
1929 printf("\t(%10s\t%10s\t%d)", name,
1930 format_time(ci.author_time, ci.author_tz.buf,
1931 show_raw_time),
1932 ent->lno + 1 + cnt);
1933 } else {
1934 if (opt & OUTPUT_SHOW_SCORE)
1935 printf(" %*d %02d",
1936 max_score_digits, ent->score,
1937 ent->suspect->refcnt);
1938 if (opt & OUTPUT_SHOW_NAME)
1939 printf(" %-*.*s", longest_file, longest_file,
1940 suspect->path);
1941 if (opt & OUTPUT_SHOW_NUMBER)
1942 printf(" %*d", max_orig_digits,
1943 ent->s_lno + 1 + cnt);
1945 if (!(opt & OUTPUT_NO_AUTHOR)) {
1946 const char *name;
1947 int pad;
1948 if (opt & OUTPUT_SHOW_EMAIL)
1949 name = ci.author_mail.buf;
1950 else
1951 name = ci.author.buf;
1952 pad = longest_author - utf8_strwidth(name);
1953 printf(" (%s%*s %10s",
1954 name, pad, "",
1955 format_time(ci.author_time,
1956 ci.author_tz.buf,
1957 show_raw_time));
1959 printf(" %*d) ",
1960 max_digits, ent->lno + 1 + cnt);
1962 do {
1963 ch = *cp++;
1964 putchar(ch);
1965 } while (ch != '\n' &&
1966 cp < sb->final_buf + sb->final_buf_size);
1969 if (sb->final_buf_size && cp[-1] != '\n')
1970 putchar('\n');
1972 commit_info_destroy(&ci);
1975 static void output(struct scoreboard *sb, int option)
1977 struct blame_entry *ent;
1979 if (option & OUTPUT_PORCELAIN) {
1980 for (ent = sb->ent; ent; ent = ent->next) {
1981 int count = 0;
1982 struct origin *suspect;
1983 struct commit *commit = ent->suspect->commit;
1984 if (commit->object.flags & MORE_THAN_ONE_PATH)
1985 continue;
1986 for (suspect = commit->util; suspect; suspect = suspect->next) {
1987 if (suspect->guilty && count++) {
1988 commit->object.flags |= MORE_THAN_ONE_PATH;
1989 break;
1995 for (ent = sb->ent; ent; ent = ent->next) {
1996 if (option & OUTPUT_PORCELAIN)
1997 emit_porcelain(sb, ent, option);
1998 else {
1999 emit_other(sb, ent, option);
2004 static const char *get_next_line(const char *start, const char *end)
2006 const char *nl = memchr(start, '\n', end - start);
2007 return nl ? nl + 1 : end;
2011 * To allow quick access to the contents of nth line in the
2012 * final image, prepare an index in the scoreboard.
2014 static int prepare_lines(struct scoreboard *sb)
2016 const char *buf = sb->final_buf;
2017 unsigned long len = sb->final_buf_size;
2018 const char *end = buf + len;
2019 const char *p;
2020 int *lineno;
2021 int num = 0;
2023 for (p = buf; p < end; p = get_next_line(p, end))
2024 num++;
2026 ALLOC_ARRAY(sb->lineno, num + 1);
2027 lineno = sb->lineno;
2029 for (p = buf; p < end; p = get_next_line(p, end))
2030 *lineno++ = p - buf;
2032 *lineno = len;
2034 sb->num_lines = num;
2035 return sb->num_lines;
2039 * Add phony grafts for use with -S; this is primarily to
2040 * support git's cvsserver that wants to give a linear history
2041 * to its clients.
2043 static int read_ancestry(const char *graft_file)
2045 FILE *fp = fopen(graft_file, "r");
2046 struct strbuf buf = STRBUF_INIT;
2047 if (!fp)
2048 return -1;
2049 while (!strbuf_getwholeline(&buf, fp, '\n')) {
2050 /* The format is just "Commit Parent1 Parent2 ...\n" */
2051 struct commit_graft *graft = read_graft_line(buf.buf, buf.len);
2052 if (graft)
2053 register_commit_graft(graft, 0);
2055 fclose(fp);
2056 strbuf_release(&buf);
2057 return 0;
2060 static int update_auto_abbrev(int auto_abbrev, struct origin *suspect)
2062 const char *uniq = find_unique_abbrev(suspect->commit->object.oid.hash,
2063 auto_abbrev);
2064 int len = strlen(uniq);
2065 if (auto_abbrev < len)
2066 return len;
2067 return auto_abbrev;
2071 * How many columns do we need to show line numbers, authors,
2072 * and filenames?
2074 static void find_alignment(struct scoreboard *sb, int *option)
2076 int longest_src_lines = 0;
2077 int longest_dst_lines = 0;
2078 unsigned largest_score = 0;
2079 struct blame_entry *e;
2080 int compute_auto_abbrev = (abbrev < 0);
2081 int auto_abbrev = DEFAULT_ABBREV;
2083 for (e = sb->ent; e; e = e->next) {
2084 struct origin *suspect = e->suspect;
2085 int num;
2087 if (compute_auto_abbrev)
2088 auto_abbrev = update_auto_abbrev(auto_abbrev, suspect);
2089 if (strcmp(suspect->path, sb->path))
2090 *option |= OUTPUT_SHOW_NAME;
2091 num = strlen(suspect->path);
2092 if (longest_file < num)
2093 longest_file = num;
2094 if (!(suspect->commit->object.flags & METAINFO_SHOWN)) {
2095 struct commit_info ci;
2096 suspect->commit->object.flags |= METAINFO_SHOWN;
2097 get_commit_info(suspect->commit, &ci, 1);
2098 if (*option & OUTPUT_SHOW_EMAIL)
2099 num = utf8_strwidth(ci.author_mail.buf);
2100 else
2101 num = utf8_strwidth(ci.author.buf);
2102 if (longest_author < num)
2103 longest_author = num;
2104 commit_info_destroy(&ci);
2106 num = e->s_lno + e->num_lines;
2107 if (longest_src_lines < num)
2108 longest_src_lines = num;
2109 num = e->lno + e->num_lines;
2110 if (longest_dst_lines < num)
2111 longest_dst_lines = num;
2112 if (largest_score < ent_score(sb, e))
2113 largest_score = ent_score(sb, e);
2115 max_orig_digits = decimal_width(longest_src_lines);
2116 max_digits = decimal_width(longest_dst_lines);
2117 max_score_digits = decimal_width(largest_score);
2119 if (compute_auto_abbrev)
2120 /* one more abbrev length is needed for the boundary commit */
2121 abbrev = auto_abbrev + 1;
2125 * For debugging -- origin is refcounted, and this asserts that
2126 * we do not underflow.
2128 static void sanity_check_refcnt(struct scoreboard *sb)
2130 int baa = 0;
2131 struct blame_entry *ent;
2133 for (ent = sb->ent; ent; ent = ent->next) {
2134 /* Nobody should have zero or negative refcnt */
2135 if (ent->suspect->refcnt <= 0) {
2136 fprintf(stderr, "%s in %s has negative refcnt %d\n",
2137 ent->suspect->path,
2138 oid_to_hex(&ent->suspect->commit->object.oid),
2139 ent->suspect->refcnt);
2140 baa = 1;
2143 if (baa) {
2144 int opt = 0160;
2145 find_alignment(sb, &opt);
2146 output(sb, opt);
2147 die("Baa %d!", baa);
2151 static unsigned parse_score(const char *arg)
2153 char *end;
2154 unsigned long score = strtoul(arg, &end, 10);
2155 if (*end)
2156 return 0;
2157 return score;
2160 static const char *add_prefix(const char *prefix, const char *path)
2162 return prefix_path(prefix, prefix ? strlen(prefix) : 0, path);
2165 static int git_blame_config(const char *var, const char *value, void *cb)
2167 if (!strcmp(var, "blame.showroot")) {
2168 show_root = git_config_bool(var, value);
2169 return 0;
2171 if (!strcmp(var, "blame.blankboundary")) {
2172 blank_boundary = git_config_bool(var, value);
2173 return 0;
2175 if (!strcmp(var, "blame.showemail")) {
2176 int *output_option = cb;
2177 if (git_config_bool(var, value))
2178 *output_option |= OUTPUT_SHOW_EMAIL;
2179 else
2180 *output_option &= ~OUTPUT_SHOW_EMAIL;
2181 return 0;
2183 if (!strcmp(var, "blame.date")) {
2184 if (!value)
2185 return config_error_nonbool(var);
2186 parse_date_format(value, &blame_date_mode);
2187 return 0;
2190 if (git_diff_heuristic_config(var, value, cb) < 0)
2191 return -1;
2192 if (userdiff_config(var, value) < 0)
2193 return -1;
2195 return git_default_config(var, value, cb);
2198 static void verify_working_tree_path(struct commit *work_tree, const char *path)
2200 struct commit_list *parents;
2201 int pos;
2203 for (parents = work_tree->parents; parents; parents = parents->next) {
2204 const struct object_id *commit_oid = &parents->item->object.oid;
2205 struct object_id blob_oid;
2206 unsigned mode;
2208 if (!get_tree_entry(commit_oid->hash, path, blob_oid.hash, &mode) &&
2209 sha1_object_info(blob_oid.hash, NULL) == OBJ_BLOB)
2210 return;
2213 pos = cache_name_pos(path, strlen(path));
2214 if (pos >= 0)
2215 ; /* path is in the index */
2216 else if (-1 - pos < active_nr &&
2217 !strcmp(active_cache[-1 - pos]->name, path))
2218 ; /* path is in the index, unmerged */
2219 else
2220 die("no such path '%s' in HEAD", path);
2223 static struct commit_list **append_parent(struct commit_list **tail, const struct object_id *oid)
2225 struct commit *parent;
2227 parent = lookup_commit_reference(oid->hash);
2228 if (!parent)
2229 die("no such commit %s", oid_to_hex(oid));
2230 return &commit_list_insert(parent, tail)->next;
2233 static void append_merge_parents(struct commit_list **tail)
2235 int merge_head;
2236 struct strbuf line = STRBUF_INIT;
2238 merge_head = open(git_path_merge_head(), O_RDONLY);
2239 if (merge_head < 0) {
2240 if (errno == ENOENT)
2241 return;
2242 die("cannot open '%s' for reading", git_path_merge_head());
2245 while (!strbuf_getwholeline_fd(&line, merge_head, '\n')) {
2246 struct object_id oid;
2247 if (line.len < GIT_SHA1_HEXSZ || get_oid_hex(line.buf, &oid))
2248 die("unknown line in '%s': %s", git_path_merge_head(), line.buf);
2249 tail = append_parent(tail, &oid);
2251 close(merge_head);
2252 strbuf_release(&line);
2256 * This isn't as simple as passing sb->buf and sb->len, because we
2257 * want to transfer ownership of the buffer to the commit (so we
2258 * must use detach).
2260 static void set_commit_buffer_from_strbuf(struct commit *c, struct strbuf *sb)
2262 size_t len;
2263 void *buf = strbuf_detach(sb, &len);
2264 set_commit_buffer(c, buf, len);
2268 * Prepare a dummy commit that represents the work tree (or staged) item.
2269 * Note that annotating work tree item never works in the reverse.
2271 static struct commit *fake_working_tree_commit(struct diff_options *opt,
2272 const char *path,
2273 const char *contents_from)
2275 struct commit *commit;
2276 struct origin *origin;
2277 struct commit_list **parent_tail, *parent;
2278 struct object_id head_oid;
2279 struct strbuf buf = STRBUF_INIT;
2280 const char *ident;
2281 time_t now;
2282 int size, len;
2283 struct cache_entry *ce;
2284 unsigned mode;
2285 struct strbuf msg = STRBUF_INIT;
2287 read_cache();
2288 time(&now);
2289 commit = alloc_commit_node();
2290 commit->object.parsed = 1;
2291 commit->date = now;
2292 parent_tail = &commit->parents;
2294 if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, head_oid.hash, NULL))
2295 die("no such ref: HEAD");
2297 parent_tail = append_parent(parent_tail, &head_oid);
2298 append_merge_parents(parent_tail);
2299 verify_working_tree_path(commit, path);
2301 origin = make_origin(commit, path);
2303 ident = fmt_ident("Not Committed Yet", "not.committed.yet", NULL, 0);
2304 strbuf_addstr(&msg, "tree 0000000000000000000000000000000000000000\n");
2305 for (parent = commit->parents; parent; parent = parent->next)
2306 strbuf_addf(&msg, "parent %s\n",
2307 oid_to_hex(&parent->item->object.oid));
2308 strbuf_addf(&msg,
2309 "author %s\n"
2310 "committer %s\n\n"
2311 "Version of %s from %s\n",
2312 ident, ident, path,
2313 (!contents_from ? path :
2314 (!strcmp(contents_from, "-") ? "standard input" : contents_from)));
2315 set_commit_buffer_from_strbuf(commit, &msg);
2317 if (!contents_from || strcmp("-", contents_from)) {
2318 struct stat st;
2319 const char *read_from;
2320 char *buf_ptr;
2321 unsigned long buf_len;
2323 if (contents_from) {
2324 if (stat(contents_from, &st) < 0)
2325 die_errno("Cannot stat '%s'", contents_from);
2326 read_from = contents_from;
2328 else {
2329 if (lstat(path, &st) < 0)
2330 die_errno("Cannot lstat '%s'", path);
2331 read_from = path;
2333 mode = canon_mode(st.st_mode);
2335 switch (st.st_mode & S_IFMT) {
2336 case S_IFREG:
2337 if (DIFF_OPT_TST(opt, ALLOW_TEXTCONV) &&
2338 textconv_object(read_from, mode, &null_oid, 0, &buf_ptr, &buf_len))
2339 strbuf_attach(&buf, buf_ptr, buf_len, buf_len + 1);
2340 else if (strbuf_read_file(&buf, read_from, st.st_size) != st.st_size)
2341 die_errno("cannot open or read '%s'", read_from);
2342 break;
2343 case S_IFLNK:
2344 if (strbuf_readlink(&buf, read_from, st.st_size) < 0)
2345 die_errno("cannot readlink '%s'", read_from);
2346 break;
2347 default:
2348 die("unsupported file type %s", read_from);
2351 else {
2352 /* Reading from stdin */
2353 mode = 0;
2354 if (strbuf_read(&buf, 0, 0) < 0)
2355 die_errno("failed to read from stdin");
2357 convert_to_git(path, buf.buf, buf.len, &buf, 0);
2358 origin->file.ptr = buf.buf;
2359 origin->file.size = buf.len;
2360 pretend_sha1_file(buf.buf, buf.len, OBJ_BLOB, origin->blob_oid.hash);
2363 * Read the current index, replace the path entry with
2364 * origin->blob_sha1 without mucking with its mode or type
2365 * bits; we are not going to write this index out -- we just
2366 * want to run "diff-index --cached".
2368 discard_cache();
2369 read_cache();
2371 len = strlen(path);
2372 if (!mode) {
2373 int pos = cache_name_pos(path, len);
2374 if (0 <= pos)
2375 mode = active_cache[pos]->ce_mode;
2376 else
2377 /* Let's not bother reading from HEAD tree */
2378 mode = S_IFREG | 0644;
2380 size = cache_entry_size(len);
2381 ce = xcalloc(1, size);
2382 oidcpy(&ce->oid, &origin->blob_oid);
2383 memcpy(ce->name, path, len);
2384 ce->ce_flags = create_ce_flags(0);
2385 ce->ce_namelen = len;
2386 ce->ce_mode = create_ce_mode(mode);
2387 add_cache_entry(ce, ADD_CACHE_OK_TO_ADD|ADD_CACHE_OK_TO_REPLACE);
2389 cache_tree_invalidate_path(&the_index, path);
2391 return commit;
2394 static struct commit *find_single_final(struct rev_info *revs,
2395 const char **name_p)
2397 int i;
2398 struct commit *found = NULL;
2399 const char *name = NULL;
2401 for (i = 0; i < revs->pending.nr; i++) {
2402 struct object *obj = revs->pending.objects[i].item;
2403 if (obj->flags & UNINTERESTING)
2404 continue;
2405 obj = deref_tag(obj, NULL, 0);
2406 if (obj->type != OBJ_COMMIT)
2407 die("Non commit %s?", revs->pending.objects[i].name);
2408 if (found)
2409 die("More than one commit to dig from %s and %s?",
2410 revs->pending.objects[i].name, name);
2411 found = (struct commit *)obj;
2412 name = revs->pending.objects[i].name;
2414 if (name_p)
2415 *name_p = name;
2416 return found;
2419 static char *prepare_final(struct scoreboard *sb)
2421 const char *name;
2422 sb->final = find_single_final(sb->revs, &name);
2423 return xstrdup_or_null(name);
2426 static const char *dwim_reverse_initial(struct scoreboard *sb)
2429 * DWIM "git blame --reverse ONE -- PATH" as
2430 * "git blame --reverse ONE..HEAD -- PATH" but only do so
2431 * when it makes sense.
2433 struct object *obj;
2434 struct commit *head_commit;
2435 unsigned char head_sha1[20];
2437 if (sb->revs->pending.nr != 1)
2438 return NULL;
2440 /* Is that sole rev a committish? */
2441 obj = sb->revs->pending.objects[0].item;
2442 obj = deref_tag(obj, NULL, 0);
2443 if (obj->type != OBJ_COMMIT)
2444 return NULL;
2446 /* Do we have HEAD? */
2447 if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, head_sha1, NULL))
2448 return NULL;
2449 head_commit = lookup_commit_reference_gently(head_sha1, 1);
2450 if (!head_commit)
2451 return NULL;
2453 /* Turn "ONE" into "ONE..HEAD" then */
2454 obj->flags |= UNINTERESTING;
2455 add_pending_object(sb->revs, &head_commit->object, "HEAD");
2457 sb->final = (struct commit *)obj;
2458 return sb->revs->pending.objects[0].name;
2461 static char *prepare_initial(struct scoreboard *sb)
2463 int i;
2464 const char *final_commit_name = NULL;
2465 struct rev_info *revs = sb->revs;
2468 * There must be one and only one negative commit, and it must be
2469 * the boundary.
2471 for (i = 0; i < revs->pending.nr; i++) {
2472 struct object *obj = revs->pending.objects[i].item;
2473 if (!(obj->flags & UNINTERESTING))
2474 continue;
2475 obj = deref_tag(obj, NULL, 0);
2476 if (obj->type != OBJ_COMMIT)
2477 die("Non commit %s?", revs->pending.objects[i].name);
2478 if (sb->final)
2479 die("More than one commit to dig up from, %s and %s?",
2480 revs->pending.objects[i].name,
2481 final_commit_name);
2482 sb->final = (struct commit *) obj;
2483 final_commit_name = revs->pending.objects[i].name;
2486 if (!final_commit_name)
2487 final_commit_name = dwim_reverse_initial(sb);
2488 if (!final_commit_name)
2489 die("No commit to dig up from?");
2490 return xstrdup(final_commit_name);
2493 static int blame_copy_callback(const struct option *option, const char *arg, int unset)
2495 int *opt = option->value;
2498 * -C enables copy from removed files;
2499 * -C -C enables copy from existing files, but only
2500 * when blaming a new file;
2501 * -C -C -C enables copy from existing files for
2502 * everybody
2504 if (*opt & PICKAXE_BLAME_COPY_HARDER)
2505 *opt |= PICKAXE_BLAME_COPY_HARDEST;
2506 if (*opt & PICKAXE_BLAME_COPY)
2507 *opt |= PICKAXE_BLAME_COPY_HARDER;
2508 *opt |= PICKAXE_BLAME_COPY | PICKAXE_BLAME_MOVE;
2510 if (arg)
2511 blame_copy_score = parse_score(arg);
2512 return 0;
2515 static int blame_move_callback(const struct option *option, const char *arg, int unset)
2517 int *opt = option->value;
2519 *opt |= PICKAXE_BLAME_MOVE;
2521 if (arg)
2522 blame_move_score = parse_score(arg);
2523 return 0;
2526 int cmd_blame(int argc, const char **argv, const char *prefix)
2528 struct rev_info revs;
2529 const char *path;
2530 struct scoreboard sb;
2531 struct origin *o;
2532 struct blame_entry *ent = NULL;
2533 long dashdash_pos, lno;
2534 char *final_commit_name = NULL;
2535 enum object_type type;
2536 struct commit *final_commit = NULL;
2538 struct string_list range_list = STRING_LIST_INIT_NODUP;
2539 int output_option = 0, opt = 0;
2540 int show_stats = 0;
2541 const char *revs_file = NULL;
2542 const char *contents_from = NULL;
2543 const struct option options[] = {
2544 OPT_BOOL(0, "incremental", &incremental, N_("Show blame entries as we find them, incrementally")),
2545 OPT_BOOL('b', NULL, &blank_boundary, N_("Show blank SHA-1 for boundary commits (Default: off)")),
2546 OPT_BOOL(0, "root", &show_root, N_("Do not treat root commits as boundaries (Default: off)")),
2547 OPT_BOOL(0, "show-stats", &show_stats, N_("Show work cost statistics")),
2548 OPT_BOOL(0, "progress", &show_progress, N_("Force progress reporting")),
2549 OPT_BIT(0, "score-debug", &output_option, N_("Show output score for blame entries"), OUTPUT_SHOW_SCORE),
2550 OPT_BIT('f', "show-name", &output_option, N_("Show original filename (Default: auto)"), OUTPUT_SHOW_NAME),
2551 OPT_BIT('n', "show-number", &output_option, N_("Show original linenumber (Default: off)"), OUTPUT_SHOW_NUMBER),
2552 OPT_BIT('p', "porcelain", &output_option, N_("Show in a format designed for machine consumption"), OUTPUT_PORCELAIN),
2553 OPT_BIT(0, "line-porcelain", &output_option, N_("Show porcelain format with per-line commit information"), OUTPUT_PORCELAIN|OUTPUT_LINE_PORCELAIN),
2554 OPT_BIT('c', NULL, &output_option, N_("Use the same output mode as git-annotate (Default: off)"), OUTPUT_ANNOTATE_COMPAT),
2555 OPT_BIT('t', NULL, &output_option, N_("Show raw timestamp (Default: off)"), OUTPUT_RAW_TIMESTAMP),
2556 OPT_BIT('l', NULL, &output_option, N_("Show long commit SHA1 (Default: off)"), OUTPUT_LONG_OBJECT_NAME),
2557 OPT_BIT('s', NULL, &output_option, N_("Suppress author name and timestamp (Default: off)"), OUTPUT_NO_AUTHOR),
2558 OPT_BIT('e', "show-email", &output_option, N_("Show author email instead of name (Default: off)"), OUTPUT_SHOW_EMAIL),
2559 OPT_BIT('w', NULL, &xdl_opts, N_("Ignore whitespace differences"), XDF_IGNORE_WHITESPACE),
2562 * The following two options are parsed by parse_revision_opt()
2563 * and are only included here to get included in the "-h"
2564 * output:
2566 { OPTION_LOWLEVEL_CALLBACK, 0, "indent-heuristic", NULL, NULL, N_("Use an experimental heuristic to improve diffs"), PARSE_OPT_NOARG, parse_opt_unknown_cb },
2568 OPT_BIT(0, "minimal", &xdl_opts, N_("Spend extra cycles to find better match"), XDF_NEED_MINIMAL),
2569 OPT_STRING('S', NULL, &revs_file, N_("file"), N_("Use revisions from <file> instead of calling git-rev-list")),
2570 OPT_STRING(0, "contents", &contents_from, N_("file"), N_("Use <file>'s contents as the final image")),
2571 { OPTION_CALLBACK, 'C', NULL, &opt, N_("score"), N_("Find line copies within and across files"), PARSE_OPT_OPTARG, blame_copy_callback },
2572 { OPTION_CALLBACK, 'M', NULL, &opt, N_("score"), N_("Find line movements within and across files"), PARSE_OPT_OPTARG, blame_move_callback },
2573 OPT_STRING_LIST('L', NULL, &range_list, N_("n,m"), N_("Process only line range n,m, counting from 1")),
2574 OPT__ABBREV(&abbrev),
2575 OPT_END()
2578 struct parse_opt_ctx_t ctx;
2579 int cmd_is_annotate = !strcmp(argv[0], "annotate");
2580 struct range_set ranges;
2581 unsigned int range_i;
2582 long anchor;
2584 git_config(git_blame_config, &output_option);
2585 init_revisions(&revs, NULL);
2586 revs.date_mode = blame_date_mode;
2587 DIFF_OPT_SET(&revs.diffopt, ALLOW_TEXTCONV);
2588 DIFF_OPT_SET(&revs.diffopt, FOLLOW_RENAMES);
2590 save_commit_buffer = 0;
2591 dashdash_pos = 0;
2592 show_progress = -1;
2594 parse_options_start(&ctx, argc, argv, prefix, options,
2595 PARSE_OPT_KEEP_DASHDASH | PARSE_OPT_KEEP_ARGV0);
2596 for (;;) {
2597 switch (parse_options_step(&ctx, options, blame_opt_usage)) {
2598 case PARSE_OPT_HELP:
2599 exit(129);
2600 case PARSE_OPT_DONE:
2601 if (ctx.argv[0])
2602 dashdash_pos = ctx.cpidx;
2603 goto parse_done;
2606 if (!strcmp(ctx.argv[0], "--reverse")) {
2607 ctx.argv[0] = "--children";
2608 reverse = 1;
2610 parse_revision_opt(&revs, &ctx, options, blame_opt_usage);
2612 parse_done:
2613 no_whole_file_rename = !DIFF_OPT_TST(&revs.diffopt, FOLLOW_RENAMES);
2614 xdl_opts |= revs.diffopt.xdl_opts & XDF_INDENT_HEURISTIC;
2615 DIFF_OPT_CLR(&revs.diffopt, FOLLOW_RENAMES);
2616 argc = parse_options_end(&ctx);
2618 if (incremental || (output_option & OUTPUT_PORCELAIN)) {
2619 if (show_progress > 0)
2620 die(_("--progress can't be used with --incremental or porcelain formats"));
2621 show_progress = 0;
2622 } else if (show_progress < 0)
2623 show_progress = isatty(2);
2625 if (0 < abbrev && abbrev < GIT_SHA1_HEXSZ)
2626 /* one more abbrev length is needed for the boundary commit */
2627 abbrev++;
2628 else if (!abbrev)
2629 abbrev = GIT_SHA1_HEXSZ;
2631 if (revs_file && read_ancestry(revs_file))
2632 die_errno("reading graft file '%s' failed", revs_file);
2634 if (cmd_is_annotate) {
2635 output_option |= OUTPUT_ANNOTATE_COMPAT;
2636 blame_date_mode.type = DATE_ISO8601;
2637 } else {
2638 blame_date_mode = revs.date_mode;
2641 /* The maximum width used to show the dates */
2642 switch (blame_date_mode.type) {
2643 case DATE_RFC2822:
2644 blame_date_width = sizeof("Thu, 19 Oct 2006 16:00:04 -0700");
2645 break;
2646 case DATE_ISO8601_STRICT:
2647 blame_date_width = sizeof("2006-10-19T16:00:04-07:00");
2648 break;
2649 case DATE_ISO8601:
2650 blame_date_width = sizeof("2006-10-19 16:00:04 -0700");
2651 break;
2652 case DATE_RAW:
2653 blame_date_width = sizeof("1161298804 -0700");
2654 break;
2655 case DATE_UNIX:
2656 blame_date_width = sizeof("1161298804");
2657 break;
2658 case DATE_SHORT:
2659 blame_date_width = sizeof("2006-10-19");
2660 break;
2661 case DATE_RELATIVE:
2662 /* TRANSLATORS: This string is used to tell us the maximum
2663 display width for a relative timestamp in "git blame"
2664 output. For C locale, "4 years, 11 months ago", which
2665 takes 22 places, is the longest among various forms of
2666 relative timestamps, but your language may need more or
2667 fewer display columns. */
2668 blame_date_width = utf8_strwidth(_("4 years, 11 months ago")) + 1; /* add the null */
2669 break;
2670 case DATE_NORMAL:
2671 blame_date_width = sizeof("Thu Oct 19 16:00:04 2006 -0700");
2672 break;
2673 case DATE_STRFTIME:
2674 blame_date_width = strlen(show_date(0, 0, &blame_date_mode)) + 1; /* add the null */
2675 break;
2677 blame_date_width -= 1; /* strip the null */
2679 if (DIFF_OPT_TST(&revs.diffopt, FIND_COPIES_HARDER))
2680 opt |= (PICKAXE_BLAME_COPY | PICKAXE_BLAME_MOVE |
2681 PICKAXE_BLAME_COPY_HARDER);
2683 if (!blame_move_score)
2684 blame_move_score = BLAME_DEFAULT_MOVE_SCORE;
2685 if (!blame_copy_score)
2686 blame_copy_score = BLAME_DEFAULT_COPY_SCORE;
2689 * We have collected options unknown to us in argv[1..unk]
2690 * which are to be passed to revision machinery if we are
2691 * going to do the "bottom" processing.
2693 * The remaining are:
2695 * (1) if dashdash_pos != 0, it is either
2696 * "blame [revisions] -- <path>" or
2697 * "blame -- <path> <rev>"
2699 * (2) otherwise, it is one of the two:
2700 * "blame [revisions] <path>"
2701 * "blame <path> <rev>"
2703 * Note that we must strip out <path> from the arguments: we do not
2704 * want the path pruning but we may want "bottom" processing.
2706 if (dashdash_pos) {
2707 switch (argc - dashdash_pos - 1) {
2708 case 2: /* (1b) */
2709 if (argc != 4)
2710 usage_with_options(blame_opt_usage, options);
2711 /* reorder for the new way: <rev> -- <path> */
2712 argv[1] = argv[3];
2713 argv[3] = argv[2];
2714 argv[2] = "--";
2715 /* FALLTHROUGH */
2716 case 1: /* (1a) */
2717 path = add_prefix(prefix, argv[--argc]);
2718 argv[argc] = NULL;
2719 break;
2720 default:
2721 usage_with_options(blame_opt_usage, options);
2723 } else {
2724 if (argc < 2)
2725 usage_with_options(blame_opt_usage, options);
2726 path = add_prefix(prefix, argv[argc - 1]);
2727 if (argc == 3 && !file_exists(path)) { /* (2b) */
2728 path = add_prefix(prefix, argv[1]);
2729 argv[1] = argv[2];
2731 argv[argc - 1] = "--";
2733 setup_work_tree();
2734 if (!file_exists(path))
2735 die_errno("cannot stat path '%s'", path);
2738 revs.disable_stdin = 1;
2739 setup_revisions(argc, argv, &revs, NULL);
2740 memset(&sb, 0, sizeof(sb));
2742 sb.revs = &revs;
2743 if (!reverse) {
2744 final_commit_name = prepare_final(&sb);
2745 sb.commits.compare = compare_commits_by_commit_date;
2747 else if (contents_from)
2748 die(_("--contents and --reverse do not blend well."));
2749 else {
2750 final_commit_name = prepare_initial(&sb);
2751 sb.commits.compare = compare_commits_by_reverse_commit_date;
2752 if (revs.first_parent_only)
2753 revs.children.name = NULL;
2756 if (!sb.final) {
2758 * "--not A B -- path" without anything positive;
2759 * do not default to HEAD, but use the working tree
2760 * or "--contents".
2762 setup_work_tree();
2763 sb.final = fake_working_tree_commit(&sb.revs->diffopt,
2764 path, contents_from);
2765 add_pending_object(&revs, &(sb.final->object), ":");
2767 else if (contents_from)
2768 die(_("cannot use --contents with final commit object name"));
2770 if (reverse && revs.first_parent_only) {
2771 final_commit = find_single_final(sb.revs, NULL);
2772 if (!final_commit)
2773 die(_("--reverse and --first-parent together require specified latest commit"));
2777 * If we have bottom, this will mark the ancestors of the
2778 * bottom commits we would reach while traversing as
2779 * uninteresting.
2781 if (prepare_revision_walk(&revs))
2782 die(_("revision walk setup failed"));
2784 if (reverse && revs.first_parent_only) {
2785 struct commit *c = final_commit;
2787 sb.revs->children.name = "children";
2788 while (c->parents &&
2789 oidcmp(&c->object.oid, &sb.final->object.oid)) {
2790 struct commit_list *l = xcalloc(1, sizeof(*l));
2792 l->item = c;
2793 if (add_decoration(&sb.revs->children,
2794 &c->parents->item->object, l))
2795 die("BUG: not unique item in first-parent chain");
2796 c = c->parents->item;
2799 if (oidcmp(&c->object.oid, &sb.final->object.oid))
2800 die(_("--reverse --first-parent together require range along first-parent chain"));
2803 if (is_null_oid(&sb.final->object.oid)) {
2804 o = sb.final->util;
2805 sb.final_buf = xmemdupz(o->file.ptr, o->file.size);
2806 sb.final_buf_size = o->file.size;
2808 else {
2809 o = get_origin(&sb, sb.final, path);
2810 if (fill_blob_sha1_and_mode(o))
2811 die(_("no such path %s in %s"), path, final_commit_name);
2813 if (DIFF_OPT_TST(&sb.revs->diffopt, ALLOW_TEXTCONV) &&
2814 textconv_object(path, o->mode, &o->blob_oid, 1, (char **) &sb.final_buf,
2815 &sb.final_buf_size))
2817 else
2818 sb.final_buf = read_sha1_file(o->blob_oid.hash, &type,
2819 &sb.final_buf_size);
2821 if (!sb.final_buf)
2822 die(_("cannot read blob %s for path %s"),
2823 oid_to_hex(&o->blob_oid),
2824 path);
2826 num_read_blob++;
2827 lno = prepare_lines(&sb);
2829 if (lno && !range_list.nr)
2830 string_list_append(&range_list, "1");
2832 anchor = 1;
2833 range_set_init(&ranges, range_list.nr);
2834 for (range_i = 0; range_i < range_list.nr; ++range_i) {
2835 long bottom, top;
2836 if (parse_range_arg(range_list.items[range_i].string,
2837 nth_line_cb, &sb, lno, anchor,
2838 &bottom, &top, sb.path))
2839 usage(blame_usage);
2840 if (lno < top || ((lno || bottom) && lno < bottom))
2841 die(Q_("file %s has only %lu line",
2842 "file %s has only %lu lines",
2843 lno), path, lno);
2844 if (bottom < 1)
2845 bottom = 1;
2846 if (top < 1)
2847 top = lno;
2848 bottom--;
2849 range_set_append_unsafe(&ranges, bottom, top);
2850 anchor = top + 1;
2852 sort_and_merge_range_set(&ranges);
2854 for (range_i = ranges.nr; range_i > 0; --range_i) {
2855 const struct range *r = &ranges.ranges[range_i - 1];
2856 long bottom = r->start;
2857 long top = r->end;
2858 struct blame_entry *next = ent;
2859 ent = xcalloc(1, sizeof(*ent));
2860 ent->lno = bottom;
2861 ent->num_lines = top - bottom;
2862 ent->suspect = o;
2863 ent->s_lno = bottom;
2864 ent->next = next;
2865 origin_incref(o);
2868 o->suspects = ent;
2869 prio_queue_put(&sb.commits, o->commit);
2871 origin_decref(o);
2873 range_set_release(&ranges);
2874 string_list_clear(&range_list, 0);
2876 sb.ent = NULL;
2877 sb.path = path;
2879 read_mailmap(&mailmap, NULL);
2881 assign_blame(&sb, opt);
2883 if (!incremental)
2884 setup_pager();
2886 free(final_commit_name);
2888 if (incremental)
2889 return 0;
2891 sb.ent = blame_sort(sb.ent, compare_blame_final);
2893 coalesce(&sb);
2895 if (!(output_option & OUTPUT_PORCELAIN))
2896 find_alignment(&sb, &output_option);
2898 output(&sb, output_option);
2899 free((void *)sb.final_buf);
2900 for (ent = sb.ent; ent; ) {
2901 struct blame_entry *e = ent->next;
2902 free(ent);
2903 ent = e;
2906 if (show_stats) {
2907 printf("num read blob: %d\n", num_read_blob);
2908 printf("num get patch: %d\n", num_get_patch);
2909 printf("num commits: %d\n", num_commits);
2911 return 0;