4 * Copyright (c) 2006, Junio C Hamano
12 #include "tree-walk.h"
17 #include "xdiff-interface.h"
18 #include "cache-tree.h"
19 #include "string-list.h"
21 #include "parse-options.h"
23 static char blame_usage[] = "git blame [options] [rev-opts] [rev] [--] file";
25 static const char *blame_opt_usage[] = {
28 "[rev-opts] are documented in git-rev-list(1)",
32 static int longest_file;
33 static int longest_author;
34 static int max_orig_digits;
35 static int max_digits;
36 static int max_score_digits;
39 static int blank_boundary;
40 static int incremental;
41 static int xdl_opts = XDF_NEED_MINIMAL;
42 static struct string_list mailmap;
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
56 #define PICKAXE_BLAME_COPY_HARDEST 010
59 * blame for a blame_entry with score lower than these thresholds
60 * is not passed to the parent using move/copy logic.
62 static unsigned blame_move_score;
63 static unsigned blame_copy_score;
64 #define BLAME_DEFAULT_MOVE_SCORE 20
65 #define BLAME_DEFAULT_COPY_SCORE 40
67 /* bits #0..7 in revision.h, #8..11 used for merge_bases() in commit.c */
68 #define METAINFO_SHOWN (1u<<12)
69 #define MORE_THAN_ONE_PATH (1u<<13)
72 * One blob in a commit that is being suspected
76 struct origin *previous;
77 struct commit *commit;
79 unsigned char blob_sha1[20];
80 char path[FLEX_ARRAY];
84 * Given an origin, prepare mmfile_t structure to be used by the
87 static void fill_origin_blob(struct origin *o, mmfile_t *file)
90 enum object_type type;
92 file->ptr = read_sha1_file(o->blob_sha1, &type,
93 (unsigned long *)(&(file->size)));
95 die("Cannot read blob %s for path %s",
96 sha1_to_hex(o->blob_sha1),
105 * Origin is refcounted and usually we keep the blob contents to be
108 static inline struct origin *origin_incref(struct origin *o)
115 static void origin_decref(struct origin *o)
117 if (o && --o->refcnt <= 0) {
119 origin_decref(o->previous);
125 static void drop_origin_blob(struct origin *o)
134 * Each group of lines is described by a blame_entry; it can be split
135 * as we pass blame to the parents. They form a linked list in the
136 * scoreboard structure, sorted by the target line number.
139 struct blame_entry *prev;
140 struct blame_entry *next;
142 /* the first line of this group in the final image;
143 * internally all line numbers are 0 based.
147 /* how many lines this group has */
150 /* the commit that introduced this group into the final image */
151 struct origin *suspect;
153 /* true if the suspect is truly guilty; false while we have not
154 * checked if the group came from one of its parents.
158 /* true if the entry has been scanned for copies in the current parent
162 /* the line number of the first line of this group in the
163 * suspect's file; internally all line numbers are 0 based.
167 /* how significant this entry is -- cached to avoid
168 * scanning the lines over and over.
174 * The current state of the blame assignment.
177 /* the final commit (i.e. where we started digging from) */
178 struct commit *final;
179 struct rev_info *revs;
183 * The contents in the final image.
184 * Used by many functions to obtain contents of the nth line,
185 * indexed with scoreboard.lineno[blame_entry.lno].
187 const char *final_buf;
188 unsigned long final_buf_size;
190 /* linked list of blames */
191 struct blame_entry *ent;
193 /* look-up a line in the final buffer */
198 static inline int same_suspect(struct origin *a, struct origin *b)
202 if (a->commit != b->commit)
204 return !strcmp(a->path, b->path);
207 static void sanity_check_refcnt(struct scoreboard *);
210 * If two blame entries that are next to each other came from
211 * contiguous lines in the same origin (i.e. <commit, path> pair),
212 * merge them together.
214 static void coalesce(struct scoreboard *sb)
216 struct blame_entry *ent, *next;
218 for (ent = sb->ent; ent && (next = ent->next); ent = next) {
219 if (same_suspect(ent->suspect, next->suspect) &&
220 ent->guilty == next->guilty &&
221 ent->s_lno + ent->num_lines == next->s_lno) {
222 ent->num_lines += next->num_lines;
223 ent->next = next->next;
225 ent->next->prev = ent;
226 origin_decref(next->suspect);
229 next = ent; /* again */
233 if (DEBUG) /* sanity */
234 sanity_check_refcnt(sb);
238 * Given a commit and a path in it, create a new origin structure.
239 * The callers that add blame to the scoreboard should use
240 * get_origin() to obtain shared, refcounted copy instead of calling
241 * this function directly.
243 static struct origin *make_origin(struct commit *commit, const char *path)
246 o = xcalloc(1, sizeof(*o) + strlen(path) + 1);
249 strcpy(o->path, path);
254 * Locate an existing origin or create a new one.
256 static struct origin *get_origin(struct scoreboard *sb,
257 struct commit *commit,
260 struct blame_entry *e;
262 for (e = sb->ent; e; e = e->next) {
263 if (e->suspect->commit == commit &&
264 !strcmp(e->suspect->path, path))
265 return origin_incref(e->suspect);
267 return make_origin(commit, path);
271 * Fill the blob_sha1 field of an origin if it hasn't, so that later
272 * call to fill_origin_blob() can use it to locate the data. blob_sha1
273 * for an origin is also used to pass the blame for the entire file to
274 * the parent to detect the case where a child's blob is identical to
275 * that of its parent's.
277 static int fill_blob_sha1(struct origin *origin)
281 if (!is_null_sha1(origin->blob_sha1))
283 if (get_tree_entry(origin->commit->object.sha1,
285 origin->blob_sha1, &mode))
287 if (sha1_object_info(origin->blob_sha1, NULL) != OBJ_BLOB)
291 hashclr(origin->blob_sha1);
296 * We have an origin -- check if the same path exists in the
297 * parent and return an origin structure to represent it.
299 static struct origin *find_origin(struct scoreboard *sb,
300 struct commit *parent,
301 struct origin *origin)
303 struct origin *porigin = NULL;
304 struct diff_options diff_opts;
305 const char *paths[2];
309 * Each commit object can cache one origin in that
310 * commit. This is a freestanding copy of origin and
313 struct origin *cached = parent->util;
314 if (!strcmp(cached->path, origin->path)) {
316 * The same path between origin and its parent
317 * without renaming -- the most common case.
319 porigin = get_origin(sb, parent, cached->path);
322 * If the origin was newly created (i.e. get_origin
323 * would call make_origin if none is found in the
324 * scoreboard), it does not know the blob_sha1,
325 * so copy it. Otherwise porigin was in the
326 * scoreboard and already knows blob_sha1.
328 if (porigin->refcnt == 1)
329 hashcpy(porigin->blob_sha1, cached->blob_sha1);
332 /* otherwise it was not very useful; free it */
337 /* See if the origin->path is different between parent
338 * and origin first. Most of the time they are the
339 * same and diff-tree is fairly efficient about this.
341 diff_setup(&diff_opts);
342 DIFF_OPT_SET(&diff_opts, RECURSIVE);
343 diff_opts.detect_rename = 0;
344 diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;
345 paths[0] = origin->path;
348 diff_tree_setup_paths(paths, &diff_opts);
349 if (diff_setup_done(&diff_opts) < 0)
352 if (is_null_sha1(origin->commit->object.sha1))
353 do_diff_cache(parent->tree->object.sha1, &diff_opts);
355 diff_tree_sha1(parent->tree->object.sha1,
356 origin->commit->tree->object.sha1,
358 diffcore_std(&diff_opts);
360 /* It is either one entry that says "modified", or "created",
363 if (!diff_queued_diff.nr) {
364 /* The path is the same as parent */
365 porigin = get_origin(sb, parent, origin->path);
366 hashcpy(porigin->blob_sha1, origin->blob_sha1);
368 else if (diff_queued_diff.nr != 1)
369 die("internal error in blame::find_origin");
371 struct diff_filepair *p = diff_queued_diff.queue[0];
374 die("internal error in blame::find_origin (%c)",
377 porigin = get_origin(sb, parent, origin->path);
378 hashcpy(porigin->blob_sha1, p->one->sha1);
382 /* Did not exist in parent, or type changed */
386 diff_flush(&diff_opts);
387 diff_tree_release_paths(&diff_opts);
390 * Create a freestanding copy that is not part of
391 * the refcounted origin found in the scoreboard, and
392 * cache it in the commit.
394 struct origin *cached;
396 cached = make_origin(porigin->commit, porigin->path);
397 hashcpy(cached->blob_sha1, porigin->blob_sha1);
398 parent->util = cached;
404 * We have an origin -- find the path that corresponds to it in its
405 * parent and return an origin structure to represent it.
407 static struct origin *find_rename(struct scoreboard *sb,
408 struct commit *parent,
409 struct origin *origin)
411 struct origin *porigin = NULL;
412 struct diff_options diff_opts;
414 const char *paths[2];
416 diff_setup(&diff_opts);
417 DIFF_OPT_SET(&diff_opts, RECURSIVE);
418 diff_opts.detect_rename = DIFF_DETECT_RENAME;
419 diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;
420 diff_opts.single_follow = origin->path;
422 diff_tree_setup_paths(paths, &diff_opts);
423 if (diff_setup_done(&diff_opts) < 0)
426 if (is_null_sha1(origin->commit->object.sha1))
427 do_diff_cache(parent->tree->object.sha1, &diff_opts);
429 diff_tree_sha1(parent->tree->object.sha1,
430 origin->commit->tree->object.sha1,
432 diffcore_std(&diff_opts);
434 for (i = 0; i < diff_queued_diff.nr; i++) {
435 struct diff_filepair *p = diff_queued_diff.queue[i];
436 if ((p->status == 'R' || p->status == 'C') &&
437 !strcmp(p->two->path, origin->path)) {
438 porigin = get_origin(sb, parent, p->one->path);
439 hashcpy(porigin->blob_sha1, p->one->sha1);
443 diff_flush(&diff_opts);
444 diff_tree_release_paths(&diff_opts);
449 * Parsing of patch chunks...
452 /* line number in postimage; up to but not including this
453 * line is the same as preimage
457 /* preimage line number after this chunk */
460 /* postimage line number after this chunk */
465 struct chunk *chunks;
469 struct blame_diff_state {
471 unsigned hunk_post_context;
472 unsigned hunk_in_pre_context : 1;
475 static void process_u_diff(void *state_, char *line, unsigned long len)
477 struct blame_diff_state *state = state_;
479 int off1, off2, len1, len2, num;
481 num = state->ret->num;
482 if (len < 4 || line[0] != '@' || line[1] != '@') {
483 if (state->hunk_in_pre_context && line[0] == ' ')
484 state->ret->chunks[num - 1].same++;
486 state->hunk_in_pre_context = 0;
488 state->hunk_post_context++;
490 state->hunk_post_context = 0;
495 if (num && state->hunk_post_context) {
496 chunk = &state->ret->chunks[num - 1];
497 chunk->p_next -= state->hunk_post_context;
498 chunk->t_next -= state->hunk_post_context;
500 state->ret->num = ++num;
501 state->ret->chunks = xrealloc(state->ret->chunks,
502 sizeof(struct chunk) * num);
503 chunk = &state->ret->chunks[num - 1];
504 if (parse_hunk_header(line, len, &off1, &len1, &off2, &len2)) {
509 /* Line numbers in patch output are one based. */
513 chunk->same = len2 ? off2 : (off2 + 1);
515 chunk->p_next = off1 + (len1 ? len1 : 1);
516 chunk->t_next = chunk->same + len2;
517 state->hunk_in_pre_context = 1;
518 state->hunk_post_context = 0;
521 static struct patch *compare_buffer(mmfile_t *file_p, mmfile_t *file_o,
524 struct blame_diff_state state;
529 xpp.flags = xdl_opts;
530 memset(&xecfg, 0, sizeof(xecfg));
531 xecfg.ctxlen = context;
532 memset(&state, 0, sizeof(state));
533 state.ret = xmalloc(sizeof(struct patch));
534 state.ret->chunks = NULL;
537 xdi_diff_outf(file_p, file_o, process_u_diff, &state, &xpp, &xecfg, &ecb);
539 if (state.ret->num) {
541 chunk = &state.ret->chunks[state.ret->num - 1];
542 chunk->p_next -= state.hunk_post_context;
543 chunk->t_next -= state.hunk_post_context;
549 * Run diff between two origins and grab the patch output, so that
550 * we can pass blame for lines origin is currently suspected for
553 static struct patch *get_patch(struct origin *parent, struct origin *origin)
555 mmfile_t file_p, file_o;
558 fill_origin_blob(parent, &file_p);
559 fill_origin_blob(origin, &file_o);
560 if (!file_p.ptr || !file_o.ptr)
562 patch = compare_buffer(&file_p, &file_o, 0);
567 static void free_patch(struct patch *p)
574 * Link in a new blame entry to the scoreboard. Entries that cover the
575 * same line range have been removed from the scoreboard previously.
577 static void add_blame_entry(struct scoreboard *sb, struct blame_entry *e)
579 struct blame_entry *ent, *prev = NULL;
581 origin_incref(e->suspect);
583 for (ent = sb->ent; ent && ent->lno < e->lno; ent = ent->next)
586 /* prev, if not NULL, is the last one that is below e */
589 e->next = prev->next;
601 * src typically is on-stack; we want to copy the information in it to
602 * a malloced blame_entry that is already on the linked list of the
603 * scoreboard. The origin of dst loses a refcnt while the origin of src
606 static void dup_entry(struct blame_entry *dst, struct blame_entry *src)
608 struct blame_entry *p, *n;
612 origin_incref(src->suspect);
613 origin_decref(dst->suspect);
614 memcpy(dst, src, sizeof(*src));
620 static const char *nth_line(struct scoreboard *sb, int lno)
622 return sb->final_buf + sb->lineno[lno];
626 * It is known that lines between tlno to same came from parent, and e
627 * has an overlap with that range. it also is known that parent's
628 * line plno corresponds to e's line tlno.
634 * <------------------>
636 * Split e into potentially three parts; before this chunk, the chunk
637 * to be blamed for the parent, and after that portion.
639 static void split_overlap(struct blame_entry *split,
640 struct blame_entry *e,
641 int tlno, int plno, int same,
642 struct origin *parent)
645 memset(split, 0, sizeof(struct blame_entry [3]));
647 if (e->s_lno < tlno) {
648 /* there is a pre-chunk part not blamed on parent */
649 split[0].suspect = origin_incref(e->suspect);
650 split[0].lno = e->lno;
651 split[0].s_lno = e->s_lno;
652 split[0].num_lines = tlno - e->s_lno;
653 split[1].lno = e->lno + tlno - e->s_lno;
654 split[1].s_lno = plno;
657 split[1].lno = e->lno;
658 split[1].s_lno = plno + (e->s_lno - tlno);
661 if (same < e->s_lno + e->num_lines) {
662 /* there is a post-chunk part not blamed on parent */
663 split[2].suspect = origin_incref(e->suspect);
664 split[2].lno = e->lno + (same - e->s_lno);
665 split[2].s_lno = e->s_lno + (same - e->s_lno);
666 split[2].num_lines = e->s_lno + e->num_lines - same;
667 chunk_end_lno = split[2].lno;
670 chunk_end_lno = e->lno + e->num_lines;
671 split[1].num_lines = chunk_end_lno - split[1].lno;
674 * if it turns out there is nothing to blame the parent for,
675 * forget about the splitting. !split[1].suspect signals this.
677 if (split[1].num_lines < 1)
679 split[1].suspect = origin_incref(parent);
683 * split_overlap() divided an existing blame e into up to three parts
684 * in split. Adjust the linked list of blames in the scoreboard to
687 static void split_blame(struct scoreboard *sb,
688 struct blame_entry *split,
689 struct blame_entry *e)
691 struct blame_entry *new_entry;
693 if (split[0].suspect && split[2].suspect) {
694 /* The first part (reuse storage for the existing entry e) */
695 dup_entry(e, &split[0]);
697 /* The last part -- me */
698 new_entry = xmalloc(sizeof(*new_entry));
699 memcpy(new_entry, &(split[2]), sizeof(struct blame_entry));
700 add_blame_entry(sb, new_entry);
702 /* ... and the middle part -- parent */
703 new_entry = xmalloc(sizeof(*new_entry));
704 memcpy(new_entry, &(split[1]), sizeof(struct blame_entry));
705 add_blame_entry(sb, new_entry);
707 else if (!split[0].suspect && !split[2].suspect)
709 * The parent covers the entire area; reuse storage for
710 * e and replace it with the parent.
712 dup_entry(e, &split[1]);
713 else if (split[0].suspect) {
714 /* me and then parent */
715 dup_entry(e, &split[0]);
717 new_entry = xmalloc(sizeof(*new_entry));
718 memcpy(new_entry, &(split[1]), sizeof(struct blame_entry));
719 add_blame_entry(sb, new_entry);
722 /* parent and then me */
723 dup_entry(e, &split[1]);
725 new_entry = xmalloc(sizeof(*new_entry));
726 memcpy(new_entry, &(split[2]), sizeof(struct blame_entry));
727 add_blame_entry(sb, new_entry);
730 if (DEBUG) { /* sanity */
731 struct blame_entry *ent;
732 int lno = sb->ent->lno, corrupt = 0;
734 for (ent = sb->ent; ent; ent = ent->next) {
739 lno += ent->num_lines;
743 for (ent = sb->ent; ent; ent = ent->next) {
744 printf("L %8d l %8d n %8d\n",
745 lno, ent->lno, ent->num_lines);
746 lno = ent->lno + ent->num_lines;
754 * After splitting the blame, the origins used by the
755 * on-stack blame_entry should lose one refcnt each.
757 static void decref_split(struct blame_entry *split)
761 for (i = 0; i < 3; i++)
762 origin_decref(split[i].suspect);
766 * Helper for blame_chunk(). blame_entry e is known to overlap with
767 * the patch hunk; split it and pass blame to the parent.
769 static void blame_overlap(struct scoreboard *sb, struct blame_entry *e,
770 int tlno, int plno, int same,
771 struct origin *parent)
773 struct blame_entry split[3];
775 split_overlap(split, e, tlno, plno, same, parent);
776 if (split[1].suspect)
777 split_blame(sb, split, e);
782 * Find the line number of the last line the target is suspected for.
784 static int find_last_in_target(struct scoreboard *sb, struct origin *target)
786 struct blame_entry *e;
787 int last_in_target = -1;
789 for (e = sb->ent; e; e = e->next) {
790 if (e->guilty || !same_suspect(e->suspect, target))
792 if (last_in_target < e->s_lno + e->num_lines)
793 last_in_target = e->s_lno + e->num_lines;
795 return last_in_target;
799 * Process one hunk from the patch between the current suspect for
800 * blame_entry e and its parent. Find and split the overlap, and
801 * pass blame to the overlapping part to the parent.
803 static void blame_chunk(struct scoreboard *sb,
804 int tlno, int plno, int same,
805 struct origin *target, struct origin *parent)
807 struct blame_entry *e;
809 for (e = sb->ent; e; e = e->next) {
810 if (e->guilty || !same_suspect(e->suspect, target))
812 if (same <= e->s_lno)
814 if (tlno < e->s_lno + e->num_lines)
815 blame_overlap(sb, e, tlno, plno, same, parent);
820 * We are looking at the origin 'target' and aiming to pass blame
821 * for the lines it is suspected to its parent. Run diff to find
822 * which lines came from parent and pass blame for them.
824 static int pass_blame_to_parent(struct scoreboard *sb,
825 struct origin *target,
826 struct origin *parent)
828 int i, last_in_target, plno, tlno;
831 last_in_target = find_last_in_target(sb, target);
832 if (last_in_target < 0)
833 return 1; /* nothing remains for this target */
835 patch = get_patch(parent, target);
837 for (i = 0; i < patch->num; i++) {
838 struct chunk *chunk = &patch->chunks[i];
840 blame_chunk(sb, tlno, plno, chunk->same, target, parent);
841 plno = chunk->p_next;
842 tlno = chunk->t_next;
844 /* The rest (i.e. anything after tlno) are the same as the parent */
845 blame_chunk(sb, tlno, plno, last_in_target, target, parent);
852 * The lines in blame_entry after splitting blames many times can become
853 * very small and trivial, and at some point it becomes pointless to
854 * blame the parents. E.g. "\t\t}\n\t}\n\n" appears everywhere in any
855 * ordinary C program, and it is not worth to say it was copied from
856 * totally unrelated file in the parent.
858 * Compute how trivial the lines in the blame_entry are.
860 static unsigned ent_score(struct scoreboard *sb, struct blame_entry *e)
869 cp = nth_line(sb, e->lno);
870 ep = nth_line(sb, e->lno + e->num_lines);
872 unsigned ch = *((unsigned char *)cp);
882 * best_so_far[] and this[] are both a split of an existing blame_entry
883 * that passes blame to the parent. Maintain best_so_far the best split
884 * so far, by comparing this and best_so_far and copying this into
885 * bst_so_far as needed.
887 static void copy_split_if_better(struct scoreboard *sb,
888 struct blame_entry *best_so_far,
889 struct blame_entry *this)
893 if (!this[1].suspect)
895 if (best_so_far[1].suspect) {
896 if (ent_score(sb, &this[1]) < ent_score(sb, &best_so_far[1]))
900 for (i = 0; i < 3; i++)
901 origin_incref(this[i].suspect);
902 decref_split(best_so_far);
903 memcpy(best_so_far, this, sizeof(struct blame_entry [3]));
907 * We are looking at a part of the final image represented by
908 * ent (tlno and same are offset by ent->s_lno).
909 * tlno is where we are looking at in the final image.
910 * up to (but not including) same match preimage.
911 * plno is where we are looking at in the preimage.
913 * <-------------- final image ---------------------->
916 * <---------preimage----->
919 * All line numbers are 0-based.
921 static void handle_split(struct scoreboard *sb,
922 struct blame_entry *ent,
923 int tlno, int plno, int same,
924 struct origin *parent,
925 struct blame_entry *split)
927 if (ent->num_lines <= tlno)
930 struct blame_entry this[3];
933 split_overlap(this, ent, tlno, plno, same, parent);
934 copy_split_if_better(sb, split, this);
940 * Find the lines from parent that are the same as ent so that
941 * we can pass blames to it. file_p has the blob contents for
944 static void find_copy_in_blob(struct scoreboard *sb,
945 struct blame_entry *ent,
946 struct origin *parent,
947 struct blame_entry *split,
957 * Prepare mmfile that contains only the lines in ent.
959 cp = nth_line(sb, ent->lno);
960 file_o.ptr = (char*) cp;
961 cnt = ent->num_lines;
963 while (cnt && cp < sb->final_buf + sb->final_buf_size) {
967 file_o.size = cp - file_o.ptr;
969 patch = compare_buffer(file_p, &file_o, 1);
972 * file_o is a part of final image we are annotating.
973 * file_p partially may match that image.
975 memset(split, 0, sizeof(struct blame_entry [3]));
977 for (i = 0; i < patch->num; i++) {
978 struct chunk *chunk = &patch->chunks[i];
980 handle_split(sb, ent, tlno, plno, chunk->same, parent, split);
981 plno = chunk->p_next;
982 tlno = chunk->t_next;
984 /* remainder, if any, all match the preimage */
985 handle_split(sb, ent, tlno, plno, ent->num_lines, parent, split);
990 * See if lines currently target is suspected for can be attributed to
993 static int find_move_in_parent(struct scoreboard *sb,
994 struct origin *target,
995 struct origin *parent)
997 int last_in_target, made_progress;
998 struct blame_entry *e, split[3];
1001 last_in_target = find_last_in_target(sb, target);
1002 if (last_in_target < 0)
1003 return 1; /* nothing remains for this target */
1005 fill_origin_blob(parent, &file_p);
1010 while (made_progress) {
1012 for (e = sb->ent; e; e = e->next) {
1013 if (e->guilty || !same_suspect(e->suspect, target) ||
1014 ent_score(sb, e) < blame_move_score)
1016 find_copy_in_blob(sb, e, parent, split, &file_p);
1017 if (split[1].suspect &&
1018 blame_move_score < ent_score(sb, &split[1])) {
1019 split_blame(sb, split, e);
1022 decref_split(split);
1029 struct blame_entry *ent;
1030 struct blame_entry split[3];
1034 * Count the number of entries the target is suspected for,
1035 * and prepare a list of entry and the best split.
1037 static struct blame_list *setup_blame_list(struct scoreboard *sb,
1038 struct origin *target,
1042 struct blame_entry *e;
1044 struct blame_list *blame_list = NULL;
1046 for (e = sb->ent, num_ents = 0; e; e = e->next)
1047 if (!e->scanned && !e->guilty &&
1048 same_suspect(e->suspect, target) &&
1049 min_score < ent_score(sb, e))
1052 blame_list = xcalloc(num_ents, sizeof(struct blame_list));
1053 for (e = sb->ent, i = 0; e; e = e->next)
1054 if (!e->scanned && !e->guilty &&
1055 same_suspect(e->suspect, target) &&
1056 min_score < ent_score(sb, e))
1057 blame_list[i++].ent = e;
1059 *num_ents_p = num_ents;
1064 * Reset the scanned status on all entries.
1066 static void reset_scanned_flag(struct scoreboard *sb)
1068 struct blame_entry *e;
1069 for (e = sb->ent; e; e = e->next)
1074 * For lines target is suspected for, see if we can find code movement
1075 * across file boundary from the parent commit. porigin is the path
1076 * in the parent we already tried.
1078 static int find_copy_in_parent(struct scoreboard *sb,
1079 struct origin *target,
1080 struct commit *parent,
1081 struct origin *porigin,
1084 struct diff_options diff_opts;
1085 const char *paths[1];
1088 struct blame_list *blame_list;
1091 blame_list = setup_blame_list(sb, target, blame_copy_score, &num_ents);
1093 return 1; /* nothing remains for this target */
1095 diff_setup(&diff_opts);
1096 DIFF_OPT_SET(&diff_opts, RECURSIVE);
1097 diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;
1100 diff_tree_setup_paths(paths, &diff_opts);
1101 if (diff_setup_done(&diff_opts) < 0)
1104 /* Try "find copies harder" on new path if requested;
1105 * we do not want to use diffcore_rename() actually to
1106 * match things up; find_copies_harder is set only to
1107 * force diff_tree_sha1() to feed all filepairs to diff_queue,
1108 * and this code needs to be after diff_setup_done(), which
1109 * usually makes find-copies-harder imply copy detection.
1111 if ((opt & PICKAXE_BLAME_COPY_HARDEST)
1112 || ((opt & PICKAXE_BLAME_COPY_HARDER)
1113 && (!porigin || strcmp(target->path, porigin->path))))
1114 DIFF_OPT_SET(&diff_opts, FIND_COPIES_HARDER);
1116 if (is_null_sha1(target->commit->object.sha1))
1117 do_diff_cache(parent->tree->object.sha1, &diff_opts);
1119 diff_tree_sha1(parent->tree->object.sha1,
1120 target->commit->tree->object.sha1,
1123 if (!DIFF_OPT_TST(&diff_opts, FIND_COPIES_HARDER))
1124 diffcore_std(&diff_opts);
1128 int made_progress = 0;
1130 for (i = 0; i < diff_queued_diff.nr; i++) {
1131 struct diff_filepair *p = diff_queued_diff.queue[i];
1132 struct origin *norigin;
1134 struct blame_entry this[3];
1136 if (!DIFF_FILE_VALID(p->one))
1137 continue; /* does not exist in parent */
1138 if (S_ISGITLINK(p->one->mode))
1139 continue; /* ignore git links */
1140 if (porigin && !strcmp(p->one->path, porigin->path))
1141 /* find_move already dealt with this path */
1144 norigin = get_origin(sb, parent, p->one->path);
1145 hashcpy(norigin->blob_sha1, p->one->sha1);
1146 fill_origin_blob(norigin, &file_p);
1150 for (j = 0; j < num_ents; j++) {
1151 find_copy_in_blob(sb, blame_list[j].ent,
1152 norigin, this, &file_p);
1153 copy_split_if_better(sb, blame_list[j].split,
1157 origin_decref(norigin);
1160 for (j = 0; j < num_ents; j++) {
1161 struct blame_entry *split = blame_list[j].split;
1162 if (split[1].suspect &&
1163 blame_copy_score < ent_score(sb, &split[1])) {
1164 split_blame(sb, split, blame_list[j].ent);
1168 blame_list[j].ent->scanned = 1;
1169 decref_split(split);
1175 blame_list = setup_blame_list(sb, target, blame_copy_score, &num_ents);
1181 reset_scanned_flag(sb);
1182 diff_flush(&diff_opts);
1183 diff_tree_release_paths(&diff_opts);
1188 * The blobs of origin and porigin exactly match, so everything
1189 * origin is suspected for can be blamed on the parent.
1191 static void pass_whole_blame(struct scoreboard *sb,
1192 struct origin *origin, struct origin *porigin)
1194 struct blame_entry *e;
1196 if (!porigin->file.ptr && origin->file.ptr) {
1197 /* Steal its file */
1198 porigin->file = origin->file;
1199 origin->file.ptr = NULL;
1201 for (e = sb->ent; e; e = e->next) {
1202 if (!same_suspect(e->suspect, origin))
1204 origin_incref(porigin);
1205 origin_decref(e->suspect);
1206 e->suspect = porigin;
1211 * We pass blame from the current commit to its parents. We keep saying
1212 * "parent" (and "porigin"), but what we mean is to find scapegoat to
1213 * exonerate ourselves.
1215 static struct commit_list *first_scapegoat(struct rev_info *revs, struct commit *commit)
1218 return commit->parents;
1219 return lookup_decoration(&revs->children, &commit->object);
1222 static int num_scapegoats(struct rev_info *revs, struct commit *commit)
1225 struct commit_list *l = first_scapegoat(revs, commit);
1226 for (cnt = 0; l; l = l->next)
1233 static void pass_blame(struct scoreboard *sb, struct origin *origin, int opt)
1235 struct rev_info *revs = sb->revs;
1236 int i, pass, num_sg;
1237 struct commit *commit = origin->commit;
1238 struct commit_list *sg;
1239 struct origin *sg_buf[MAXSG];
1240 struct origin *porigin, **sg_origin = sg_buf;
1242 num_sg = num_scapegoats(revs, commit);
1245 else if (num_sg < ARRAY_SIZE(sg_buf))
1246 memset(sg_buf, 0, sizeof(sg_buf));
1248 sg_origin = xcalloc(num_sg, sizeof(*sg_origin));
1251 * The first pass looks for unrenamed path to optimize for
1252 * common cases, then we look for renames in the second pass.
1254 for (pass = 0; pass < 2; pass++) {
1255 struct origin *(*find)(struct scoreboard *,
1256 struct commit *, struct origin *);
1257 find = pass ? find_rename : find_origin;
1259 for (i = 0, sg = first_scapegoat(revs, commit);
1261 sg = sg->next, i++) {
1262 struct commit *p = sg->item;
1267 if (parse_commit(p))
1269 porigin = find(sb, p, origin);
1272 if (!hashcmp(porigin->blob_sha1, origin->blob_sha1)) {
1273 pass_whole_blame(sb, origin, porigin);
1274 origin_decref(porigin);
1277 for (j = same = 0; j < i; j++)
1279 !hashcmp(sg_origin[j]->blob_sha1,
1280 porigin->blob_sha1)) {
1285 sg_origin[i] = porigin;
1287 origin_decref(porigin);
1292 for (i = 0, sg = first_scapegoat(revs, commit);
1294 sg = sg->next, i++) {
1295 struct origin *porigin = sg_origin[i];
1298 if (!origin->previous) {
1299 origin_incref(porigin);
1300 origin->previous = porigin;
1302 if (pass_blame_to_parent(sb, origin, porigin))
1307 * Optionally find moves in parents' files.
1309 if (opt & PICKAXE_BLAME_MOVE)
1310 for (i = 0, sg = first_scapegoat(revs, commit);
1312 sg = sg->next, i++) {
1313 struct origin *porigin = sg_origin[i];
1316 if (find_move_in_parent(sb, origin, porigin))
1321 * Optionally find copies from parents' files.
1323 if (opt & PICKAXE_BLAME_COPY)
1324 for (i = 0, sg = first_scapegoat(revs, commit);
1326 sg = sg->next, i++) {
1327 struct origin *porigin = sg_origin[i];
1328 if (find_copy_in_parent(sb, origin, sg->item,
1334 for (i = 0; i < num_sg; i++) {
1336 drop_origin_blob(sg_origin[i]);
1337 origin_decref(sg_origin[i]);
1340 drop_origin_blob(origin);
1341 if (sg_buf != sg_origin)
1346 * Information on commits, used for output.
1351 const char *author_mail;
1352 unsigned long author_time;
1353 const char *author_tz;
1355 /* filled only when asked for details */
1356 const char *committer;
1357 const char *committer_mail;
1358 unsigned long committer_time;
1359 const char *committer_tz;
1361 const char *summary;
1365 * Parse author/committer line in the commit object buffer
1367 static void get_ac_line(const char *inbuf, const char *what,
1368 int bufsz, char *person, const char **mail,
1369 unsigned long *time, const char **tz)
1371 int len, tzlen, maillen;
1372 char *tmp, *endp, *timepos;
1374 tmp = strstr(inbuf, what);
1377 tmp += strlen(what);
1378 endp = strchr(tmp, '\n');
1386 *mail = *tz = "(unknown)";
1390 memcpy(person, tmp, len);
1398 tzlen = (person+len)-(tmp+1);
1403 *time = strtoul(tmp, NULL, 10);
1411 maillen = timepos - tmp;
1417 * mailmap expansion may make the name longer.
1418 * make room by pushing stuff down.
1420 tmp = person + bufsz - (tzlen + 1);
1421 memmove(tmp, *tz, tzlen);
1425 tmp = tmp - (maillen + 1);
1426 memmove(tmp, *mail, maillen);
1431 * Now, convert e-mail using mailmap
1433 map_email(&mailmap, tmp + 1, person, tmp-person-1);
1436 static void get_commit_info(struct commit *commit,
1437 struct commit_info *ret,
1442 static char author_buf[1024];
1443 static char committer_buf[1024];
1444 static char summary_buf[1024];
1447 * We've operated without save_commit_buffer, so
1448 * we now need to populate them for output.
1450 if (!commit->buffer) {
1451 enum object_type type;
1454 read_sha1_file(commit->object.sha1, &type, &size);
1455 if (!commit->buffer)
1456 die("Cannot read commit %s",
1457 sha1_to_hex(commit->object.sha1));
1459 ret->author = author_buf;
1460 get_ac_line(commit->buffer, "\nauthor ",
1461 sizeof(author_buf), author_buf, &ret->author_mail,
1462 &ret->author_time, &ret->author_tz);
1467 ret->committer = committer_buf;
1468 get_ac_line(commit->buffer, "\ncommitter ",
1469 sizeof(committer_buf), committer_buf, &ret->committer_mail,
1470 &ret->committer_time, &ret->committer_tz);
1472 ret->summary = summary_buf;
1473 tmp = strstr(commit->buffer, "\n\n");
1476 sprintf(summary_buf, "(%s)", sha1_to_hex(commit->object.sha1));
1480 endp = strchr(tmp, '\n');
1482 endp = tmp + strlen(tmp);
1484 if (len >= sizeof(summary_buf) || len == 0)
1486 memcpy(summary_buf, tmp, len);
1487 summary_buf[len] = 0;
1491 * To allow LF and other nonportable characters in pathnames,
1492 * they are c-style quoted as needed.
1494 static void write_filename_info(const char *path)
1496 printf("filename ");
1497 write_name_quoted(path, stdout, '\n');
1501 * Porcelain/Incremental format wants to show a lot of details per
1502 * commit. Instead of repeating this every line, emit it only once,
1503 * the first time each commit appears in the output.
1505 static int emit_one_suspect_detail(struct origin *suspect)
1507 struct commit_info ci;
1509 if (suspect->commit->object.flags & METAINFO_SHOWN)
1512 suspect->commit->object.flags |= METAINFO_SHOWN;
1513 get_commit_info(suspect->commit, &ci, 1);
1514 printf("author %s\n", ci.author);
1515 printf("author-mail %s\n", ci.author_mail);
1516 printf("author-time %lu\n", ci.author_time);
1517 printf("author-tz %s\n", ci.author_tz);
1518 printf("committer %s\n", ci.committer);
1519 printf("committer-mail %s\n", ci.committer_mail);
1520 printf("committer-time %lu\n", ci.committer_time);
1521 printf("committer-tz %s\n", ci.committer_tz);
1522 printf("summary %s\n", ci.summary);
1523 if (suspect->commit->object.flags & UNINTERESTING)
1524 printf("boundary\n");
1525 if (suspect->previous) {
1526 struct origin *prev = suspect->previous;
1527 printf("previous %s ", sha1_to_hex(prev->commit->object.sha1));
1528 write_name_quoted(prev->path, stdout, '\n');
1534 * The blame_entry is found to be guilty for the range. Mark it
1535 * as such, and show it in incremental output.
1537 static void found_guilty_entry(struct blame_entry *ent)
1543 struct origin *suspect = ent->suspect;
1545 printf("%s %d %d %d\n",
1546 sha1_to_hex(suspect->commit->object.sha1),
1547 ent->s_lno + 1, ent->lno + 1, ent->num_lines);
1548 emit_one_suspect_detail(suspect);
1549 write_filename_info(suspect->path);
1550 maybe_flush_or_die(stdout, "stdout");
1555 * The main loop -- while the scoreboard has lines whose true origin
1556 * is still unknown, pick one blame_entry, and allow its current
1557 * suspect to pass blames to its parents.
1559 static void assign_blame(struct scoreboard *sb, int opt)
1561 struct rev_info *revs = sb->revs;
1564 struct blame_entry *ent;
1565 struct commit *commit;
1566 struct origin *suspect = NULL;
1568 /* find one suspect to break down */
1569 for (ent = sb->ent; !suspect && ent; ent = ent->next)
1571 suspect = ent->suspect;
1573 return; /* all done */
1576 * We will use this suspect later in the loop,
1577 * so hold onto it in the meantime.
1579 origin_incref(suspect);
1580 commit = suspect->commit;
1581 if (!commit->object.parsed)
1582 parse_commit(commit);
1584 (!(commit->object.flags & UNINTERESTING) &&
1585 !(revs->max_age != -1 && commit->date < revs->max_age)))
1586 pass_blame(sb, suspect, opt);
1588 commit->object.flags |= UNINTERESTING;
1589 if (commit->object.parsed)
1590 mark_parents_uninteresting(commit);
1592 /* treat root commit as boundary */
1593 if (!commit->parents && !show_root)
1594 commit->object.flags |= UNINTERESTING;
1596 /* Take responsibility for the remaining entries */
1597 for (ent = sb->ent; ent; ent = ent->next)
1598 if (same_suspect(ent->suspect, suspect))
1599 found_guilty_entry(ent);
1600 origin_decref(suspect);
1602 if (DEBUG) /* sanity */
1603 sanity_check_refcnt(sb);
1607 static const char *format_time(unsigned long time, const char *tz_str,
1610 static char time_buf[128];
1615 if (show_raw_time) {
1616 sprintf(time_buf, "%lu %s", time, tz_str);
1621 minutes = tz < 0 ? -tz : tz;
1622 minutes = (minutes / 100)*60 + (minutes % 100);
1623 minutes = tz < 0 ? -minutes : minutes;
1624 t = time + minutes * 60;
1627 strftime(time_buf, sizeof(time_buf), "%Y-%m-%d %H:%M:%S ", tm);
1628 strcat(time_buf, tz_str);
1632 #define OUTPUT_ANNOTATE_COMPAT 001
1633 #define OUTPUT_LONG_OBJECT_NAME 002
1634 #define OUTPUT_RAW_TIMESTAMP 004
1635 #define OUTPUT_PORCELAIN 010
1636 #define OUTPUT_SHOW_NAME 020
1637 #define OUTPUT_SHOW_NUMBER 040
1638 #define OUTPUT_SHOW_SCORE 0100
1639 #define OUTPUT_NO_AUTHOR 0200
1641 static void emit_porcelain(struct scoreboard *sb, struct blame_entry *ent)
1645 struct origin *suspect = ent->suspect;
1648 strcpy(hex, sha1_to_hex(suspect->commit->object.sha1));
1649 printf("%s%c%d %d %d\n",
1651 ent->guilty ? ' ' : '*', // purely for debugging
1655 if (emit_one_suspect_detail(suspect) ||
1656 (suspect->commit->object.flags & MORE_THAN_ONE_PATH))
1657 write_filename_info(suspect->path);
1659 cp = nth_line(sb, ent->lno);
1660 for (cnt = 0; cnt < ent->num_lines; cnt++) {
1663 printf("%s %d %d\n", hex,
1664 ent->s_lno + 1 + cnt,
1665 ent->lno + 1 + cnt);
1670 } while (ch != '\n' &&
1671 cp < sb->final_buf + sb->final_buf_size);
1675 static void emit_other(struct scoreboard *sb, struct blame_entry *ent, int opt)
1679 struct origin *suspect = ent->suspect;
1680 struct commit_info ci;
1682 int show_raw_time = !!(opt & OUTPUT_RAW_TIMESTAMP);
1684 get_commit_info(suspect->commit, &ci, 1);
1685 strcpy(hex, sha1_to_hex(suspect->commit->object.sha1));
1687 cp = nth_line(sb, ent->lno);
1688 for (cnt = 0; cnt < ent->num_lines; cnt++) {
1690 int length = (opt & OUTPUT_LONG_OBJECT_NAME) ? 40 : 8;
1692 if (suspect->commit->object.flags & UNINTERESTING) {
1694 memset(hex, ' ', length);
1695 else if (!(opt & OUTPUT_ANNOTATE_COMPAT)) {
1701 printf("%.*s", length, hex);
1702 if (opt & OUTPUT_ANNOTATE_COMPAT)
1703 printf("\t(%10s\t%10s\t%d)", ci.author,
1704 format_time(ci.author_time, ci.author_tz,
1706 ent->lno + 1 + cnt);
1708 if (opt & OUTPUT_SHOW_SCORE)
1710 max_score_digits, ent->score,
1711 ent->suspect->refcnt);
1712 if (opt & OUTPUT_SHOW_NAME)
1713 printf(" %-*.*s", longest_file, longest_file,
1715 if (opt & OUTPUT_SHOW_NUMBER)
1716 printf(" %*d", max_orig_digits,
1717 ent->s_lno + 1 + cnt);
1719 if (!(opt & OUTPUT_NO_AUTHOR))
1720 printf(" (%-*.*s %10s",
1721 longest_author, longest_author,
1723 format_time(ci.author_time,
1727 max_digits, ent->lno + 1 + cnt);
1732 } while (ch != '\n' &&
1733 cp < sb->final_buf + sb->final_buf_size);
1737 static void output(struct scoreboard *sb, int option)
1739 struct blame_entry *ent;
1741 if (option & OUTPUT_PORCELAIN) {
1742 for (ent = sb->ent; ent; ent = ent->next) {
1743 struct blame_entry *oth;
1744 struct origin *suspect = ent->suspect;
1745 struct commit *commit = suspect->commit;
1746 if (commit->object.flags & MORE_THAN_ONE_PATH)
1748 for (oth = ent->next; oth; oth = oth->next) {
1749 if ((oth->suspect->commit != commit) ||
1750 !strcmp(oth->suspect->path, suspect->path))
1752 commit->object.flags |= MORE_THAN_ONE_PATH;
1758 for (ent = sb->ent; ent; ent = ent->next) {
1759 if (option & OUTPUT_PORCELAIN)
1760 emit_porcelain(sb, ent);
1762 emit_other(sb, ent, option);
1768 * To allow quick access to the contents of nth line in the
1769 * final image, prepare an index in the scoreboard.
1771 static int prepare_lines(struct scoreboard *sb)
1773 const char *buf = sb->final_buf;
1774 unsigned long len = sb->final_buf_size;
1775 int num = 0, incomplete = 0, bol = 1;
1777 if (len && buf[len-1] != '\n')
1778 incomplete++; /* incomplete line at the end */
1781 sb->lineno = xrealloc(sb->lineno,
1782 sizeof(int* ) * (num + 1));
1783 sb->lineno[num] = buf - sb->final_buf;
1786 if (*buf++ == '\n') {
1791 sb->lineno = xrealloc(sb->lineno,
1792 sizeof(int* ) * (num + incomplete + 1));
1793 sb->lineno[num + incomplete] = buf - sb->final_buf;
1794 sb->num_lines = num + incomplete;
1795 return sb->num_lines;
1799 * Add phony grafts for use with -S; this is primarily to
1800 * support git's cvsserver that wants to give a linear history
1803 static int read_ancestry(const char *graft_file)
1805 FILE *fp = fopen(graft_file, "r");
1809 while (fgets(buf, sizeof(buf), fp)) {
1810 /* The format is just "Commit Parent1 Parent2 ...\n" */
1811 int len = strlen(buf);
1812 struct commit_graft *graft = read_graft_line(buf, len);
1814 register_commit_graft(graft, 0);
1821 * How many columns do we need to show line numbers in decimal?
1823 static int lineno_width(int lines)
1827 for (width = 1, i = 10; i <= lines + 1; width++)
1833 * How many columns do we need to show line numbers, authors,
1836 static void find_alignment(struct scoreboard *sb, int *option)
1838 int longest_src_lines = 0;
1839 int longest_dst_lines = 0;
1840 unsigned largest_score = 0;
1841 struct blame_entry *e;
1843 for (e = sb->ent; e; e = e->next) {
1844 struct origin *suspect = e->suspect;
1845 struct commit_info ci;
1848 if (strcmp(suspect->path, sb->path))
1849 *option |= OUTPUT_SHOW_NAME;
1850 num = strlen(suspect->path);
1851 if (longest_file < num)
1853 if (!(suspect->commit->object.flags & METAINFO_SHOWN)) {
1854 suspect->commit->object.flags |= METAINFO_SHOWN;
1855 get_commit_info(suspect->commit, &ci, 1);
1856 num = strlen(ci.author);
1857 if (longest_author < num)
1858 longest_author = num;
1860 num = e->s_lno + e->num_lines;
1861 if (longest_src_lines < num)
1862 longest_src_lines = num;
1863 num = e->lno + e->num_lines;
1864 if (longest_dst_lines < num)
1865 longest_dst_lines = num;
1866 if (largest_score < ent_score(sb, e))
1867 largest_score = ent_score(sb, e);
1869 max_orig_digits = lineno_width(longest_src_lines);
1870 max_digits = lineno_width(longest_dst_lines);
1871 max_score_digits = lineno_width(largest_score);
1875 * For debugging -- origin is refcounted, and this asserts that
1876 * we do not underflow.
1878 static void sanity_check_refcnt(struct scoreboard *sb)
1881 struct blame_entry *ent;
1883 for (ent = sb->ent; ent; ent = ent->next) {
1884 /* Nobody should have zero or negative refcnt */
1885 if (ent->suspect->refcnt <= 0) {
1886 fprintf(stderr, "%s in %s has negative refcnt %d\n",
1888 sha1_to_hex(ent->suspect->commit->object.sha1),
1889 ent->suspect->refcnt);
1895 find_alignment(sb, &opt);
1897 die("Baa %d!", baa);
1902 * Used for the command line parsing; check if the path exists
1903 * in the working tree.
1905 static int has_string_in_work_tree(const char *path)
1908 return !lstat(path, &st);
1911 static unsigned parse_score(const char *arg)
1914 unsigned long score = strtoul(arg, &end, 10);
1920 static const char *add_prefix(const char *prefix, const char *path)
1922 return prefix_path(prefix, prefix ? strlen(prefix) : 0, path);
1926 * Parsing of (comma separated) one item in the -L option
1928 static const char *parse_loc(const char *spec,
1929 struct scoreboard *sb, long lno,
1930 long begin, long *ret)
1937 regmatch_t match[1];
1939 /* Allow "-L <something>,+20" to mean starting at <something>
1940 * for 20 lines, or "-L <something>,-5" for 5 lines ending at
1943 if (1 < begin && (spec[0] == '+' || spec[0] == '-')) {
1944 num = strtol(spec + 1, &term, 10);
1945 if (term != spec + 1) {
1949 *ret = begin + num - 2;
1958 num = strtol(spec, &term, 10);
1966 /* it could be a regexp of form /.../ */
1967 for (term = (char*) spec + 1; *term && *term != '/'; term++) {
1974 /* try [spec+1 .. term-1] as regexp */
1976 begin--; /* input is in human terms */
1977 line = nth_line(sb, begin);
1979 if (!(reg_error = regcomp(®exp, spec + 1, REG_NEWLINE)) &&
1980 !(reg_error = regexec(®exp, line, 1, match, 0))) {
1981 const char *cp = line + match[0].rm_so;
1984 while (begin++ < lno) {
1985 nline = nth_line(sb, begin);
1986 if (line <= cp && cp < nline)
1997 regerror(reg_error, ®exp, errbuf, 1024);
1998 die("-L parameter '%s': %s", spec + 1, errbuf);
2003 * Parsing of -L option
2005 static void prepare_blame_range(struct scoreboard *sb,
2006 const char *bottomtop,
2008 long *bottom, long *top)
2012 term = parse_loc(bottomtop, sb, lno, 1, bottom);
2014 term = parse_loc(term + 1, sb, lno, *bottom + 1, top);
2022 static int git_blame_config(const char *var, const char *value, void *cb)
2024 if (!strcmp(var, "blame.showroot")) {
2025 show_root = git_config_bool(var, value);
2028 if (!strcmp(var, "blame.blankboundary")) {
2029 blank_boundary = git_config_bool(var, value);
2032 return git_default_config(var, value, cb);
2036 * Prepare a dummy commit that represents the work tree (or staged) item.
2037 * Note that annotating work tree item never works in the reverse.
2039 static struct commit *fake_working_tree_commit(const char *path, const char *contents_from)
2041 struct commit *commit;
2042 struct origin *origin;
2043 unsigned char head_sha1[20];
2044 struct strbuf buf = STRBUF_INIT;
2048 struct cache_entry *ce;
2051 if (get_sha1("HEAD", head_sha1))
2052 die("No such ref: HEAD");
2055 commit = xcalloc(1, sizeof(*commit));
2056 commit->parents = xcalloc(1, sizeof(*commit->parents));
2057 commit->parents->item = lookup_commit_reference(head_sha1);
2058 commit->object.parsed = 1;
2060 commit->object.type = OBJ_COMMIT;
2062 origin = make_origin(commit, path);
2064 if (!contents_from || strcmp("-", contents_from)) {
2066 const char *read_from;
2067 unsigned long fin_size;
2069 if (contents_from) {
2070 if (stat(contents_from, &st) < 0)
2071 die("Cannot stat %s", contents_from);
2072 read_from = contents_from;
2075 if (lstat(path, &st) < 0)
2076 die("Cannot lstat %s", path);
2079 fin_size = xsize_t(st.st_size);
2080 mode = canon_mode(st.st_mode);
2081 switch (st.st_mode & S_IFMT) {
2083 if (strbuf_read_file(&buf, read_from, st.st_size) != st.st_size)
2084 die("cannot open or read %s", read_from);
2087 if (readlink(read_from, buf.buf, buf.alloc) != fin_size)
2088 die("cannot readlink %s", read_from);
2092 die("unsupported file type %s", read_from);
2096 /* Reading from stdin */
2097 contents_from = "standard input";
2099 if (strbuf_read(&buf, 0, 0) < 0)
2100 die("read error %s from stdin", strerror(errno));
2102 convert_to_git(path, buf.buf, buf.len, &buf, 0);
2103 origin->file.ptr = buf.buf;
2104 origin->file.size = buf.len;
2105 pretend_sha1_file(buf.buf, buf.len, OBJ_BLOB, origin->blob_sha1);
2106 commit->util = origin;
2109 * Read the current index, replace the path entry with
2110 * origin->blob_sha1 without mucking with its mode or type
2111 * bits; we are not going to write this index out -- we just
2112 * want to run "diff-index --cached".
2119 int pos = cache_name_pos(path, len);
2121 mode = active_cache[pos]->ce_mode;
2123 /* Let's not bother reading from HEAD tree */
2124 mode = S_IFREG | 0644;
2126 size = cache_entry_size(len);
2127 ce = xcalloc(1, size);
2128 hashcpy(ce->sha1, origin->blob_sha1);
2129 memcpy(ce->name, path, len);
2130 ce->ce_flags = create_ce_flags(len, 0);
2131 ce->ce_mode = create_ce_mode(mode);
2132 add_cache_entry(ce, ADD_CACHE_OK_TO_ADD|ADD_CACHE_OK_TO_REPLACE);
2135 * We are not going to write this out, so this does not matter
2136 * right now, but someday we might optimize diff-index --cached
2137 * with cache-tree information.
2139 cache_tree_invalidate_path(active_cache_tree, path);
2141 commit->buffer = xmalloc(400);
2142 ident = fmt_ident("Not Committed Yet", "not.committed.yet", NULL, 0);
2143 snprintf(commit->buffer, 400,
2144 "tree 0000000000000000000000000000000000000000\n"
2148 "Version of %s from %s\n",
2149 sha1_to_hex(head_sha1),
2150 ident, ident, path, contents_from ? contents_from : path);
2154 static const char *prepare_final(struct scoreboard *sb)
2157 const char *final_commit_name = NULL;
2158 struct rev_info *revs = sb->revs;
2161 * There must be one and only one positive commit in the
2162 * revs->pending array.
2164 for (i = 0; i < revs->pending.nr; i++) {
2165 struct object *obj = revs->pending.objects[i].item;
2166 if (obj->flags & UNINTERESTING)
2168 while (obj->type == OBJ_TAG)
2169 obj = deref_tag(obj, NULL, 0);
2170 if (obj->type != OBJ_COMMIT)
2171 die("Non commit %s?", revs->pending.objects[i].name);
2173 die("More than one commit to dig from %s and %s?",
2174 revs->pending.objects[i].name,
2176 sb->final = (struct commit *) obj;
2177 final_commit_name = revs->pending.objects[i].name;
2179 return final_commit_name;
2182 static const char *prepare_initial(struct scoreboard *sb)
2185 const char *final_commit_name = NULL;
2186 struct rev_info *revs = sb->revs;
2189 * There must be one and only one negative commit, and it must be
2192 for (i = 0; i < revs->pending.nr; i++) {
2193 struct object *obj = revs->pending.objects[i].item;
2194 if (!(obj->flags & UNINTERESTING))
2196 while (obj->type == OBJ_TAG)
2197 obj = deref_tag(obj, NULL, 0);
2198 if (obj->type != OBJ_COMMIT)
2199 die("Non commit %s?", revs->pending.objects[i].name);
2201 die("More than one commit to dig down to %s and %s?",
2202 revs->pending.objects[i].name,
2204 sb->final = (struct commit *) obj;
2205 final_commit_name = revs->pending.objects[i].name;
2207 if (!final_commit_name)
2208 die("No commit to dig down to?");
2209 return final_commit_name;
2212 static int blame_copy_callback(const struct option *option, const char *arg, int unset)
2214 int *opt = option->value;
2217 * -C enables copy from removed files;
2218 * -C -C enables copy from existing files, but only
2219 * when blaming a new file;
2220 * -C -C -C enables copy from existing files for
2223 if (*opt & PICKAXE_BLAME_COPY_HARDER)
2224 *opt |= PICKAXE_BLAME_COPY_HARDEST;
2225 if (*opt & PICKAXE_BLAME_COPY)
2226 *opt |= PICKAXE_BLAME_COPY_HARDER;
2227 *opt |= PICKAXE_BLAME_COPY | PICKAXE_BLAME_MOVE;
2230 blame_copy_score = parse_score(arg);
2234 static int blame_move_callback(const struct option *option, const char *arg, int unset)
2236 int *opt = option->value;
2238 *opt |= PICKAXE_BLAME_MOVE;
2241 blame_move_score = parse_score(arg);
2245 static int blame_bottomtop_callback(const struct option *option, const char *arg, int unset)
2247 const char **bottomtop = option->value;
2251 die("More than one '-L n,m' option given");
2256 int cmd_blame(int argc, const char **argv, const char *prefix)
2258 struct rev_info revs;
2260 struct scoreboard sb;
2262 struct blame_entry *ent;
2263 long dashdash_pos, bottom, top, lno;
2264 const char *final_commit_name = NULL;
2265 enum object_type type;
2267 static const char *bottomtop = NULL;
2268 static int output_option = 0, opt = 0;
2269 static int show_stats = 0;
2270 static const char *revs_file = NULL;
2271 static const char *contents_from = NULL;
2272 static const struct option options[] = {
2273 OPT_BOOLEAN(0, "incremental", &incremental, "Show blame entries as we find them, incrementally"),
2274 OPT_BOOLEAN('b', NULL, &blank_boundary, "Show blank SHA-1 for boundary commits (Default: off)"),
2275 OPT_BOOLEAN(0, "root", &show_root, "Do not treat root commits as boundaries (Default: off)"),
2276 OPT_BOOLEAN(0, "show-stats", &show_stats, "Show work cost statistics"),
2277 OPT_BIT(0, "score-debug", &output_option, "Show output score for blame entries", OUTPUT_SHOW_SCORE),
2278 OPT_BIT('f', "show-name", &output_option, "Show original filename (Default: auto)", OUTPUT_SHOW_NAME),
2279 OPT_BIT('n', "show-number", &output_option, "Show original linenumber (Default: off)", OUTPUT_SHOW_NUMBER),
2280 OPT_BIT('p', "porcelain", &output_option, "Show in a format designed for machine consumption", OUTPUT_PORCELAIN),
2281 OPT_BIT('c', NULL, &output_option, "Use the same output mode as git-annotate (Default: off)", OUTPUT_ANNOTATE_COMPAT),
2282 OPT_BIT('t', NULL, &output_option, "Show raw timestamp (Default: off)", OUTPUT_RAW_TIMESTAMP),
2283 OPT_BIT('l', NULL, &output_option, "Show long commit SHA1 (Default: off)", OUTPUT_LONG_OBJECT_NAME),
2284 OPT_BIT('s', NULL, &output_option, "Suppress author name and timestamp (Default: off)", OUTPUT_NO_AUTHOR),
2285 OPT_BIT('w', NULL, &xdl_opts, "Ignore whitespace differences", XDF_IGNORE_WHITESPACE),
2286 OPT_STRING('S', NULL, &revs_file, "file", "Use revisions from <file> instead of calling git-rev-list"),
2287 OPT_STRING(0, "contents", &contents_from, "file", "Use <file>'s contents as the final image"),
2288 { OPTION_CALLBACK, 'C', NULL, &opt, "score", "Find line copies within and across files", PARSE_OPT_OPTARG, blame_copy_callback },
2289 { OPTION_CALLBACK, 'M', NULL, &opt, "score", "Find line movements within and across files", PARSE_OPT_OPTARG, blame_move_callback },
2290 OPT_CALLBACK('L', NULL, &bottomtop, "n,m", "Process only line range n,m, counting from 1", blame_bottomtop_callback),
2294 struct parse_opt_ctx_t ctx;
2295 int cmd_is_annotate = !strcmp(argv[0], "annotate");
2297 git_config(git_blame_config, NULL);
2298 init_revisions(&revs, NULL);
2299 save_commit_buffer = 0;
2302 parse_options_start(&ctx, argc, argv, PARSE_OPT_KEEP_DASHDASH |
2303 PARSE_OPT_KEEP_ARGV0);
2305 switch (parse_options_step(&ctx, options, blame_opt_usage)) {
2306 case PARSE_OPT_HELP:
2308 case PARSE_OPT_DONE:
2310 dashdash_pos = ctx.cpidx;
2314 if (!strcmp(ctx.argv[0], "--reverse")) {
2315 ctx.argv[0] = "--children";
2318 parse_revision_opt(&revs, &ctx, options, blame_opt_usage);
2321 argc = parse_options_end(&ctx);
2323 if (cmd_is_annotate)
2324 output_option |= OUTPUT_ANNOTATE_COMPAT;
2326 if (DIFF_OPT_TST(&revs.diffopt, FIND_COPIES_HARDER))
2327 opt |= (PICKAXE_BLAME_COPY | PICKAXE_BLAME_MOVE |
2328 PICKAXE_BLAME_COPY_HARDER);
2330 if (!blame_move_score)
2331 blame_move_score = BLAME_DEFAULT_MOVE_SCORE;
2332 if (!blame_copy_score)
2333 blame_copy_score = BLAME_DEFAULT_COPY_SCORE;
2336 * We have collected options unknown to us in argv[1..unk]
2337 * which are to be passed to revision machinery if we are
2338 * going to do the "bottom" processing.
2340 * The remaining are:
2342 * (1) if dashdash_pos != 0, its either
2343 * "blame [revisions] -- <path>" or
2344 * "blame -- <path> <rev>"
2346 * (2) otherwise, its one of the two:
2347 * "blame [revisions] <path>"
2348 * "blame <path> <rev>"
2350 * Note that we must strip out <path> from the arguments: we do not
2351 * want the path pruning but we may want "bottom" processing.
2354 switch (argc - dashdash_pos - 1) {
2357 usage_with_options(blame_opt_usage, options);
2358 /* reorder for the new way: <rev> -- <path> */
2364 path = add_prefix(prefix, argv[--argc]);
2368 usage_with_options(blame_opt_usage, options);
2372 usage_with_options(blame_opt_usage, options);
2373 path = add_prefix(prefix, argv[argc - 1]);
2374 if (argc == 3 && !has_string_in_work_tree(path)) { /* (2b) */
2375 path = add_prefix(prefix, argv[1]);
2378 argv[argc - 1] = "--";
2381 if (!has_string_in_work_tree(path))
2382 die("cannot stat path %s: %s", path, strerror(errno));
2385 setup_revisions(argc, argv, &revs, NULL);
2386 memset(&sb, 0, sizeof(sb));
2390 final_commit_name = prepare_final(&sb);
2391 else if (contents_from)
2392 die("--contents and --children do not blend well.");
2394 final_commit_name = prepare_initial(&sb);
2398 * "--not A B -- path" without anything positive;
2399 * do not default to HEAD, but use the working tree
2403 sb.final = fake_working_tree_commit(path, contents_from);
2404 add_pending_object(&revs, &(sb.final->object), ":");
2406 else if (contents_from)
2407 die("Cannot use --contents with final commit object name");
2410 * If we have bottom, this will mark the ancestors of the
2411 * bottom commits we would reach while traversing as
2414 if (prepare_revision_walk(&revs))
2415 die("revision walk setup failed");
2417 if (is_null_sha1(sb.final->object.sha1)) {
2420 buf = xmalloc(o->file.size + 1);
2421 memcpy(buf, o->file.ptr, o->file.size + 1);
2423 sb.final_buf_size = o->file.size;
2426 o = get_origin(&sb, sb.final, path);
2427 if (fill_blob_sha1(o))
2428 die("no such path %s in %s", path, final_commit_name);
2430 sb.final_buf = read_sha1_file(o->blob_sha1, &type,
2431 &sb.final_buf_size);
2433 die("Cannot read blob %s for path %s",
2434 sha1_to_hex(o->blob_sha1),
2438 lno = prepare_lines(&sb);
2442 prepare_blame_range(&sb, bottomtop, lno, &bottom, &top);
2443 if (bottom && top && top < bottom) {
2445 tmp = top; top = bottom; bottom = tmp;
2453 die("file %s has only %lu lines", path, lno);
2455 ent = xcalloc(1, sizeof(*ent));
2457 ent->num_lines = top - bottom;
2459 ent->s_lno = bottom;
2464 if (revs_file && read_ancestry(revs_file))
2465 die("reading graft file %s failed: %s",
2466 revs_file, strerror(errno));
2468 read_mailmap(&mailmap, ".mailmap", NULL);
2473 assign_blame(&sb, opt);
2480 if (!(output_option & OUTPUT_PORCELAIN))
2481 find_alignment(&sb, &output_option);
2483 output(&sb, output_option);
2484 free((void *)sb.final_buf);
2485 for (ent = sb.ent; ent; ) {
2486 struct blame_entry *e = ent->next;
2492 printf("num read blob: %d\n", num_read_blob);
2493 printf("num get patch: %d\n", num_get_patch);
2494 printf("num commits: %d\n", num_commits);