4 * Copyright (c) 2006, Junio C Hamano
12 #include "tree-walk.h"
16 #include "xdiff-interface.h"
22 static char blame_usage[] =
23 "git-blame [-c] [-l] [-t] [-f] [-n] [-p] [-L n,m] [-S <revs-file>] [-M] [-C] [-C] [commit] [--] file\n"
24 " -c, --compatibility Use the same output mode as git-annotate (Default: off)\n"
25 " -b Show blank SHA-1 for boundary commits (Default: off)\n"
26 " -l, --long Show long commit SHA1 (Default: off)\n"
27 " --root Do not treat root commits as boundaries (Default: off)\n"
28 " -t, --time Show raw timestamp (Default: off)\n"
29 " -f, --show-name Show original filename (Default: auto)\n"
30 " -n, --show-number Show original linenumber (Default: off)\n"
31 " -p, --porcelain Show in a format designed for machine consumption\n"
32 " -L n,m Process only line range n,m, counting from 1\n"
33 " -M, -C Find line movements within and across files\n"
34 " -S revs-file Use revisions from revs-file instead of calling git-rev-list\n";
36 static int longest_file;
37 static int longest_author;
38 static int max_orig_digits;
39 static int max_digits;
40 static int max_score_digits;
42 static int blank_boundary;
49 static int num_read_blob;
50 static int num_get_patch;
51 static int num_commits;
53 #define PICKAXE_BLAME_MOVE 01
54 #define PICKAXE_BLAME_COPY 02
55 #define PICKAXE_BLAME_COPY_HARDER 04
58 * blame for a blame_entry with score lower than these thresholds
59 * is not passed to the parent using move/copy logic.
61 static unsigned blame_move_score;
62 static unsigned blame_copy_score;
63 #define BLAME_DEFAULT_MOVE_SCORE 20
64 #define BLAME_DEFAULT_COPY_SCORE 40
66 /* bits #0..7 in revision.h, #8..11 used for merge_bases() in commit.c */
67 #define METAINFO_SHOWN (1u<<12)
68 #define MORE_THAN_ONE_PATH (1u<<13)
71 * One blob in a commit that is being suspected
75 struct commit *commit;
77 unsigned char blob_sha1[20];
78 char path[FLEX_ARRAY];
81 static char *fill_origin_blob(struct origin *o, mmfile_t *file)
86 file->ptr = read_sha1_file(o->blob_sha1, type,
87 (unsigned long *)(&(file->size)));
95 static inline struct origin *origin_incref(struct origin *o)
102 static void origin_decref(struct origin *o)
104 if (o && --o->refcnt <= 0) {
107 memset(o, 0, sizeof(*o));
113 struct blame_entry *prev;
114 struct blame_entry *next;
116 /* the first line of this group in the final image;
117 * internally all line numbers are 0 based.
121 /* how many lines this group has */
124 /* the commit that introduced this group into the final image */
125 struct origin *suspect;
127 /* true if the suspect is truly guilty; false while we have not
128 * checked if the group came from one of its parents.
132 /* the line number of the first line of this group in the
133 * suspect's file; internally all line numbers are 0 based.
137 /* how significant this entry is -- cached to avoid
138 * scanning the lines over and over
144 /* the final commit (i.e. where we started digging from) */
145 struct commit *final;
149 /* the contents in the final; pointed into by buf pointers of
152 const char *final_buf;
153 unsigned long final_buf_size;
155 /* linked list of blames */
156 struct blame_entry *ent;
158 /* look-up a line in the final buffer */
163 static int cmp_suspect(struct origin *a, struct origin *b)
165 int cmp = hashcmp(a->commit->object.sha1, b->commit->object.sha1);
168 return strcmp(a->path, b->path);
171 #define cmp_suspect(a, b) ( ((a)==(b)) ? 0 : cmp_suspect(a,b) )
173 static void sanity_check_refcnt(struct scoreboard *);
175 static void coalesce(struct scoreboard *sb)
177 struct blame_entry *ent, *next;
179 for (ent = sb->ent; ent && (next = ent->next); ent = next) {
180 if (!cmp_suspect(ent->suspect, next->suspect) &&
181 ent->guilty == next->guilty &&
182 ent->s_lno + ent->num_lines == next->s_lno) {
183 ent->num_lines += next->num_lines;
184 ent->next = next->next;
186 ent->next->prev = ent;
187 origin_decref(next->suspect);
190 next = ent; /* again */
194 if (DEBUG) /* sanity */
195 sanity_check_refcnt(sb);
198 static struct origin *make_origin(struct commit *commit, const char *path)
201 o = xcalloc(1, sizeof(*o) + strlen(path) + 1);
204 strcpy(o->path, path);
208 static struct origin *get_origin(struct scoreboard *sb,
209 struct commit *commit,
212 struct blame_entry *e;
214 for (e = sb->ent; e; e = e->next) {
215 if (e->suspect->commit == commit &&
216 !strcmp(e->suspect->path, path))
217 return origin_incref(e->suspect);
219 return make_origin(commit, path);
222 static int fill_blob_sha1(struct origin *origin)
227 if (!is_null_sha1(origin->blob_sha1))
229 if (get_tree_entry(origin->commit->object.sha1,
231 origin->blob_sha1, &mode))
233 if (sha1_object_info(origin->blob_sha1, type, NULL) ||
234 strcmp(type, blob_type))
238 hashclr(origin->blob_sha1);
242 static struct origin *find_origin(struct scoreboard *sb,
243 struct commit *parent,
244 struct origin *origin)
246 struct origin *porigin = NULL;
247 struct diff_options diff_opts;
248 const char *paths[2];
251 /* This is a freestanding copy of origin and not
254 struct origin *cached = parent->util;
255 if (!strcmp(cached->path, origin->path)) {
256 porigin = get_origin(sb, parent, cached->path);
257 if (porigin->refcnt == 1)
258 hashcpy(porigin->blob_sha1, cached->blob_sha1);
261 /* otherwise it was not very useful; free it */
266 /* See if the origin->path is different between parent
267 * and origin first. Most of the time they are the
268 * same and diff-tree is fairly efficient about this.
270 diff_setup(&diff_opts);
271 diff_opts.recursive = 1;
272 diff_opts.detect_rename = 0;
273 diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;
274 paths[0] = origin->path;
277 diff_tree_setup_paths(paths, &diff_opts);
278 if (diff_setup_done(&diff_opts) < 0)
280 diff_tree_sha1(parent->tree->object.sha1,
281 origin->commit->tree->object.sha1,
283 diffcore_std(&diff_opts);
285 /* It is either one entry that says "modified", or "created",
288 if (!diff_queued_diff.nr) {
289 /* The path is the same as parent */
290 porigin = get_origin(sb, parent, origin->path);
291 hashcpy(porigin->blob_sha1, origin->blob_sha1);
293 else if (diff_queued_diff.nr != 1)
294 die("internal error in blame::find_origin");
296 struct diff_filepair *p = diff_queued_diff.queue[0];
299 die("internal error in blame::find_origin (%c)",
302 porigin = get_origin(sb, parent, origin->path);
303 hashcpy(porigin->blob_sha1, p->one->sha1);
307 /* Did not exist in parent, or type changed */
311 diff_flush(&diff_opts);
313 struct origin *cached;
314 cached = make_origin(porigin->commit, porigin->path);
315 hashcpy(cached->blob_sha1, porigin->blob_sha1);
316 parent->util = cached;
321 static struct origin *find_rename(struct scoreboard *sb,
322 struct commit *parent,
323 struct origin *origin)
325 struct origin *porigin = NULL;
326 struct diff_options diff_opts;
328 const char *paths[2];
330 diff_setup(&diff_opts);
331 diff_opts.recursive = 1;
332 diff_opts.detect_rename = DIFF_DETECT_RENAME;
333 diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;
334 diff_opts.single_follow = origin->path;
336 diff_tree_setup_paths(paths, &diff_opts);
337 if (diff_setup_done(&diff_opts) < 0)
339 diff_tree_sha1(parent->tree->object.sha1,
340 origin->commit->tree->object.sha1,
342 diffcore_std(&diff_opts);
344 for (i = 0; i < diff_queued_diff.nr; i++) {
345 struct diff_filepair *p = diff_queued_diff.queue[i];
346 if ((p->status == 'R' || p->status == 'C') &&
347 !strcmp(p->two->path, origin->path)) {
348 porigin = get_origin(sb, parent, p->one->path);
349 hashcpy(porigin->blob_sha1, p->one->sha1);
353 diff_flush(&diff_opts);
358 /* line number in postimage; up to but not including this
359 * line is the same as preimage
363 /* preimage line number after this chunk */
366 /* postimage line number after this chunk */
371 struct chunk *chunks;
375 struct blame_diff_state {
376 struct xdiff_emit_state xm;
378 unsigned hunk_post_context;
379 unsigned hunk_in_pre_context : 1;
382 static void process_u_diff(void *state_, char *line, unsigned long len)
384 struct blame_diff_state *state = state_;
386 int off1, off2, len1, len2, num;
388 num = state->ret->num;
389 if (len < 4 || line[0] != '@' || line[1] != '@') {
390 if (state->hunk_in_pre_context && line[0] == ' ')
391 state->ret->chunks[num - 1].same++;
393 state->hunk_in_pre_context = 0;
395 state->hunk_post_context++;
397 state->hunk_post_context = 0;
402 if (num && state->hunk_post_context) {
403 chunk = &state->ret->chunks[num - 1];
404 chunk->p_next -= state->hunk_post_context;
405 chunk->t_next -= state->hunk_post_context;
407 state->ret->num = ++num;
408 state->ret->chunks = xrealloc(state->ret->chunks,
409 sizeof(struct chunk) * num);
410 chunk = &state->ret->chunks[num - 1];
411 if (parse_hunk_header(line, len, &off1, &len1, &off2, &len2)) {
416 /* Line numbers in patch output are one based. */
420 chunk->same = len2 ? off2 : (off2 + 1);
422 chunk->p_next = off1 + (len1 ? len1 : 1);
423 chunk->t_next = chunk->same + len2;
424 state->hunk_in_pre_context = 1;
425 state->hunk_post_context = 0;
428 static struct patch *compare_buffer(mmfile_t *file_p, mmfile_t *file_o,
431 struct blame_diff_state state;
436 xpp.flags = XDF_NEED_MINIMAL;
437 xecfg.ctxlen = context;
439 ecb.outf = xdiff_outf;
441 memset(&state, 0, sizeof(state));
442 state.xm.consume = process_u_diff;
443 state.ret = xmalloc(sizeof(struct patch));
444 state.ret->chunks = NULL;
447 xdl_diff(file_p, file_o, &xpp, &xecfg, &ecb);
449 if (state.ret->num) {
451 chunk = &state.ret->chunks[state.ret->num - 1];
452 chunk->p_next -= state.hunk_post_context;
453 chunk->t_next -= state.hunk_post_context;
458 static struct patch *get_patch(struct origin *parent, struct origin *origin)
460 mmfile_t file_p, file_o;
463 fill_origin_blob(parent, &file_p);
464 fill_origin_blob(origin, &file_o);
465 if (!file_p.ptr || !file_o.ptr)
467 patch = compare_buffer(&file_p, &file_o, 0);
472 static void free_patch(struct patch *p)
478 static void add_blame_entry(struct scoreboard *sb, struct blame_entry *e)
480 struct blame_entry *ent, *prev = NULL;
482 origin_incref(e->suspect);
484 for (ent = sb->ent; ent && ent->lno < e->lno; ent = ent->next)
487 /* prev, if not NULL, is the last one that is below e */
490 e->next = prev->next;
501 static void dup_entry(struct blame_entry *dst, struct blame_entry *src)
503 struct blame_entry *p, *n;
507 origin_incref(src->suspect);
508 origin_decref(dst->suspect);
509 memcpy(dst, src, sizeof(*src));
515 static const char *nth_line(struct scoreboard *sb, int lno)
517 return sb->final_buf + sb->lineno[lno];
520 static void split_overlap(struct blame_entry *split,
521 struct blame_entry *e,
522 int tlno, int plno, int same,
523 struct origin *parent)
525 /* it is known that lines between tlno to same came from
526 * parent, and e has an overlap with that range. it also is
527 * known that parent's line plno corresponds to e's line tlno.
533 * <------------------>
535 * Potentially we need to split e into three parts; before
536 * this chunk, the chunk to be blamed for parent, and after
540 memset(split, 0, sizeof(struct blame_entry [3]));
542 if (e->s_lno < tlno) {
543 /* there is a pre-chunk part not blamed on parent */
544 split[0].suspect = origin_incref(e->suspect);
545 split[0].lno = e->lno;
546 split[0].s_lno = e->s_lno;
547 split[0].num_lines = tlno - e->s_lno;
548 split[1].lno = e->lno + tlno - e->s_lno;
549 split[1].s_lno = plno;
552 split[1].lno = e->lno;
553 split[1].s_lno = plno + (e->s_lno - tlno);
556 if (same < e->s_lno + e->num_lines) {
557 /* there is a post-chunk part not blamed on parent */
558 split[2].suspect = origin_incref(e->suspect);
559 split[2].lno = e->lno + (same - e->s_lno);
560 split[2].s_lno = e->s_lno + (same - e->s_lno);
561 split[2].num_lines = e->s_lno + e->num_lines - same;
562 chunk_end_lno = split[2].lno;
565 chunk_end_lno = e->lno + e->num_lines;
566 split[1].num_lines = chunk_end_lno - split[1].lno;
568 if (split[1].num_lines < 1)
570 split[1].suspect = origin_incref(parent);
573 static void split_blame(struct scoreboard *sb,
574 struct blame_entry *split,
575 struct blame_entry *e)
577 struct blame_entry *new_entry;
579 if (split[0].suspect && split[2].suspect) {
580 /* we need to split e into two and add another for parent */
581 dup_entry(e, &split[0]);
583 new_entry = xmalloc(sizeof(*new_entry));
584 memcpy(new_entry, &(split[2]), sizeof(struct blame_entry));
585 add_blame_entry(sb, new_entry);
587 new_entry = xmalloc(sizeof(*new_entry));
588 memcpy(new_entry, &(split[1]), sizeof(struct blame_entry));
589 add_blame_entry(sb, new_entry);
591 else if (!split[0].suspect && !split[2].suspect)
592 /* parent covers the entire area */
593 dup_entry(e, &split[1]);
594 else if (split[0].suspect) {
595 dup_entry(e, &split[0]);
597 new_entry = xmalloc(sizeof(*new_entry));
598 memcpy(new_entry, &(split[1]), sizeof(struct blame_entry));
599 add_blame_entry(sb, new_entry);
602 dup_entry(e, &split[1]);
604 new_entry = xmalloc(sizeof(*new_entry));
605 memcpy(new_entry, &(split[2]), sizeof(struct blame_entry));
606 add_blame_entry(sb, new_entry);
609 if (DEBUG) { /* sanity */
610 struct blame_entry *ent;
611 int lno = sb->ent->lno, corrupt = 0;
613 for (ent = sb->ent; ent; ent = ent->next) {
618 lno += ent->num_lines;
622 for (ent = sb->ent; ent; ent = ent->next) {
623 printf("L %8d l %8d n %8d\n",
624 lno, ent->lno, ent->num_lines);
625 lno = ent->lno + ent->num_lines;
632 static void decref_split(struct blame_entry *split)
636 for (i = 0; i < 3; i++)
637 origin_decref(split[i].suspect);
640 static void blame_overlap(struct scoreboard *sb, struct blame_entry *e,
641 int tlno, int plno, int same,
642 struct origin *parent)
644 struct blame_entry split[3];
646 split_overlap(split, e, tlno, plno, same, parent);
647 if (split[1].suspect)
648 split_blame(sb, split, e);
652 static int find_last_in_target(struct scoreboard *sb, struct origin *target)
654 struct blame_entry *e;
655 int last_in_target = -1;
657 for (e = sb->ent; e; e = e->next) {
658 if (e->guilty || cmp_suspect(e->suspect, target))
660 if (last_in_target < e->s_lno + e->num_lines)
661 last_in_target = e->s_lno + e->num_lines;
663 return last_in_target;
666 static void blame_chunk(struct scoreboard *sb,
667 int tlno, int plno, int same,
668 struct origin *target, struct origin *parent)
670 struct blame_entry *e;
672 for (e = sb->ent; e; e = e->next) {
673 if (e->guilty || cmp_suspect(e->suspect, target))
675 if (same <= e->s_lno)
677 if (tlno < e->s_lno + e->num_lines)
678 blame_overlap(sb, e, tlno, plno, same, parent);
682 static int pass_blame_to_parent(struct scoreboard *sb,
683 struct origin *target,
684 struct origin *parent)
686 int i, last_in_target, plno, tlno;
689 last_in_target = find_last_in_target(sb, target);
690 if (last_in_target < 0)
691 return 1; /* nothing remains for this target */
693 patch = get_patch(parent, target);
695 for (i = 0; i < patch->num; i++) {
696 struct chunk *chunk = &patch->chunks[i];
698 blame_chunk(sb, tlno, plno, chunk->same, target, parent);
699 plno = chunk->p_next;
700 tlno = chunk->t_next;
702 /* rest (i.e. anything above tlno) are the same as parent */
703 blame_chunk(sb, tlno, plno, last_in_target, target, parent);
709 static unsigned ent_score(struct scoreboard *sb, struct blame_entry *e)
718 cp = nth_line(sb, e->lno);
719 ep = nth_line(sb, e->lno + e->num_lines);
721 unsigned ch = *((unsigned char *)cp);
730 static void copy_split_if_better(struct scoreboard *sb,
731 struct blame_entry *best_so_far,
732 struct blame_entry *this)
736 if (!this[1].suspect)
738 if (best_so_far[1].suspect) {
739 if (ent_score(sb, &this[1]) < ent_score(sb, &best_so_far[1]))
743 for (i = 0; i < 3; i++)
744 origin_incref(this[i].suspect);
745 decref_split(best_so_far);
746 memcpy(best_so_far, this, sizeof(struct blame_entry [3]));
749 static void find_copy_in_blob(struct scoreboard *sb,
750 struct blame_entry *ent,
751 struct origin *parent,
752 struct blame_entry *split,
761 cp = nth_line(sb, ent->lno);
762 file_o.ptr = (char*) cp;
763 cnt = ent->num_lines;
765 while (cnt && cp < sb->final_buf + sb->final_buf_size) {
769 file_o.size = cp - file_o.ptr;
771 patch = compare_buffer(file_p, &file_o, 1);
773 memset(split, 0, sizeof(struct blame_entry [3]));
775 for (i = 0; i < patch->num; i++) {
776 struct chunk *chunk = &patch->chunks[i];
778 /* tlno to chunk->same are the same as ent */
779 if (ent->num_lines <= tlno)
781 if (tlno < chunk->same) {
782 struct blame_entry this[3];
783 split_overlap(this, ent,
784 tlno + ent->s_lno, plno,
785 chunk->same + ent->s_lno,
787 copy_split_if_better(sb, split, this);
790 plno = chunk->p_next;
791 tlno = chunk->t_next;
796 static int find_move_in_parent(struct scoreboard *sb,
797 struct origin *target,
798 struct origin *parent)
800 int last_in_target, made_progress;
801 struct blame_entry *e, split[3];
804 last_in_target = find_last_in_target(sb, target);
805 if (last_in_target < 0)
806 return 1; /* nothing remains for this target */
808 fill_origin_blob(parent, &file_p);
813 while (made_progress) {
815 for (e = sb->ent; e; e = e->next) {
816 if (e->guilty || cmp_suspect(e->suspect, target))
818 find_copy_in_blob(sb, e, parent, split, &file_p);
819 if (split[1].suspect &&
820 blame_move_score < ent_score(sb, &split[1])) {
821 split_blame(sb, split, e);
832 struct blame_entry *ent;
833 struct blame_entry split[3];
836 static struct blame_list *setup_blame_list(struct scoreboard *sb,
837 struct origin *target,
840 struct blame_entry *e;
842 struct blame_list *blame_list = NULL;
844 /* Count the number of entries the target is suspected for,
845 * and prepare a list of entry and the best split.
847 for (e = sb->ent, num_ents = 0; e; e = e->next)
848 if (!e->guilty && !cmp_suspect(e->suspect, target))
851 blame_list = xcalloc(num_ents, sizeof(struct blame_list));
852 for (e = sb->ent, i = 0; e; e = e->next)
853 if (!e->guilty && !cmp_suspect(e->suspect, target))
854 blame_list[i++].ent = e;
856 *num_ents_p = num_ents;
860 static int find_copy_in_parent(struct scoreboard *sb,
861 struct origin *target,
862 struct commit *parent,
863 struct origin *porigin,
866 struct diff_options diff_opts;
867 const char *paths[1];
870 struct blame_list *blame_list;
873 blame_list = setup_blame_list(sb, target, &num_ents);
875 return 1; /* nothing remains for this target */
877 diff_setup(&diff_opts);
878 diff_opts.recursive = 1;
879 diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;
882 diff_tree_setup_paths(paths, &diff_opts);
883 if (diff_setup_done(&diff_opts) < 0)
886 /* Try "find copies harder" on new path if requested;
887 * we do not want to use diffcore_rename() actually to
888 * match things up; find_copies_harder is set only to
889 * force diff_tree_sha1() to feed all filepairs to diff_queue,
890 * and this code needs to be after diff_setup_done(), which
891 * usually makes find-copies-harder imply copy detection.
893 if ((opt & PICKAXE_BLAME_COPY_HARDER) &&
894 (!porigin || strcmp(target->path, porigin->path)))
895 diff_opts.find_copies_harder = 1;
897 diff_tree_sha1(parent->tree->object.sha1,
898 target->commit->tree->object.sha1,
901 if (!diff_opts.find_copies_harder)
902 diffcore_std(&diff_opts);
906 int made_progress = 0;
908 for (i = 0; i < diff_queued_diff.nr; i++) {
909 struct diff_filepair *p = diff_queued_diff.queue[i];
910 struct origin *norigin;
912 struct blame_entry this[3];
914 if (!DIFF_FILE_VALID(p->one))
915 continue; /* does not exist in parent */
916 if (porigin && !strcmp(p->one->path, porigin->path))
917 /* find_move already dealt with this path */
920 norigin = get_origin(sb, parent, p->one->path);
921 hashcpy(norigin->blob_sha1, p->one->sha1);
922 fill_origin_blob(norigin, &file_p);
926 for (j = 0; j < num_ents; j++) {
927 find_copy_in_blob(sb, blame_list[j].ent,
928 norigin, this, &file_p);
929 copy_split_if_better(sb, blame_list[j].split,
933 origin_decref(norigin);
936 for (j = 0; j < num_ents; j++) {
937 struct blame_entry *split = blame_list[j].split;
938 if (split[1].suspect &&
939 blame_copy_score < ent_score(sb, &split[1])) {
940 split_blame(sb, split, blame_list[j].ent);
949 blame_list = setup_blame_list(sb, target, &num_ents);
955 diff_flush(&diff_opts);
960 /* The blobs of origin and porigin exactly match, so everything
961 * origin is suspected for can be blamed on the parent.
963 static void pass_whole_blame(struct scoreboard *sb,
964 struct origin *origin, struct origin *porigin)
966 struct blame_entry *e;
968 if (!porigin->file.ptr && origin->file.ptr) {
970 porigin->file = origin->file;
971 origin->file.ptr = NULL;
973 for (e = sb->ent; e; e = e->next) {
974 if (cmp_suspect(e->suspect, origin))
976 origin_incref(porigin);
977 origin_decref(e->suspect);
978 e->suspect = porigin;
984 static void pass_blame(struct scoreboard *sb, struct origin *origin, int opt)
987 struct commit *commit = origin->commit;
988 struct commit_list *parent;
989 struct origin *parent_origin[MAXPARENT], *porigin;
991 memset(parent_origin, 0, sizeof(parent_origin));
993 /* The first pass looks for unrenamed path to optimize for
994 * common cases, then we look for renames in the second pass.
996 for (pass = 0; pass < 2; pass++) {
997 struct origin *(*find)(struct scoreboard *,
998 struct commit *, struct origin *);
999 find = pass ? find_rename : find_origin;
1001 for (i = 0, parent = commit->parents;
1002 i < MAXPARENT && parent;
1003 parent = parent->next, i++) {
1004 struct commit *p = parent->item;
1007 if (parent_origin[i])
1009 if (parse_commit(p))
1011 porigin = find(sb, p, origin);
1014 if (!hashcmp(porigin->blob_sha1, origin->blob_sha1)) {
1015 pass_whole_blame(sb, origin, porigin);
1016 origin_decref(porigin);
1019 for (j = same = 0; j < i; j++)
1020 if (parent_origin[j] &&
1021 !hashcmp(parent_origin[j]->blob_sha1,
1022 porigin->blob_sha1)) {
1027 parent_origin[i] = porigin;
1029 origin_decref(porigin);
1034 for (i = 0, parent = commit->parents;
1035 i < MAXPARENT && parent;
1036 parent = parent->next, i++) {
1037 struct origin *porigin = parent_origin[i];
1040 if (pass_blame_to_parent(sb, origin, porigin))
1045 * Optionally run "miff" to find moves in parents' files here.
1047 if (opt & PICKAXE_BLAME_MOVE)
1048 for (i = 0, parent = commit->parents;
1049 i < MAXPARENT && parent;
1050 parent = parent->next, i++) {
1051 struct origin *porigin = parent_origin[i];
1054 if (find_move_in_parent(sb, origin, porigin))
1059 * Optionally run "ciff" to find copies from parents' files here.
1061 if (opt & PICKAXE_BLAME_COPY)
1062 for (i = 0, parent = commit->parents;
1063 i < MAXPARENT && parent;
1064 parent = parent->next, i++) {
1065 struct origin *porigin = parent_origin[i];
1066 if (find_copy_in_parent(sb, origin, parent->item,
1072 for (i = 0; i < MAXPARENT; i++)
1073 origin_decref(parent_origin[i]);
1076 static void assign_blame(struct scoreboard *sb, struct rev_info *revs, int opt)
1079 struct blame_entry *ent;
1080 struct commit *commit;
1081 struct origin *suspect = NULL;
1083 /* find one suspect to break down */
1084 for (ent = sb->ent; !suspect && ent; ent = ent->next)
1086 suspect = ent->suspect;
1088 return; /* all done */
1090 origin_incref(suspect);
1091 commit = suspect->commit;
1092 if (!commit->object.parsed)
1093 parse_commit(commit);
1094 if (!(commit->object.flags & UNINTERESTING) &&
1095 !(revs->max_age != -1 && commit->date < revs->max_age))
1096 pass_blame(sb, suspect, opt);
1098 commit->object.flags |= UNINTERESTING;
1099 if (commit->object.parsed)
1100 mark_parents_uninteresting(commit);
1102 /* treat root commit as boundary */
1103 if (!commit->parents && !show_root)
1104 commit->object.flags |= UNINTERESTING;
1106 /* Take responsibility for the remaining entries */
1107 for (ent = sb->ent; ent; ent = ent->next)
1108 if (!cmp_suspect(ent->suspect, suspect))
1110 origin_decref(suspect);
1112 if (DEBUG) /* sanity */
1113 sanity_check_refcnt(sb);
1117 static const char *format_time(unsigned long time, const char *tz_str,
1120 static char time_buf[128];
1125 if (show_raw_time) {
1126 sprintf(time_buf, "%lu %s", time, tz_str);
1131 minutes = tz < 0 ? -tz : tz;
1132 minutes = (minutes / 100)*60 + (minutes % 100);
1133 minutes = tz < 0 ? -minutes : minutes;
1134 t = time + minutes * 60;
1137 strftime(time_buf, sizeof(time_buf), "%Y-%m-%d %H:%M:%S ", tm);
1138 strcat(time_buf, tz_str);
1146 unsigned long author_time;
1149 /* filled only when asked for details */
1151 char *committer_mail;
1152 unsigned long committer_time;
1158 static void get_ac_line(const char *inbuf, const char *what,
1159 int bufsz, char *person, char **mail,
1160 unsigned long *time, char **tz)
1165 tmp = strstr(inbuf, what);
1168 tmp += strlen(what);
1169 endp = strchr(tmp, '\n');
1177 person = *mail = *tz = "(unknown)";
1181 memcpy(person, tmp, len);
1193 *time = strtoul(tmp, NULL, 10);
1202 static void get_commit_info(struct commit *commit,
1203 struct commit_info *ret,
1208 static char author_buf[1024];
1209 static char committer_buf[1024];
1210 static char summary_buf[1024];
1212 /* We've operated without save_commit_buffer, so
1213 * we now need to populate them for output.
1215 if (!commit->buffer) {
1219 read_sha1_file(commit->object.sha1, type, &size);
1221 ret->author = author_buf;
1222 get_ac_line(commit->buffer, "\nauthor ",
1223 sizeof(author_buf), author_buf, &ret->author_mail,
1224 &ret->author_time, &ret->author_tz);
1229 ret->committer = committer_buf;
1230 get_ac_line(commit->buffer, "\ncommitter ",
1231 sizeof(committer_buf), committer_buf, &ret->committer_mail,
1232 &ret->committer_time, &ret->committer_tz);
1234 ret->summary = summary_buf;
1235 tmp = strstr(commit->buffer, "\n\n");
1238 sprintf(summary_buf, "(%s)", sha1_to_hex(commit->object.sha1));
1242 endp = strchr(tmp, '\n');
1246 if (len >= sizeof(summary_buf))
1248 memcpy(summary_buf, tmp, len);
1249 summary_buf[len] = 0;
1252 #define OUTPUT_ANNOTATE_COMPAT 001
1253 #define OUTPUT_LONG_OBJECT_NAME 002
1254 #define OUTPUT_RAW_TIMESTAMP 004
1255 #define OUTPUT_PORCELAIN 010
1256 #define OUTPUT_SHOW_NAME 020
1257 #define OUTPUT_SHOW_NUMBER 040
1258 #define OUTPUT_SHOW_SCORE 0100
1260 static void emit_porcelain(struct scoreboard *sb, struct blame_entry *ent)
1264 struct origin *suspect = ent->suspect;
1267 strcpy(hex, sha1_to_hex(suspect->commit->object.sha1));
1268 printf("%s%c%d %d %d\n",
1270 ent->guilty ? ' ' : '*', // purely for debugging
1274 if (!(suspect->commit->object.flags & METAINFO_SHOWN)) {
1275 struct commit_info ci;
1276 suspect->commit->object.flags |= METAINFO_SHOWN;
1277 get_commit_info(suspect->commit, &ci, 1);
1278 printf("author %s\n", ci.author);
1279 printf("author-mail %s\n", ci.author_mail);
1280 printf("author-time %lu\n", ci.author_time);
1281 printf("author-tz %s\n", ci.author_tz);
1282 printf("committer %s\n", ci.committer);
1283 printf("committer-mail %s\n", ci.committer_mail);
1284 printf("committer-time %lu\n", ci.committer_time);
1285 printf("committer-tz %s\n", ci.committer_tz);
1286 printf("filename %s\n", suspect->path);
1287 printf("summary %s\n", ci.summary);
1288 if (suspect->commit->object.flags & UNINTERESTING)
1289 printf("boundary\n");
1291 else if (suspect->commit->object.flags & MORE_THAN_ONE_PATH)
1292 printf("filename %s\n", suspect->path);
1294 cp = nth_line(sb, ent->lno);
1295 for (cnt = 0; cnt < ent->num_lines; cnt++) {
1298 printf("%s %d %d\n", hex,
1299 ent->s_lno + 1 + cnt,
1300 ent->lno + 1 + cnt);
1305 } while (ch != '\n' &&
1306 cp < sb->final_buf + sb->final_buf_size);
1310 static void emit_other(struct scoreboard *sb, struct blame_entry *ent, int opt)
1314 struct origin *suspect = ent->suspect;
1315 struct commit_info ci;
1317 int show_raw_time = !!(opt & OUTPUT_RAW_TIMESTAMP);
1319 get_commit_info(suspect->commit, &ci, 1);
1320 strcpy(hex, sha1_to_hex(suspect->commit->object.sha1));
1322 cp = nth_line(sb, ent->lno);
1323 for (cnt = 0; cnt < ent->num_lines; cnt++) {
1325 int length = (opt & OUTPUT_LONG_OBJECT_NAME) ? 40 : 8;
1327 if (suspect->commit->object.flags & UNINTERESTING) {
1328 if (!blank_boundary) {
1333 memset(hex, ' ', length);
1336 printf("%.*s", length, hex);
1337 if (opt & OUTPUT_ANNOTATE_COMPAT)
1338 printf("\t(%10s\t%10s\t%d)", ci.author,
1339 format_time(ci.author_time, ci.author_tz,
1341 ent->lno + 1 + cnt);
1343 if (opt & OUTPUT_SHOW_SCORE)
1345 max_score_digits, ent->score,
1346 ent->suspect->refcnt);
1347 if (opt & OUTPUT_SHOW_NAME)
1348 printf(" %-*.*s", longest_file, longest_file,
1350 if (opt & OUTPUT_SHOW_NUMBER)
1351 printf(" %*d", max_orig_digits,
1352 ent->s_lno + 1 + cnt);
1353 printf(" (%-*.*s %10s %*d) ",
1354 longest_author, longest_author, ci.author,
1355 format_time(ci.author_time, ci.author_tz,
1357 max_digits, ent->lno + 1 + cnt);
1362 } while (ch != '\n' &&
1363 cp < sb->final_buf + sb->final_buf_size);
1367 static void output(struct scoreboard *sb, int option)
1369 struct blame_entry *ent;
1371 if (option & OUTPUT_PORCELAIN) {
1372 for (ent = sb->ent; ent; ent = ent->next) {
1373 struct blame_entry *oth;
1374 struct origin *suspect = ent->suspect;
1375 struct commit *commit = suspect->commit;
1376 if (commit->object.flags & MORE_THAN_ONE_PATH)
1378 for (oth = ent->next; oth; oth = oth->next) {
1379 if ((oth->suspect->commit != commit) ||
1380 !strcmp(oth->suspect->path, suspect->path))
1382 commit->object.flags |= MORE_THAN_ONE_PATH;
1388 for (ent = sb->ent; ent; ent = ent->next) {
1389 if (option & OUTPUT_PORCELAIN)
1390 emit_porcelain(sb, ent);
1392 emit_other(sb, ent, option);
1397 static int prepare_lines(struct scoreboard *sb)
1399 const char *buf = sb->final_buf;
1400 unsigned long len = sb->final_buf_size;
1401 int num = 0, incomplete = 0, bol = 1;
1403 if (len && buf[len-1] != '\n')
1404 incomplete++; /* incomplete line at the end */
1407 sb->lineno = xrealloc(sb->lineno,
1408 sizeof(int* ) * (num + 1));
1409 sb->lineno[num] = buf - sb->final_buf;
1412 if (*buf++ == '\n') {
1417 sb->lineno = xrealloc(sb->lineno,
1418 sizeof(int* ) * (num + incomplete + 1));
1419 sb->lineno[num + incomplete] = buf - sb->final_buf;
1420 sb->num_lines = num + incomplete;
1421 return sb->num_lines;
1424 static int read_ancestry(const char *graft_file)
1426 FILE *fp = fopen(graft_file, "r");
1430 while (fgets(buf, sizeof(buf), fp)) {
1431 /* The format is just "Commit Parent1 Parent2 ...\n" */
1432 int len = strlen(buf);
1433 struct commit_graft *graft = read_graft_line(buf, len);
1435 register_commit_graft(graft, 0);
1441 static int lineno_width(int lines)
1445 for (width = 1, i = 10; i <= lines + 1; width++)
1450 static void find_alignment(struct scoreboard *sb, int *option)
1452 int longest_src_lines = 0;
1453 int longest_dst_lines = 0;
1454 unsigned largest_score = 0;
1455 struct blame_entry *e;
1457 for (e = sb->ent; e; e = e->next) {
1458 struct origin *suspect = e->suspect;
1459 struct commit_info ci;
1462 if (strcmp(suspect->path, sb->path))
1463 *option |= OUTPUT_SHOW_NAME;
1464 num = strlen(suspect->path);
1465 if (longest_file < num)
1467 if (!(suspect->commit->object.flags & METAINFO_SHOWN)) {
1468 suspect->commit->object.flags |= METAINFO_SHOWN;
1469 get_commit_info(suspect->commit, &ci, 1);
1470 num = strlen(ci.author);
1471 if (longest_author < num)
1472 longest_author = num;
1474 num = e->s_lno + e->num_lines;
1475 if (longest_src_lines < num)
1476 longest_src_lines = num;
1477 num = e->lno + e->num_lines;
1478 if (longest_dst_lines < num)
1479 longest_dst_lines = num;
1480 if (largest_score < ent_score(sb, e))
1481 largest_score = ent_score(sb, e);
1483 max_orig_digits = lineno_width(longest_src_lines);
1484 max_digits = lineno_width(longest_dst_lines);
1485 max_score_digits = lineno_width(largest_score);
1488 static void sanity_check_refcnt(struct scoreboard *sb)
1491 struct blame_entry *ent;
1493 for (ent = sb->ent; ent; ent = ent->next) {
1494 /* Nobody should have zero or negative refcnt */
1495 if (ent->suspect->refcnt <= 0) {
1496 fprintf(stderr, "%s in %s has negative refcnt %d\n",
1498 sha1_to_hex(ent->suspect->commit->object.sha1),
1499 ent->suspect->refcnt);
1503 for (ent = sb->ent; ent; ent = ent->next) {
1504 /* Mark the ones that haven't been checked */
1505 if (0 < ent->suspect->refcnt)
1506 ent->suspect->refcnt = -ent->suspect->refcnt;
1508 for (ent = sb->ent; ent; ent = ent->next) {
1509 /* then pick each and see if they have the the correct
1513 struct blame_entry *e;
1514 struct origin *suspect = ent->suspect;
1516 if (0 < suspect->refcnt)
1518 suspect->refcnt = -suspect->refcnt; /* Unmark */
1519 for (found = 0, e = sb->ent; e; e = e->next) {
1520 if (e->suspect != suspect)
1524 if (suspect->refcnt != found) {
1525 fprintf(stderr, "%s in %s has refcnt %d, not %d\n",
1527 sha1_to_hex(ent->suspect->commit->object.sha1),
1528 ent->suspect->refcnt, found);
1534 find_alignment(sb, &opt);
1536 die("Baa %d!", baa);
1540 static int has_path_in_work_tree(const char *path)
1543 return !lstat(path, &st);
1546 static unsigned parse_score(const char *arg)
1549 unsigned long score = strtoul(arg, &end, 10);
1555 static const char *add_prefix(const char *prefix, const char *path)
1557 if (!prefix || !prefix[0])
1559 return prefix_path(prefix, strlen(prefix), path);
1562 static const char *parse_loc(const char *spec,
1563 struct scoreboard *sb, long lno,
1564 long begin, long *ret)
1571 regmatch_t match[1];
1573 /* Allow "-L <something>,+20" to mean starting at <something>
1574 * for 20 lines, or "-L <something>,-5" for 5 lines ending at
1577 if (1 < begin && (spec[0] == '+' || spec[0] == '-')) {
1578 num = strtol(spec + 1, &term, 10);
1579 if (term != spec + 1) {
1583 *ret = begin + num - 2;
1592 num = strtol(spec, &term, 10);
1600 /* it could be a regexp of form /.../ */
1601 for (term = (char*) spec + 1; *term && *term != '/'; term++) {
1608 /* try [spec+1 .. term-1] as regexp */
1610 begin--; /* input is in human terms */
1611 line = nth_line(sb, begin);
1613 if (!(reg_error = regcomp(®exp, spec + 1, REG_NEWLINE)) &&
1614 !(reg_error = regexec(®exp, line, 1, match, 0))) {
1615 const char *cp = line + match[0].rm_so;
1618 while (begin++ < lno) {
1619 nline = nth_line(sb, begin);
1620 if (line <= cp && cp < nline)
1631 regerror(reg_error, ®exp, errbuf, 1024);
1632 die("-L parameter '%s': %s", spec + 1, errbuf);
1636 static void prepare_blame_range(struct scoreboard *sb,
1637 const char *bottomtop,
1639 long *bottom, long *top)
1643 term = parse_loc(bottomtop, sb, lno, 1, bottom);
1645 term = parse_loc(term + 1, sb, lno, *bottom + 1, top);
1653 static int git_blame_config(const char *var, const char *value)
1655 if (!strcmp(var, "blame.showroot")) {
1656 show_root = git_config_bool(var, value);
1659 if (!strcmp(var, "blame.blankboundary")) {
1660 blank_boundary = git_config_bool(var, value);
1663 return git_default_config(var, value);
1666 int cmd_blame(int argc, const char **argv, const char *prefix)
1668 struct rev_info revs;
1670 struct scoreboard sb;
1672 struct blame_entry *ent;
1673 int i, seen_dashdash, unk, opt;
1674 long bottom, top, lno;
1675 int output_option = 0;
1676 const char *revs_file = NULL;
1677 const char *final_commit_name = NULL;
1679 const char *bottomtop = NULL;
1681 git_config(git_blame_config);
1682 save_commit_buffer = 0;
1686 for (unk = i = 1; i < argc; i++) {
1687 const char *arg = argv[i];
1690 else if (!strcmp("-b", arg))
1692 else if (!strcmp("--root", arg))
1694 else if (!strcmp("-c", arg))
1695 output_option |= OUTPUT_ANNOTATE_COMPAT;
1696 else if (!strcmp("-t", arg))
1697 output_option |= OUTPUT_RAW_TIMESTAMP;
1698 else if (!strcmp("-l", arg))
1699 output_option |= OUTPUT_LONG_OBJECT_NAME;
1700 else if (!strcmp("-S", arg) && ++i < argc)
1701 revs_file = argv[i];
1702 else if (!strncmp("-M", arg, 2)) {
1703 opt |= PICKAXE_BLAME_MOVE;
1704 blame_move_score = parse_score(arg+2);
1706 else if (!strncmp("-C", arg, 2)) {
1707 if (opt & PICKAXE_BLAME_COPY)
1708 opt |= PICKAXE_BLAME_COPY_HARDER;
1709 opt |= PICKAXE_BLAME_COPY | PICKAXE_BLAME_MOVE;
1710 blame_copy_score = parse_score(arg+2);
1712 else if (!strncmp("-L", arg, 2)) {
1721 die("More than one '-L n,m' option given");
1724 else if (!strcmp("--score-debug", arg))
1725 output_option |= OUTPUT_SHOW_SCORE;
1726 else if (!strcmp("-f", arg) ||
1727 !strcmp("--show-name", arg))
1728 output_option |= OUTPUT_SHOW_NAME;
1729 else if (!strcmp("-n", arg) ||
1730 !strcmp("--show-number", arg))
1731 output_option |= OUTPUT_SHOW_NUMBER;
1732 else if (!strcmp("-p", arg) ||
1733 !strcmp("--porcelain", arg))
1734 output_option |= OUTPUT_PORCELAIN;
1735 else if (!strcmp("--", arg)) {
1744 if (!blame_move_score)
1745 blame_move_score = BLAME_DEFAULT_MOVE_SCORE;
1746 if (!blame_copy_score)
1747 blame_copy_score = BLAME_DEFAULT_COPY_SCORE;
1749 /* We have collected options unknown to us in argv[1..unk]
1750 * which are to be passed to revision machinery if we are
1751 * going to do the "bottom" procesing.
1753 * The remaining are:
1755 * (1) if seen_dashdash, its either
1756 * "-options -- <path>" or
1757 * "-options -- <path> <rev>".
1758 * but the latter is allowed only if there is no
1759 * options that we passed to revision machinery.
1761 * (2) otherwise, we may have "--" somewhere later and
1762 * might be looking at the first one of multiple 'rev'
1763 * parameters (e.g. " master ^next ^maint -- path").
1764 * See if there is a dashdash first, and give the
1765 * arguments before that to revision machinery.
1766 * After that there must be one 'path'.
1768 * (3) otherwise, its one of the three:
1769 * "-options <path> <rev>"
1770 * "-options <rev> <path>"
1772 * but again the first one is allowed only if
1773 * there is no options that we passed to revision
1777 if (seen_dashdash) {
1781 path = add_prefix(prefix, argv[i]);
1782 if (i + 1 == argc - 1) {
1785 argv[unk++] = argv[i + 1];
1787 else if (i + 1 != argc)
1788 /* garbage at end */
1793 for (j = i; !seen_dashdash && j < argc; j++)
1794 if (!strcmp(argv[j], "--"))
1796 if (seen_dashdash) {
1797 if (seen_dashdash + 1 != argc - 1)
1799 path = add_prefix(prefix, argv[seen_dashdash + 1]);
1800 for (j = i; j < seen_dashdash; j++)
1801 argv[unk++] = argv[j];
1805 path = add_prefix(prefix, argv[i]);
1806 if (i + 1 == argc - 1) {
1807 final_commit_name = argv[i + 1];
1809 /* if (unk == 1) we could be getting
1812 if (unk == 1 && !has_path_in_work_tree(path)) {
1813 path = add_prefix(prefix, argv[i + 1]);
1814 final_commit_name = argv[i];
1817 else if (i != argc - 1)
1818 usage(blame_usage); /* garbage at end */
1820 if (!has_path_in_work_tree(path))
1821 die("cannot stat path %s: %s",
1822 path, strerror(errno));
1826 if (final_commit_name)
1827 argv[unk++] = final_commit_name;
1829 /* Now we got rev and path. We do not want the path pruning
1830 * but we may want "bottom" processing.
1832 argv[unk++] = "--"; /* terminate the rev name */
1835 init_revisions(&revs, NULL);
1836 setup_revisions(unk, argv, &revs, "HEAD");
1837 memset(&sb, 0, sizeof(sb));
1839 /* There must be one and only one positive commit in the
1840 * revs->pending array.
1842 for (i = 0; i < revs.pending.nr; i++) {
1843 struct object *obj = revs.pending.objects[i].item;
1844 if (obj->flags & UNINTERESTING)
1846 while (obj->type == OBJ_TAG)
1847 obj = deref_tag(obj, NULL, 0);
1848 if (obj->type != OBJ_COMMIT)
1849 die("Non commit %s?",
1850 revs.pending.objects[i].name);
1852 die("More than one commit to dig from %s and %s?",
1853 revs.pending.objects[i].name,
1855 sb.final = (struct commit *) obj;
1856 final_commit_name = revs.pending.objects[i].name;
1860 /* "--not A B -- path" without anything positive */
1861 unsigned char head_sha1[20];
1863 final_commit_name = "HEAD";
1864 if (get_sha1(final_commit_name, head_sha1))
1865 die("No such ref: HEAD");
1866 sb.final = lookup_commit_reference(head_sha1);
1867 add_pending_object(&revs, &(sb.final->object), "HEAD");
1870 /* If we have bottom, this will mark the ancestors of the
1871 * bottom commits we would reach while traversing as
1874 prepare_revision_walk(&revs);
1876 o = get_origin(&sb, sb.final, path);
1877 if (fill_blob_sha1(o))
1878 die("no such path %s in %s", path, final_commit_name);
1880 sb.final_buf = read_sha1_file(o->blob_sha1, type, &sb.final_buf_size);
1882 lno = prepare_lines(&sb);
1886 prepare_blame_range(&sb, bottomtop, lno, &bottom, &top);
1887 if (bottom && top && top < bottom) {
1889 tmp = top; top = bottom; bottom = tmp;
1897 die("file %s has only %lu lines", path, lno);
1899 ent = xcalloc(1, sizeof(*ent));
1901 ent->num_lines = top - bottom;
1903 ent->s_lno = bottom;
1908 if (revs_file && read_ancestry(revs_file))
1909 die("reading graft file %s failed: %s",
1910 revs_file, strerror(errno));
1912 assign_blame(&sb, &revs, opt);
1916 if (!(output_option & OUTPUT_PORCELAIN))
1917 find_alignment(&sb, &output_option);
1919 output(&sb, output_option);
1920 free((void *)sb.final_buf);
1921 for (ent = sb.ent; ent; ) {
1922 struct blame_entry *e = ent->next;
1928 printf("num read blob: %d\n", num_read_blob);
1929 printf("num get patch: %d\n", num_get_patch);
1930 printf("num commits: %d\n", num_commits);