4 * Copyright (c) 2006, Junio C Hamano
12 #include "tree-walk.h"
17 #include "xdiff-interface.h"
18 #include "cache-tree.h"
19 #include "path-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 cmd_is_annotate;
42 static int xdl_opts = XDF_NEED_MINIMAL;
43 static struct path_list mailmap;
50 static int num_read_blob;
51 static int num_get_patch;
52 static int num_commits;
54 #define PICKAXE_BLAME_MOVE 01
55 #define PICKAXE_BLAME_COPY 02
56 #define PICKAXE_BLAME_COPY_HARDER 04
57 #define PICKAXE_BLAME_COPY_HARDEST 010
60 * blame for a blame_entry with score lower than these thresholds
61 * is not passed to the parent using move/copy logic.
63 static unsigned blame_move_score;
64 static unsigned blame_copy_score;
65 #define BLAME_DEFAULT_MOVE_SCORE 20
66 #define BLAME_DEFAULT_COPY_SCORE 40
68 /* bits #0..7 in revision.h, #8..11 used for merge_bases() in commit.c */
69 #define METAINFO_SHOWN (1u<<12)
70 #define MORE_THAN_ONE_PATH (1u<<13)
73 * One blob in a commit that is being suspected
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) {
123 static void drop_origin_blob(struct origin *o)
132 * Each group of lines is described by a blame_entry; it can be split
133 * as we pass blame to the parents. They form a linked list in the
134 * scoreboard structure, sorted by the target line number.
137 struct blame_entry *prev;
138 struct blame_entry *next;
140 /* the first line of this group in the final image;
141 * internally all line numbers are 0 based.
145 /* how many lines this group has */
148 /* the commit that introduced this group into the final image */
149 struct origin *suspect;
151 /* true if the suspect is truly guilty; false while we have not
152 * checked if the group came from one of its parents.
156 /* true if the entry has been scanned for copies in the current parent
160 /* the line number of the first line of this group in the
161 * suspect's file; internally all line numbers are 0 based.
165 /* how significant this entry is -- cached to avoid
166 * scanning the lines over and over.
172 * The current state of the blame assignment.
175 /* the final commit (i.e. where we started digging from) */
176 struct commit *final;
177 struct rev_info *revs;
181 * The contents in the final image.
182 * Used by many functions to obtain contents of the nth line,
183 * indexed with scoreboard.lineno[blame_entry.lno].
185 const char *final_buf;
186 unsigned long final_buf_size;
188 /* linked list of blames */
189 struct blame_entry *ent;
191 /* look-up a line in the final buffer */
196 static inline int same_suspect(struct origin *a, struct origin *b)
200 if (a->commit != b->commit)
202 return !strcmp(a->path, b->path);
205 static void sanity_check_refcnt(struct scoreboard *);
208 * If two blame entries that are next to each other came from
209 * contiguous lines in the same origin (i.e. <commit, path> pair),
210 * merge them together.
212 static void coalesce(struct scoreboard *sb)
214 struct blame_entry *ent, *next;
216 for (ent = sb->ent; ent && (next = ent->next); ent = next) {
217 if (same_suspect(ent->suspect, next->suspect) &&
218 ent->guilty == next->guilty &&
219 ent->s_lno + ent->num_lines == next->s_lno) {
220 ent->num_lines += next->num_lines;
221 ent->next = next->next;
223 ent->next->prev = ent;
224 origin_decref(next->suspect);
227 next = ent; /* again */
231 if (DEBUG) /* sanity */
232 sanity_check_refcnt(sb);
236 * Given a commit and a path in it, create a new origin structure.
237 * The callers that add blame to the scoreboard should use
238 * get_origin() to obtain shared, refcounted copy instead of calling
239 * this function directly.
241 static struct origin *make_origin(struct commit *commit, const char *path)
244 o = xcalloc(1, sizeof(*o) + strlen(path) + 1);
247 strcpy(o->path, path);
252 * Locate an existing origin or create a new one.
254 static struct origin *get_origin(struct scoreboard *sb,
255 struct commit *commit,
258 struct blame_entry *e;
260 for (e = sb->ent; e; e = e->next) {
261 if (e->suspect->commit == commit &&
262 !strcmp(e->suspect->path, path))
263 return origin_incref(e->suspect);
265 return make_origin(commit, path);
269 * Fill the blob_sha1 field of an origin if it hasn't, so that later
270 * call to fill_origin_blob() can use it to locate the data. blob_sha1
271 * for an origin is also used to pass the blame for the entire file to
272 * the parent to detect the case where a child's blob is identical to
273 * that of its parent's.
275 static int fill_blob_sha1(struct origin *origin)
279 if (!is_null_sha1(origin->blob_sha1))
281 if (get_tree_entry(origin->commit->object.sha1,
283 origin->blob_sha1, &mode))
285 if (sha1_object_info(origin->blob_sha1, NULL) != OBJ_BLOB)
289 hashclr(origin->blob_sha1);
294 * We have an origin -- check if the same path exists in the
295 * parent and return an origin structure to represent it.
297 static struct origin *find_origin(struct scoreboard *sb,
298 struct commit *parent,
299 struct origin *origin)
301 struct origin *porigin = NULL;
302 struct diff_options diff_opts;
303 const char *paths[2];
307 * Each commit object can cache one origin in that
308 * commit. This is a freestanding copy of origin and
311 struct origin *cached = parent->util;
312 if (!strcmp(cached->path, origin->path)) {
314 * The same path between origin and its parent
315 * without renaming -- the most common case.
317 porigin = get_origin(sb, parent, cached->path);
320 * If the origin was newly created (i.e. get_origin
321 * would call make_origin if none is found in the
322 * scoreboard), it does not know the blob_sha1,
323 * so copy it. Otherwise porigin was in the
324 * scoreboard and already knows blob_sha1.
326 if (porigin->refcnt == 1)
327 hashcpy(porigin->blob_sha1, cached->blob_sha1);
330 /* otherwise it was not very useful; free it */
335 /* See if the origin->path is different between parent
336 * and origin first. Most of the time they are the
337 * same and diff-tree is fairly efficient about this.
339 diff_setup(&diff_opts);
340 DIFF_OPT_SET(&diff_opts, RECURSIVE);
341 diff_opts.detect_rename = 0;
342 diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;
343 paths[0] = origin->path;
346 diff_tree_setup_paths(paths, &diff_opts);
347 if (diff_setup_done(&diff_opts) < 0)
350 if (is_null_sha1(origin->commit->object.sha1))
351 do_diff_cache(parent->tree->object.sha1, &diff_opts);
353 diff_tree_sha1(parent->tree->object.sha1,
354 origin->commit->tree->object.sha1,
356 diffcore_std(&diff_opts);
358 /* It is either one entry that says "modified", or "created",
361 if (!diff_queued_diff.nr) {
362 /* The path is the same as parent */
363 porigin = get_origin(sb, parent, origin->path);
364 hashcpy(porigin->blob_sha1, origin->blob_sha1);
366 else if (diff_queued_diff.nr != 1)
367 die("internal error in blame::find_origin");
369 struct diff_filepair *p = diff_queued_diff.queue[0];
372 die("internal error in blame::find_origin (%c)",
375 porigin = get_origin(sb, parent, origin->path);
376 hashcpy(porigin->blob_sha1, p->one->sha1);
380 /* Did not exist in parent, or type changed */
384 diff_flush(&diff_opts);
385 diff_tree_release_paths(&diff_opts);
388 * Create a freestanding copy that is not part of
389 * the refcounted origin found in the scoreboard, and
390 * cache it in the commit.
392 struct origin *cached;
394 cached = make_origin(porigin->commit, porigin->path);
395 hashcpy(cached->blob_sha1, porigin->blob_sha1);
396 parent->util = cached;
402 * We have an origin -- find the path that corresponds to it in its
403 * parent and return an origin structure to represent it.
405 static struct origin *find_rename(struct scoreboard *sb,
406 struct commit *parent,
407 struct origin *origin)
409 struct origin *porigin = NULL;
410 struct diff_options diff_opts;
412 const char *paths[2];
414 diff_setup(&diff_opts);
415 DIFF_OPT_SET(&diff_opts, RECURSIVE);
416 diff_opts.detect_rename = DIFF_DETECT_RENAME;
417 diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;
418 diff_opts.single_follow = origin->path;
420 diff_tree_setup_paths(paths, &diff_opts);
421 if (diff_setup_done(&diff_opts) < 0)
424 if (is_null_sha1(origin->commit->object.sha1))
425 do_diff_cache(parent->tree->object.sha1, &diff_opts);
427 diff_tree_sha1(parent->tree->object.sha1,
428 origin->commit->tree->object.sha1,
430 diffcore_std(&diff_opts);
432 for (i = 0; i < diff_queued_diff.nr; i++) {
433 struct diff_filepair *p = diff_queued_diff.queue[i];
434 if ((p->status == 'R' || p->status == 'C') &&
435 !strcmp(p->two->path, origin->path)) {
436 porigin = get_origin(sb, parent, p->one->path);
437 hashcpy(porigin->blob_sha1, p->one->sha1);
441 diff_flush(&diff_opts);
442 diff_tree_release_paths(&diff_opts);
447 * Parsing of patch chunks...
450 /* line number in postimage; up to but not including this
451 * line is the same as preimage
455 /* preimage line number after this chunk */
458 /* postimage line number after this chunk */
463 struct chunk *chunks;
467 struct blame_diff_state {
468 struct xdiff_emit_state xm;
470 unsigned hunk_post_context;
471 unsigned hunk_in_pre_context : 1;
474 static void process_u_diff(void *state_, char *line, unsigned long len)
476 struct blame_diff_state *state = state_;
478 int off1, off2, len1, len2, num;
480 num = state->ret->num;
481 if (len < 4 || line[0] != '@' || line[1] != '@') {
482 if (state->hunk_in_pre_context && line[0] == ' ')
483 state->ret->chunks[num - 1].same++;
485 state->hunk_in_pre_context = 0;
487 state->hunk_post_context++;
489 state->hunk_post_context = 0;
494 if (num && state->hunk_post_context) {
495 chunk = &state->ret->chunks[num - 1];
496 chunk->p_next -= state->hunk_post_context;
497 chunk->t_next -= state->hunk_post_context;
499 state->ret->num = ++num;
500 state->ret->chunks = xrealloc(state->ret->chunks,
501 sizeof(struct chunk) * num);
502 chunk = &state->ret->chunks[num - 1];
503 if (parse_hunk_header(line, len, &off1, &len1, &off2, &len2)) {
508 /* Line numbers in patch output are one based. */
512 chunk->same = len2 ? off2 : (off2 + 1);
514 chunk->p_next = off1 + (len1 ? len1 : 1);
515 chunk->t_next = chunk->same + len2;
516 state->hunk_in_pre_context = 1;
517 state->hunk_post_context = 0;
520 static struct patch *compare_buffer(mmfile_t *file_p, mmfile_t *file_o,
523 struct blame_diff_state state;
528 xpp.flags = xdl_opts;
529 memset(&xecfg, 0, sizeof(xecfg));
530 xecfg.ctxlen = context;
531 ecb.outf = xdiff_outf;
533 memset(&state, 0, sizeof(state));
534 state.xm.consume = process_u_diff;
535 state.ret = xmalloc(sizeof(struct patch));
536 state.ret->chunks = NULL;
539 xdi_diff(file_p, file_o, &xpp, &xecfg, &ecb);
541 if (state.ret->num) {
543 chunk = &state.ret->chunks[state.ret->num - 1];
544 chunk->p_next -= state.hunk_post_context;
545 chunk->t_next -= state.hunk_post_context;
551 * Run diff between two origins and grab the patch output, so that
552 * we can pass blame for lines origin is currently suspected for
555 static struct patch *get_patch(struct origin *parent, struct origin *origin)
557 mmfile_t file_p, file_o;
560 fill_origin_blob(parent, &file_p);
561 fill_origin_blob(origin, &file_o);
562 if (!file_p.ptr || !file_o.ptr)
564 patch = compare_buffer(&file_p, &file_o, 0);
569 static void free_patch(struct patch *p)
576 * Link in a new blame entry to the scoreboard. Entries that cover the
577 * same line range have been removed from the scoreboard previously.
579 static void add_blame_entry(struct scoreboard *sb, struct blame_entry *e)
581 struct blame_entry *ent, *prev = NULL;
583 origin_incref(e->suspect);
585 for (ent = sb->ent; ent && ent->lno < e->lno; ent = ent->next)
588 /* prev, if not NULL, is the last one that is below e */
591 e->next = prev->next;
603 * src typically is on-stack; we want to copy the information in it to
604 * a malloced blame_entry that is already on the linked list of the
605 * scoreboard. The origin of dst loses a refcnt while the origin of src
608 static void dup_entry(struct blame_entry *dst, struct blame_entry *src)
610 struct blame_entry *p, *n;
614 origin_incref(src->suspect);
615 origin_decref(dst->suspect);
616 memcpy(dst, src, sizeof(*src));
622 static const char *nth_line(struct scoreboard *sb, int lno)
624 return sb->final_buf + sb->lineno[lno];
628 * It is known that lines between tlno to same came from parent, and e
629 * has an overlap with that range. it also is known that parent's
630 * line plno corresponds to e's line tlno.
636 * <------------------>
638 * Split e into potentially three parts; before this chunk, the chunk
639 * to be blamed for the parent, and after that portion.
641 static void split_overlap(struct blame_entry *split,
642 struct blame_entry *e,
643 int tlno, int plno, int same,
644 struct origin *parent)
647 memset(split, 0, sizeof(struct blame_entry [3]));
649 if (e->s_lno < tlno) {
650 /* there is a pre-chunk part not blamed on parent */
651 split[0].suspect = origin_incref(e->suspect);
652 split[0].lno = e->lno;
653 split[0].s_lno = e->s_lno;
654 split[0].num_lines = tlno - e->s_lno;
655 split[1].lno = e->lno + tlno - e->s_lno;
656 split[1].s_lno = plno;
659 split[1].lno = e->lno;
660 split[1].s_lno = plno + (e->s_lno - tlno);
663 if (same < e->s_lno + e->num_lines) {
664 /* there is a post-chunk part not blamed on parent */
665 split[2].suspect = origin_incref(e->suspect);
666 split[2].lno = e->lno + (same - e->s_lno);
667 split[2].s_lno = e->s_lno + (same - e->s_lno);
668 split[2].num_lines = e->s_lno + e->num_lines - same;
669 chunk_end_lno = split[2].lno;
672 chunk_end_lno = e->lno + e->num_lines;
673 split[1].num_lines = chunk_end_lno - split[1].lno;
676 * if it turns out there is nothing to blame the parent for,
677 * forget about the splitting. !split[1].suspect signals this.
679 if (split[1].num_lines < 1)
681 split[1].suspect = origin_incref(parent);
685 * split_overlap() divided an existing blame e into up to three parts
686 * in split. Adjust the linked list of blames in the scoreboard to
689 static void split_blame(struct scoreboard *sb,
690 struct blame_entry *split,
691 struct blame_entry *e)
693 struct blame_entry *new_entry;
695 if (split[0].suspect && split[2].suspect) {
696 /* The first part (reuse storage for the existing entry e) */
697 dup_entry(e, &split[0]);
699 /* The last part -- me */
700 new_entry = xmalloc(sizeof(*new_entry));
701 memcpy(new_entry, &(split[2]), sizeof(struct blame_entry));
702 add_blame_entry(sb, new_entry);
704 /* ... and the middle part -- parent */
705 new_entry = xmalloc(sizeof(*new_entry));
706 memcpy(new_entry, &(split[1]), sizeof(struct blame_entry));
707 add_blame_entry(sb, new_entry);
709 else if (!split[0].suspect && !split[2].suspect)
711 * The parent covers the entire area; reuse storage for
712 * e and replace it with the parent.
714 dup_entry(e, &split[1]);
715 else if (split[0].suspect) {
716 /* me and then parent */
717 dup_entry(e, &split[0]);
719 new_entry = xmalloc(sizeof(*new_entry));
720 memcpy(new_entry, &(split[1]), sizeof(struct blame_entry));
721 add_blame_entry(sb, new_entry);
724 /* parent and then me */
725 dup_entry(e, &split[1]);
727 new_entry = xmalloc(sizeof(*new_entry));
728 memcpy(new_entry, &(split[2]), sizeof(struct blame_entry));
729 add_blame_entry(sb, new_entry);
732 if (DEBUG) { /* sanity */
733 struct blame_entry *ent;
734 int lno = sb->ent->lno, corrupt = 0;
736 for (ent = sb->ent; ent; ent = ent->next) {
741 lno += ent->num_lines;
745 for (ent = sb->ent; ent; ent = ent->next) {
746 printf("L %8d l %8d n %8d\n",
747 lno, ent->lno, ent->num_lines);
748 lno = ent->lno + ent->num_lines;
756 * After splitting the blame, the origins used by the
757 * on-stack blame_entry should lose one refcnt each.
759 static void decref_split(struct blame_entry *split)
763 for (i = 0; i < 3; i++)
764 origin_decref(split[i].suspect);
768 * Helper for blame_chunk(). blame_entry e is known to overlap with
769 * the patch hunk; split it and pass blame to the parent.
771 static void blame_overlap(struct scoreboard *sb, struct blame_entry *e,
772 int tlno, int plno, int same,
773 struct origin *parent)
775 struct blame_entry split[3];
777 split_overlap(split, e, tlno, plno, same, parent);
778 if (split[1].suspect)
779 split_blame(sb, split, e);
784 * Find the line number of the last line the target is suspected for.
786 static int find_last_in_target(struct scoreboard *sb, struct origin *target)
788 struct blame_entry *e;
789 int last_in_target = -1;
791 for (e = sb->ent; e; e = e->next) {
792 if (e->guilty || !same_suspect(e->suspect, target))
794 if (last_in_target < e->s_lno + e->num_lines)
795 last_in_target = e->s_lno + e->num_lines;
797 return last_in_target;
801 * Process one hunk from the patch between the current suspect for
802 * blame_entry e and its parent. Find and split the overlap, and
803 * pass blame to the overlapping part to the parent.
805 static void blame_chunk(struct scoreboard *sb,
806 int tlno, int plno, int same,
807 struct origin *target, struct origin *parent)
809 struct blame_entry *e;
811 for (e = sb->ent; e; e = e->next) {
812 if (e->guilty || !same_suspect(e->suspect, target))
814 if (same <= e->s_lno)
816 if (tlno < e->s_lno + e->num_lines)
817 blame_overlap(sb, e, tlno, plno, same, parent);
822 * We are looking at the origin 'target' and aiming to pass blame
823 * for the lines it is suspected to its parent. Run diff to find
824 * which lines came from parent and pass blame for them.
826 static int pass_blame_to_parent(struct scoreboard *sb,
827 struct origin *target,
828 struct origin *parent)
830 int i, last_in_target, plno, tlno;
833 last_in_target = find_last_in_target(sb, target);
834 if (last_in_target < 0)
835 return 1; /* nothing remains for this target */
837 patch = get_patch(parent, target);
839 for (i = 0; i < patch->num; i++) {
840 struct chunk *chunk = &patch->chunks[i];
842 blame_chunk(sb, tlno, plno, chunk->same, target, parent);
843 plno = chunk->p_next;
844 tlno = chunk->t_next;
846 /* The rest (i.e. anything after tlno) are the same as the parent */
847 blame_chunk(sb, tlno, plno, last_in_target, target, parent);
854 * The lines in blame_entry after splitting blames many times can become
855 * very small and trivial, and at some point it becomes pointless to
856 * blame the parents. E.g. "\t\t}\n\t}\n\n" appears everywhere in any
857 * ordinary C program, and it is not worth to say it was copied from
858 * totally unrelated file in the parent.
860 * Compute how trivial the lines in the blame_entry are.
862 static unsigned ent_score(struct scoreboard *sb, struct blame_entry *e)
871 cp = nth_line(sb, e->lno);
872 ep = nth_line(sb, e->lno + e->num_lines);
874 unsigned ch = *((unsigned char *)cp);
884 * best_so_far[] and this[] are both a split of an existing blame_entry
885 * that passes blame to the parent. Maintain best_so_far the best split
886 * so far, by comparing this and best_so_far and copying this into
887 * bst_so_far as needed.
889 static void copy_split_if_better(struct scoreboard *sb,
890 struct blame_entry *best_so_far,
891 struct blame_entry *this)
895 if (!this[1].suspect)
897 if (best_so_far[1].suspect) {
898 if (ent_score(sb, &this[1]) < ent_score(sb, &best_so_far[1]))
902 for (i = 0; i < 3; i++)
903 origin_incref(this[i].suspect);
904 decref_split(best_so_far);
905 memcpy(best_so_far, this, sizeof(struct blame_entry [3]));
909 * We are looking at a part of the final image represented by
910 * ent (tlno and same are offset by ent->s_lno).
911 * tlno is where we are looking at in the final image.
912 * up to (but not including) same match preimage.
913 * plno is where we are looking at in the preimage.
915 * <-------------- final image ---------------------->
918 * <---------preimage----->
921 * All line numbers are 0-based.
923 static void handle_split(struct scoreboard *sb,
924 struct blame_entry *ent,
925 int tlno, int plno, int same,
926 struct origin *parent,
927 struct blame_entry *split)
929 if (ent->num_lines <= tlno)
932 struct blame_entry this[3];
935 split_overlap(this, ent, tlno, plno, same, parent);
936 copy_split_if_better(sb, split, this);
942 * Find the lines from parent that are the same as ent so that
943 * we can pass blames to it. file_p has the blob contents for
946 static void find_copy_in_blob(struct scoreboard *sb,
947 struct blame_entry *ent,
948 struct origin *parent,
949 struct blame_entry *split,
959 * Prepare mmfile that contains only the lines in ent.
961 cp = nth_line(sb, ent->lno);
962 file_o.ptr = (char*) cp;
963 cnt = ent->num_lines;
965 while (cnt && cp < sb->final_buf + sb->final_buf_size) {
969 file_o.size = cp - file_o.ptr;
971 patch = compare_buffer(file_p, &file_o, 1);
974 * file_o is a part of final image we are annotating.
975 * file_p partially may match that image.
977 memset(split, 0, sizeof(struct blame_entry [3]));
979 for (i = 0; i < patch->num; i++) {
980 struct chunk *chunk = &patch->chunks[i];
982 handle_split(sb, ent, tlno, plno, chunk->same, parent, split);
983 plno = chunk->p_next;
984 tlno = chunk->t_next;
986 /* remainder, if any, all match the preimage */
987 handle_split(sb, ent, tlno, plno, ent->num_lines, parent, split);
992 * See if lines currently target is suspected for can be attributed to
995 static int find_move_in_parent(struct scoreboard *sb,
996 struct origin *target,
997 struct origin *parent)
999 int last_in_target, made_progress;
1000 struct blame_entry *e, split[3];
1003 last_in_target = find_last_in_target(sb, target);
1004 if (last_in_target < 0)
1005 return 1; /* nothing remains for this target */
1007 fill_origin_blob(parent, &file_p);
1012 while (made_progress) {
1014 for (e = sb->ent; e; e = e->next) {
1015 if (e->guilty || !same_suspect(e->suspect, target))
1017 find_copy_in_blob(sb, e, parent, split, &file_p);
1018 if (split[1].suspect &&
1019 blame_move_score < ent_score(sb, &split[1])) {
1020 split_blame(sb, split, e);
1023 decref_split(split);
1030 struct blame_entry *ent;
1031 struct blame_entry split[3];
1035 * Count the number of entries the target is suspected for,
1036 * and prepare a list of entry and the best split.
1038 static struct blame_list *setup_blame_list(struct scoreboard *sb,
1039 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 && same_suspect(e->suspect, target))
1050 blame_list = xcalloc(num_ents, sizeof(struct blame_list));
1051 for (e = sb->ent, i = 0; e; e = e->next)
1052 if (!e->scanned && !e->guilty && same_suspect(e->suspect, target))
1053 blame_list[i++].ent = e;
1055 *num_ents_p = num_ents;
1060 * Reset the scanned status on all entries.
1062 static void reset_scanned_flag(struct scoreboard *sb)
1064 struct blame_entry *e;
1065 for (e = sb->ent; e; e = e->next)
1070 * For lines target is suspected for, see if we can find code movement
1071 * across file boundary from the parent commit. porigin is the path
1072 * in the parent we already tried.
1074 static int find_copy_in_parent(struct scoreboard *sb,
1075 struct origin *target,
1076 struct commit *parent,
1077 struct origin *porigin,
1080 struct diff_options diff_opts;
1081 const char *paths[1];
1084 struct blame_list *blame_list;
1087 blame_list = setup_blame_list(sb, target, &num_ents);
1089 return 1; /* nothing remains for this target */
1091 diff_setup(&diff_opts);
1092 DIFF_OPT_SET(&diff_opts, RECURSIVE);
1093 diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;
1096 diff_tree_setup_paths(paths, &diff_opts);
1097 if (diff_setup_done(&diff_opts) < 0)
1100 /* Try "find copies harder" on new path if requested;
1101 * we do not want to use diffcore_rename() actually to
1102 * match things up; find_copies_harder is set only to
1103 * force diff_tree_sha1() to feed all filepairs to diff_queue,
1104 * and this code needs to be after diff_setup_done(), which
1105 * usually makes find-copies-harder imply copy detection.
1107 if ((opt & PICKAXE_BLAME_COPY_HARDEST)
1108 || ((opt & PICKAXE_BLAME_COPY_HARDER)
1109 && (!porigin || strcmp(target->path, porigin->path))))
1110 DIFF_OPT_SET(&diff_opts, FIND_COPIES_HARDER);
1112 if (is_null_sha1(target->commit->object.sha1))
1113 do_diff_cache(parent->tree->object.sha1, &diff_opts);
1115 diff_tree_sha1(parent->tree->object.sha1,
1116 target->commit->tree->object.sha1,
1119 if (!DIFF_OPT_TST(&diff_opts, FIND_COPIES_HARDER))
1120 diffcore_std(&diff_opts);
1124 int made_progress = 0;
1126 for (i = 0; i < diff_queued_diff.nr; i++) {
1127 struct diff_filepair *p = diff_queued_diff.queue[i];
1128 struct origin *norigin;
1130 struct blame_entry this[3];
1132 if (!DIFF_FILE_VALID(p->one))
1133 continue; /* does not exist in parent */
1134 if (porigin && !strcmp(p->one->path, porigin->path))
1135 /* find_move already dealt with this path */
1138 norigin = get_origin(sb, parent, p->one->path);
1139 hashcpy(norigin->blob_sha1, p->one->sha1);
1140 fill_origin_blob(norigin, &file_p);
1144 for (j = 0; j < num_ents; j++) {
1145 find_copy_in_blob(sb, blame_list[j].ent,
1146 norigin, this, &file_p);
1147 copy_split_if_better(sb, blame_list[j].split,
1151 origin_decref(norigin);
1154 for (j = 0; j < num_ents; j++) {
1155 struct blame_entry *split = blame_list[j].split;
1156 if (split[1].suspect &&
1157 blame_copy_score < ent_score(sb, &split[1])) {
1158 split_blame(sb, split, blame_list[j].ent);
1162 blame_list[j].ent->scanned = 1;
1163 decref_split(split);
1169 blame_list = setup_blame_list(sb, target, &num_ents);
1175 reset_scanned_flag(sb);
1176 diff_flush(&diff_opts);
1177 diff_tree_release_paths(&diff_opts);
1182 * The blobs of origin and porigin exactly match, so everything
1183 * origin is suspected for can be blamed on the parent.
1185 static void pass_whole_blame(struct scoreboard *sb,
1186 struct origin *origin, struct origin *porigin)
1188 struct blame_entry *e;
1190 if (!porigin->file.ptr && origin->file.ptr) {
1191 /* Steal its file */
1192 porigin->file = origin->file;
1193 origin->file.ptr = NULL;
1195 for (e = sb->ent; e; e = e->next) {
1196 if (!same_suspect(e->suspect, origin))
1198 origin_incref(porigin);
1199 origin_decref(e->suspect);
1200 e->suspect = porigin;
1205 * We pass blame from the current commit to its parents. We keep saying
1206 * "parent" (and "porigin"), but what we mean is to find scapegoat to
1207 * exonerate ourselves.
1209 static struct commit_list *first_scapegoat(struct rev_info *revs, struct commit *commit)
1212 return commit->parents;
1213 return lookup_decoration(&revs->children, &commit->object);
1216 static int num_scapegoats(struct rev_info *revs, struct commit *commit)
1219 struct commit_list *l = first_scapegoat(revs, commit);
1220 for (cnt = 0; l; l = l->next)
1227 static void pass_blame(struct scoreboard *sb, struct origin *origin, int opt)
1229 struct rev_info *revs = sb->revs;
1230 int i, pass, num_sg;
1231 struct commit *commit = origin->commit;
1232 struct commit_list *sg;
1233 struct origin *sg_buf[MAXSG];
1234 struct origin *porigin, **sg_origin = sg_buf;
1236 num_sg = num_scapegoats(revs, commit);
1239 else if (num_sg < ARRAY_SIZE(sg_buf))
1240 memset(sg_buf, 0, sizeof(sg_buf));
1242 sg_origin = xcalloc(num_sg, sizeof(*sg_origin));
1245 * The first pass looks for unrenamed path to optimize for
1246 * common cases, then we look for renames in the second pass.
1248 for (pass = 0; pass < 2; pass++) {
1249 struct origin *(*find)(struct scoreboard *,
1250 struct commit *, struct origin *);
1251 find = pass ? find_rename : find_origin;
1253 for (i = 0, sg = first_scapegoat(revs, commit);
1255 sg = sg->next, i++) {
1256 struct commit *p = sg->item;
1261 if (parse_commit(p))
1263 porigin = find(sb, p, origin);
1266 if (!hashcmp(porigin->blob_sha1, origin->blob_sha1)) {
1267 pass_whole_blame(sb, origin, porigin);
1268 origin_decref(porigin);
1271 for (j = same = 0; j < i; j++)
1273 !hashcmp(sg_origin[j]->blob_sha1,
1274 porigin->blob_sha1)) {
1279 sg_origin[i] = porigin;
1281 origin_decref(porigin);
1286 for (i = 0, sg = first_scapegoat(revs, commit);
1288 sg = sg->next, i++) {
1289 struct origin *porigin = sg_origin[i];
1292 if (pass_blame_to_parent(sb, origin, porigin))
1297 * Optionally find moves in parents' files.
1299 if (opt & PICKAXE_BLAME_MOVE)
1300 for (i = 0, sg = first_scapegoat(revs, commit);
1302 sg = sg->next, i++) {
1303 struct origin *porigin = sg_origin[i];
1306 if (find_move_in_parent(sb, origin, porigin))
1311 * Optionally find copies from parents' files.
1313 if (opt & PICKAXE_BLAME_COPY)
1314 for (i = 0, sg = first_scapegoat(revs, commit);
1316 sg = sg->next, i++) {
1317 struct origin *porigin = sg_origin[i];
1318 if (find_copy_in_parent(sb, origin, sg->item,
1324 for (i = 0; i < num_sg; i++) {
1326 drop_origin_blob(sg_origin[i]);
1327 origin_decref(sg_origin[i]);
1330 drop_origin_blob(origin);
1331 if (sg_buf != sg_origin)
1336 * Information on commits, used for output.
1341 const char *author_mail;
1342 unsigned long author_time;
1343 const char *author_tz;
1345 /* filled only when asked for details */
1346 const char *committer;
1347 const char *committer_mail;
1348 unsigned long committer_time;
1349 const char *committer_tz;
1351 const char *summary;
1355 * Parse author/committer line in the commit object buffer
1357 static void get_ac_line(const char *inbuf, const char *what,
1358 int bufsz, char *person, const char **mail,
1359 unsigned long *time, const char **tz)
1361 int len, tzlen, maillen;
1362 char *tmp, *endp, *timepos;
1364 tmp = strstr(inbuf, what);
1367 tmp += strlen(what);
1368 endp = strchr(tmp, '\n');
1376 *mail = *tz = "(unknown)";
1380 memcpy(person, tmp, len);
1388 tzlen = (person+len)-(tmp+1);
1393 *time = strtoul(tmp, NULL, 10);
1401 maillen = timepos - tmp;
1407 * mailmap expansion may make the name longer.
1408 * make room by pushing stuff down.
1410 tmp = person + bufsz - (tzlen + 1);
1411 memmove(tmp, *tz, tzlen);
1415 tmp = tmp - (maillen + 1);
1416 memmove(tmp, *mail, maillen);
1421 * Now, convert e-mail using mailmap
1423 map_email(&mailmap, tmp + 1, person, tmp-person-1);
1426 static void get_commit_info(struct commit *commit,
1427 struct commit_info *ret,
1432 static char author_buf[1024];
1433 static char committer_buf[1024];
1434 static char summary_buf[1024];
1437 * We've operated without save_commit_buffer, so
1438 * we now need to populate them for output.
1440 if (!commit->buffer) {
1441 enum object_type type;
1444 read_sha1_file(commit->object.sha1, &type, &size);
1445 if (!commit->buffer)
1446 die("Cannot read commit %s",
1447 sha1_to_hex(commit->object.sha1));
1449 ret->author = author_buf;
1450 get_ac_line(commit->buffer, "\nauthor ",
1451 sizeof(author_buf), author_buf, &ret->author_mail,
1452 &ret->author_time, &ret->author_tz);
1457 ret->committer = committer_buf;
1458 get_ac_line(commit->buffer, "\ncommitter ",
1459 sizeof(committer_buf), committer_buf, &ret->committer_mail,
1460 &ret->committer_time, &ret->committer_tz);
1462 ret->summary = summary_buf;
1463 tmp = strstr(commit->buffer, "\n\n");
1466 sprintf(summary_buf, "(%s)", sha1_to_hex(commit->object.sha1));
1470 endp = strchr(tmp, '\n');
1472 endp = tmp + strlen(tmp);
1474 if (len >= sizeof(summary_buf) || len == 0)
1476 memcpy(summary_buf, tmp, len);
1477 summary_buf[len] = 0;
1481 * To allow LF and other nonportable characters in pathnames,
1482 * they are c-style quoted as needed.
1484 static void write_filename_info(const char *path)
1486 printf("filename ");
1487 write_name_quoted(path, stdout, '\n');
1491 * The blame_entry is found to be guilty for the range. Mark it
1492 * as such, and show it in incremental output.
1494 static void found_guilty_entry(struct blame_entry *ent)
1500 struct origin *suspect = ent->suspect;
1502 printf("%s %d %d %d\n",
1503 sha1_to_hex(suspect->commit->object.sha1),
1504 ent->s_lno + 1, ent->lno + 1, ent->num_lines);
1505 if (!(suspect->commit->object.flags & METAINFO_SHOWN)) {
1506 struct commit_info ci;
1507 suspect->commit->object.flags |= METAINFO_SHOWN;
1508 get_commit_info(suspect->commit, &ci, 1);
1509 printf("author %s\n", ci.author);
1510 printf("author-mail %s\n", ci.author_mail);
1511 printf("author-time %lu\n", ci.author_time);
1512 printf("author-tz %s\n", ci.author_tz);
1513 printf("committer %s\n", ci.committer);
1514 printf("committer-mail %s\n", ci.committer_mail);
1515 printf("committer-time %lu\n", ci.committer_time);
1516 printf("committer-tz %s\n", ci.committer_tz);
1517 printf("summary %s\n", ci.summary);
1518 if (suspect->commit->object.flags & UNINTERESTING)
1519 printf("boundary\n");
1521 write_filename_info(suspect->path);
1522 maybe_flush_or_die(stdout, "stdout");
1527 * The main loop -- while the scoreboard has lines whose true origin
1528 * is still unknown, pick one blame_entry, and allow its current
1529 * suspect to pass blames to its parents.
1531 static void assign_blame(struct scoreboard *sb, int opt)
1533 struct rev_info *revs = sb->revs;
1536 struct blame_entry *ent;
1537 struct commit *commit;
1538 struct origin *suspect = NULL;
1540 /* find one suspect to break down */
1541 for (ent = sb->ent; !suspect && ent; ent = ent->next)
1543 suspect = ent->suspect;
1545 return; /* all done */
1548 * We will use this suspect later in the loop,
1549 * so hold onto it in the meantime.
1551 origin_incref(suspect);
1552 commit = suspect->commit;
1553 if (!commit->object.parsed)
1554 parse_commit(commit);
1556 (!(commit->object.flags & UNINTERESTING) &&
1557 !(revs->max_age != -1 && commit->date < revs->max_age)))
1558 pass_blame(sb, suspect, opt);
1560 commit->object.flags |= UNINTERESTING;
1561 if (commit->object.parsed)
1562 mark_parents_uninteresting(commit);
1564 /* treat root commit as boundary */
1565 if (!commit->parents && !show_root)
1566 commit->object.flags |= UNINTERESTING;
1568 /* Take responsibility for the remaining entries */
1569 for (ent = sb->ent; ent; ent = ent->next)
1570 if (same_suspect(ent->suspect, suspect))
1571 found_guilty_entry(ent);
1572 origin_decref(suspect);
1574 if (DEBUG) /* sanity */
1575 sanity_check_refcnt(sb);
1579 static const char *format_time(unsigned long time, const char *tz_str,
1582 static char time_buf[128];
1587 if (show_raw_time) {
1588 sprintf(time_buf, "%lu %s", time, tz_str);
1593 minutes = tz < 0 ? -tz : tz;
1594 minutes = (minutes / 100)*60 + (minutes % 100);
1595 minutes = tz < 0 ? -minutes : minutes;
1596 t = time + minutes * 60;
1599 strftime(time_buf, sizeof(time_buf), "%Y-%m-%d %H:%M:%S ", tm);
1600 strcat(time_buf, tz_str);
1604 #define OUTPUT_ANNOTATE_COMPAT 001
1605 #define OUTPUT_LONG_OBJECT_NAME 002
1606 #define OUTPUT_RAW_TIMESTAMP 004
1607 #define OUTPUT_PORCELAIN 010
1608 #define OUTPUT_SHOW_NAME 020
1609 #define OUTPUT_SHOW_NUMBER 040
1610 #define OUTPUT_SHOW_SCORE 0100
1611 #define OUTPUT_NO_AUTHOR 0200
1613 static void emit_porcelain(struct scoreboard *sb, struct blame_entry *ent)
1617 struct origin *suspect = ent->suspect;
1620 strcpy(hex, sha1_to_hex(suspect->commit->object.sha1));
1621 printf("%s%c%d %d %d\n",
1623 ent->guilty ? ' ' : '*', // purely for debugging
1627 if (!(suspect->commit->object.flags & METAINFO_SHOWN)) {
1628 struct commit_info ci;
1629 suspect->commit->object.flags |= METAINFO_SHOWN;
1630 get_commit_info(suspect->commit, &ci, 1);
1631 printf("author %s\n", ci.author);
1632 printf("author-mail %s\n", ci.author_mail);
1633 printf("author-time %lu\n", ci.author_time);
1634 printf("author-tz %s\n", ci.author_tz);
1635 printf("committer %s\n", ci.committer);
1636 printf("committer-mail %s\n", ci.committer_mail);
1637 printf("committer-time %lu\n", ci.committer_time);
1638 printf("committer-tz %s\n", ci.committer_tz);
1639 write_filename_info(suspect->path);
1640 printf("summary %s\n", ci.summary);
1641 if (suspect->commit->object.flags & UNINTERESTING)
1642 printf("boundary\n");
1644 else if (suspect->commit->object.flags & MORE_THAN_ONE_PATH)
1645 write_filename_info(suspect->path);
1647 cp = nth_line(sb, ent->lno);
1648 for (cnt = 0; cnt < ent->num_lines; cnt++) {
1651 printf("%s %d %d\n", hex,
1652 ent->s_lno + 1 + cnt,
1653 ent->lno + 1 + cnt);
1658 } while (ch != '\n' &&
1659 cp < sb->final_buf + sb->final_buf_size);
1663 static void emit_other(struct scoreboard *sb, struct blame_entry *ent, int opt)
1667 struct origin *suspect = ent->suspect;
1668 struct commit_info ci;
1670 int show_raw_time = !!(opt & OUTPUT_RAW_TIMESTAMP);
1672 get_commit_info(suspect->commit, &ci, 1);
1673 strcpy(hex, sha1_to_hex(suspect->commit->object.sha1));
1675 cp = nth_line(sb, ent->lno);
1676 for (cnt = 0; cnt < ent->num_lines; cnt++) {
1678 int length = (opt & OUTPUT_LONG_OBJECT_NAME) ? 40 : 8;
1680 if (suspect->commit->object.flags & UNINTERESTING) {
1682 memset(hex, ' ', length);
1683 else if (!cmd_is_annotate) {
1689 printf("%.*s", length, hex);
1690 if (opt & OUTPUT_ANNOTATE_COMPAT)
1691 printf("\t(%10s\t%10s\t%d)", ci.author,
1692 format_time(ci.author_time, ci.author_tz,
1694 ent->lno + 1 + cnt);
1696 if (opt & OUTPUT_SHOW_SCORE)
1698 max_score_digits, ent->score,
1699 ent->suspect->refcnt);
1700 if (opt & OUTPUT_SHOW_NAME)
1701 printf(" %-*.*s", longest_file, longest_file,
1703 if (opt & OUTPUT_SHOW_NUMBER)
1704 printf(" %*d", max_orig_digits,
1705 ent->s_lno + 1 + cnt);
1707 if (!(opt & OUTPUT_NO_AUTHOR))
1708 printf(" (%-*.*s %10s",
1709 longest_author, longest_author,
1711 format_time(ci.author_time,
1715 max_digits, ent->lno + 1 + cnt);
1720 } while (ch != '\n' &&
1721 cp < sb->final_buf + sb->final_buf_size);
1725 static void output(struct scoreboard *sb, int option)
1727 struct blame_entry *ent;
1729 if (option & OUTPUT_PORCELAIN) {
1730 for (ent = sb->ent; ent; ent = ent->next) {
1731 struct blame_entry *oth;
1732 struct origin *suspect = ent->suspect;
1733 struct commit *commit = suspect->commit;
1734 if (commit->object.flags & MORE_THAN_ONE_PATH)
1736 for (oth = ent->next; oth; oth = oth->next) {
1737 if ((oth->suspect->commit != commit) ||
1738 !strcmp(oth->suspect->path, suspect->path))
1740 commit->object.flags |= MORE_THAN_ONE_PATH;
1746 for (ent = sb->ent; ent; ent = ent->next) {
1747 if (option & OUTPUT_PORCELAIN)
1748 emit_porcelain(sb, ent);
1750 emit_other(sb, ent, option);
1756 * To allow quick access to the contents of nth line in the
1757 * final image, prepare an index in the scoreboard.
1759 static int prepare_lines(struct scoreboard *sb)
1761 const char *buf = sb->final_buf;
1762 unsigned long len = sb->final_buf_size;
1763 int num = 0, incomplete = 0, bol = 1;
1765 if (len && buf[len-1] != '\n')
1766 incomplete++; /* incomplete line at the end */
1769 sb->lineno = xrealloc(sb->lineno,
1770 sizeof(int* ) * (num + 1));
1771 sb->lineno[num] = buf - sb->final_buf;
1774 if (*buf++ == '\n') {
1779 sb->lineno = xrealloc(sb->lineno,
1780 sizeof(int* ) * (num + incomplete + 1));
1781 sb->lineno[num + incomplete] = buf - sb->final_buf;
1782 sb->num_lines = num + incomplete;
1783 return sb->num_lines;
1787 * Add phony grafts for use with -S; this is primarily to
1788 * support git-cvsserver that wants to give a linear history
1791 static int read_ancestry(const char *graft_file)
1793 FILE *fp = fopen(graft_file, "r");
1797 while (fgets(buf, sizeof(buf), fp)) {
1798 /* The format is just "Commit Parent1 Parent2 ...\n" */
1799 int len = strlen(buf);
1800 struct commit_graft *graft = read_graft_line(buf, len);
1802 register_commit_graft(graft, 0);
1809 * How many columns do we need to show line numbers in decimal?
1811 static int lineno_width(int lines)
1815 for (width = 1, i = 10; i <= lines + 1; width++)
1821 * How many columns do we need to show line numbers, authors,
1824 static void find_alignment(struct scoreboard *sb, int *option)
1826 int longest_src_lines = 0;
1827 int longest_dst_lines = 0;
1828 unsigned largest_score = 0;
1829 struct blame_entry *e;
1831 for (e = sb->ent; e; e = e->next) {
1832 struct origin *suspect = e->suspect;
1833 struct commit_info ci;
1836 if (strcmp(suspect->path, sb->path))
1837 *option |= OUTPUT_SHOW_NAME;
1838 num = strlen(suspect->path);
1839 if (longest_file < num)
1841 if (!(suspect->commit->object.flags & METAINFO_SHOWN)) {
1842 suspect->commit->object.flags |= METAINFO_SHOWN;
1843 get_commit_info(suspect->commit, &ci, 1);
1844 num = strlen(ci.author);
1845 if (longest_author < num)
1846 longest_author = num;
1848 num = e->s_lno + e->num_lines;
1849 if (longest_src_lines < num)
1850 longest_src_lines = num;
1851 num = e->lno + e->num_lines;
1852 if (longest_dst_lines < num)
1853 longest_dst_lines = num;
1854 if (largest_score < ent_score(sb, e))
1855 largest_score = ent_score(sb, e);
1857 max_orig_digits = lineno_width(longest_src_lines);
1858 max_digits = lineno_width(longest_dst_lines);
1859 max_score_digits = lineno_width(largest_score);
1863 * For debugging -- origin is refcounted, and this asserts that
1864 * we do not underflow.
1866 static void sanity_check_refcnt(struct scoreboard *sb)
1869 struct blame_entry *ent;
1871 for (ent = sb->ent; ent; ent = ent->next) {
1872 /* Nobody should have zero or negative refcnt */
1873 if (ent->suspect->refcnt <= 0) {
1874 fprintf(stderr, "%s in %s has negative refcnt %d\n",
1876 sha1_to_hex(ent->suspect->commit->object.sha1),
1877 ent->suspect->refcnt);
1881 for (ent = sb->ent; ent; ent = ent->next) {
1882 /* Mark the ones that haven't been checked */
1883 if (0 < ent->suspect->refcnt)
1884 ent->suspect->refcnt = -ent->suspect->refcnt;
1886 for (ent = sb->ent; ent; ent = ent->next) {
1888 * ... then pick each and see if they have the the
1892 struct blame_entry *e;
1893 struct origin *suspect = ent->suspect;
1895 if (0 < suspect->refcnt)
1897 suspect->refcnt = -suspect->refcnt; /* Unmark */
1898 for (found = 0, e = sb->ent; e; e = e->next) {
1899 if (e->suspect != suspect)
1903 if (suspect->refcnt != found) {
1904 fprintf(stderr, "%s in %s has refcnt %d, not %d\n",
1906 sha1_to_hex(ent->suspect->commit->object.sha1),
1907 ent->suspect->refcnt, found);
1913 find_alignment(sb, &opt);
1915 die("Baa %d!", baa);
1920 * Used for the command line parsing; check if the path exists
1921 * in the working tree.
1923 static int has_path_in_work_tree(const char *path)
1926 return !lstat(path, &st);
1929 static unsigned parse_score(const char *arg)
1932 unsigned long score = strtoul(arg, &end, 10);
1938 static const char *add_prefix(const char *prefix, const char *path)
1940 return prefix_path(prefix, prefix ? strlen(prefix) : 0, path);
1944 * Parsing of (comma separated) one item in the -L option
1946 static const char *parse_loc(const char *spec,
1947 struct scoreboard *sb, long lno,
1948 long begin, long *ret)
1955 regmatch_t match[1];
1957 /* Allow "-L <something>,+20" to mean starting at <something>
1958 * for 20 lines, or "-L <something>,-5" for 5 lines ending at
1961 if (1 < begin && (spec[0] == '+' || spec[0] == '-')) {
1962 num = strtol(spec + 1, &term, 10);
1963 if (term != spec + 1) {
1967 *ret = begin + num - 2;
1976 num = strtol(spec, &term, 10);
1984 /* it could be a regexp of form /.../ */
1985 for (term = (char*) spec + 1; *term && *term != '/'; term++) {
1992 /* try [spec+1 .. term-1] as regexp */
1994 begin--; /* input is in human terms */
1995 line = nth_line(sb, begin);
1997 if (!(reg_error = regcomp(®exp, spec + 1, REG_NEWLINE)) &&
1998 !(reg_error = regexec(®exp, line, 1, match, 0))) {
1999 const char *cp = line + match[0].rm_so;
2002 while (begin++ < lno) {
2003 nline = nth_line(sb, begin);
2004 if (line <= cp && cp < nline)
2015 regerror(reg_error, ®exp, errbuf, 1024);
2016 die("-L parameter '%s': %s", spec + 1, errbuf);
2021 * Parsing of -L option
2023 static void prepare_blame_range(struct scoreboard *sb,
2024 const char *bottomtop,
2026 long *bottom, long *top)
2030 term = parse_loc(bottomtop, sb, lno, 1, bottom);
2032 term = parse_loc(term + 1, sb, lno, *bottom + 1, top);
2040 static int git_blame_config(const char *var, const char *value, void *cb)
2042 if (!strcmp(var, "blame.showroot")) {
2043 show_root = git_config_bool(var, value);
2046 if (!strcmp(var, "blame.blankboundary")) {
2047 blank_boundary = git_config_bool(var, value);
2050 return git_default_config(var, value, cb);
2054 * Prepare a dummy commit that represents the work tree (or staged) item.
2055 * Note that annotating work tree item never works in the reverse.
2057 static struct commit *fake_working_tree_commit(const char *path, const char *contents_from)
2059 struct commit *commit;
2060 struct origin *origin;
2061 unsigned char head_sha1[20];
2066 struct cache_entry *ce;
2069 if (get_sha1("HEAD", head_sha1))
2070 die("No such ref: HEAD");
2073 commit = xcalloc(1, sizeof(*commit));
2074 commit->parents = xcalloc(1, sizeof(*commit->parents));
2075 commit->parents->item = lookup_commit_reference(head_sha1);
2076 commit->object.parsed = 1;
2078 commit->object.type = OBJ_COMMIT;
2080 origin = make_origin(commit, path);
2082 strbuf_init(&buf, 0);
2083 if (!contents_from || strcmp("-", contents_from)) {
2085 const char *read_from;
2086 unsigned long fin_size;
2088 if (contents_from) {
2089 if (stat(contents_from, &st) < 0)
2090 die("Cannot stat %s", contents_from);
2091 read_from = contents_from;
2094 if (lstat(path, &st) < 0)
2095 die("Cannot lstat %s", path);
2098 fin_size = xsize_t(st.st_size);
2099 mode = canon_mode(st.st_mode);
2100 switch (st.st_mode & S_IFMT) {
2102 if (strbuf_read_file(&buf, read_from, st.st_size) != st.st_size)
2103 die("cannot open or read %s", read_from);
2106 if (readlink(read_from, buf.buf, buf.alloc) != fin_size)
2107 die("cannot readlink %s", read_from);
2111 die("unsupported file type %s", read_from);
2115 /* Reading from stdin */
2116 contents_from = "standard input";
2118 if (strbuf_read(&buf, 0, 0) < 0)
2119 die("read error %s from stdin", strerror(errno));
2121 convert_to_git(path, buf.buf, buf.len, &buf, 0);
2122 origin->file.ptr = buf.buf;
2123 origin->file.size = buf.len;
2124 pretend_sha1_file(buf.buf, buf.len, OBJ_BLOB, origin->blob_sha1);
2125 commit->util = origin;
2128 * Read the current index, replace the path entry with
2129 * origin->blob_sha1 without mucking with its mode or type
2130 * bits; we are not going to write this index out -- we just
2131 * want to run "diff-index --cached".
2138 int pos = cache_name_pos(path, len);
2140 mode = active_cache[pos]->ce_mode;
2142 /* Let's not bother reading from HEAD tree */
2143 mode = S_IFREG | 0644;
2145 size = cache_entry_size(len);
2146 ce = xcalloc(1, size);
2147 hashcpy(ce->sha1, origin->blob_sha1);
2148 memcpy(ce->name, path, len);
2149 ce->ce_flags = create_ce_flags(len, 0);
2150 ce->ce_mode = create_ce_mode(mode);
2151 add_cache_entry(ce, ADD_CACHE_OK_TO_ADD|ADD_CACHE_OK_TO_REPLACE);
2154 * We are not going to write this out, so this does not matter
2155 * right now, but someday we might optimize diff-index --cached
2156 * with cache-tree information.
2158 cache_tree_invalidate_path(active_cache_tree, path);
2160 commit->buffer = xmalloc(400);
2161 ident = fmt_ident("Not Committed Yet", "not.committed.yet", NULL, 0);
2162 snprintf(commit->buffer, 400,
2163 "tree 0000000000000000000000000000000000000000\n"
2167 "Version of %s from %s\n",
2168 sha1_to_hex(head_sha1),
2169 ident, ident, path, contents_from ? contents_from : path);
2173 static const char *prepare_final(struct scoreboard *sb)
2176 const char *final_commit_name = NULL;
2177 struct rev_info *revs = sb->revs;
2180 * There must be one and only one positive commit in the
2181 * revs->pending array.
2183 for (i = 0; i < revs->pending.nr; i++) {
2184 struct object *obj = revs->pending.objects[i].item;
2185 if (obj->flags & UNINTERESTING)
2187 while (obj->type == OBJ_TAG)
2188 obj = deref_tag(obj, NULL, 0);
2189 if (obj->type != OBJ_COMMIT)
2190 die("Non commit %s?", revs->pending.objects[i].name);
2192 die("More than one commit to dig from %s and %s?",
2193 revs->pending.objects[i].name,
2195 sb->final = (struct commit *) obj;
2196 final_commit_name = revs->pending.objects[i].name;
2198 return final_commit_name;
2201 static const char *prepare_initial(struct scoreboard *sb)
2204 const char *final_commit_name = NULL;
2205 struct rev_info *revs = sb->revs;
2208 * There must be one and only one negative commit, and it must be
2211 for (i = 0; i < revs->pending.nr; i++) {
2212 struct object *obj = revs->pending.objects[i].item;
2213 if (!(obj->flags & UNINTERESTING))
2215 while (obj->type == OBJ_TAG)
2216 obj = deref_tag(obj, NULL, 0);
2217 if (obj->type != OBJ_COMMIT)
2218 die("Non commit %s?", revs->pending.objects[i].name);
2220 die("More than one commit to dig down to %s and %s?",
2221 revs->pending.objects[i].name,
2223 sb->final = (struct commit *) obj;
2224 final_commit_name = revs->pending.objects[i].name;
2226 if (!final_commit_name)
2227 die("No commit to dig down to?");
2228 return final_commit_name;
2231 static int blame_copy_callback(const struct option *option, const char *arg, int unset)
2233 int *opt = option->value;
2236 * -C enables copy from removed files;
2237 * -C -C enables copy from existing files, but only
2238 * when blaming a new file;
2239 * -C -C -C enables copy from existing files for
2242 if (*opt & PICKAXE_BLAME_COPY_HARDER)
2243 *opt |= PICKAXE_BLAME_COPY_HARDEST;
2244 if (*opt & PICKAXE_BLAME_COPY)
2245 *opt |= PICKAXE_BLAME_COPY_HARDER;
2246 *opt |= PICKAXE_BLAME_COPY | PICKAXE_BLAME_MOVE;
2249 blame_copy_score = parse_score(arg);
2253 static int blame_move_callback(const struct option *option, const char *arg, int unset)
2255 int *opt = option->value;
2257 *opt |= PICKAXE_BLAME_MOVE;
2260 blame_move_score = parse_score(arg);
2264 static int blame_bottomtop_callback(const struct option *option, const char *arg, int unset)
2266 const char **bottomtop = option->value;
2270 die("More than one '-L n,m' option given");
2275 int cmd_blame(int argc, const char **argv, const char *prefix)
2277 struct rev_info revs;
2279 struct scoreboard sb;
2281 struct blame_entry *ent;
2282 long dashdash_pos, bottom, top, lno;
2283 const char *final_commit_name = NULL;
2284 enum object_type type;
2286 static const char *bottomtop = NULL;
2287 static int output_option = 0, opt = 0;
2288 static int show_stats = 0;
2289 static const char *revs_file = NULL;
2290 static const char *contents_from = NULL;
2291 static const struct option options[] = {
2292 OPT_BOOLEAN(0, "incremental", &incremental, "Show blame entries as we find them, incrementally"),
2293 OPT_BOOLEAN('b', NULL, &blank_boundary, "Show blank SHA-1 for boundary commits (Default: off)"),
2294 OPT_BOOLEAN(0, "root", &show_root, "Do not treat root commits as boundaries (Default: off)"),
2295 OPT_BOOLEAN(0, "show-stats", &show_stats, "Show work cost statistics"),
2296 OPT_BIT(0, "score-debug", &output_option, "Show output score for blame entries", OUTPUT_SHOW_SCORE),
2297 OPT_BIT('f', "show-name", &output_option, "Show original filename (Default: auto)", OUTPUT_SHOW_NAME),
2298 OPT_BIT('n', "show-number", &output_option, "Show original linenumber (Default: off)", OUTPUT_SHOW_NUMBER),
2299 OPT_BIT('p', "porcelain", &output_option, "Show in a format designed for machine consumption", OUTPUT_PORCELAIN),
2300 OPT_BIT('c', NULL, &output_option, "Use the same output mode as git-annotate (Default: off)", OUTPUT_ANNOTATE_COMPAT),
2301 OPT_BIT('t', NULL, &output_option, "Show raw timestamp (Default: off)", OUTPUT_RAW_TIMESTAMP),
2302 OPT_BIT('l', NULL, &output_option, "Show long commit SHA1 (Default: off)", OUTPUT_LONG_OBJECT_NAME),
2303 OPT_BIT('s', NULL, &output_option, "Suppress author name and timestamp (Default: off)", OUTPUT_NO_AUTHOR),
2304 OPT_BIT('w', NULL, &xdl_opts, "Ignore whitespace differences", XDF_IGNORE_WHITESPACE),
2305 OPT_STRING('S', NULL, &revs_file, "file", "Use revisions from <file> instead of calling git-rev-list"),
2306 OPT_STRING(0, "contents", &contents_from, "file", "Use <file>'s contents as the final image"),
2307 { OPTION_CALLBACK, 'C', NULL, &opt, "score", "Find line copies within and across files", PARSE_OPT_OPTARG, blame_copy_callback },
2308 { OPTION_CALLBACK, 'M', NULL, &opt, "score", "Find line movements within and across files", PARSE_OPT_OPTARG, blame_move_callback },
2309 OPT_CALLBACK('L', NULL, &bottomtop, "n,m", "Process only line range n,m, counting from 1", blame_bottomtop_callback),
2313 struct parse_opt_ctx_t ctx;
2315 cmd_is_annotate = !strcmp(argv[0], "annotate");
2317 git_config(git_blame_config, NULL);
2318 init_revisions(&revs, NULL);
2319 save_commit_buffer = 0;
2322 parse_options_start(&ctx, argc, argv, PARSE_OPT_KEEP_DASHDASH |
2323 PARSE_OPT_KEEP_ARGV0);
2325 switch (parse_options_step(&ctx, options, blame_opt_usage)) {
2326 case PARSE_OPT_HELP:
2328 case PARSE_OPT_DONE:
2330 dashdash_pos = ctx.cpidx;
2334 if (!strcmp(ctx.argv[0], "--reverse")) {
2335 ctx.argv[0] = "--children";
2338 parse_revision_opt(&revs, &ctx, options, blame_opt_usage);
2341 argc = parse_options_end(&ctx);
2343 if (!blame_move_score)
2344 blame_move_score = BLAME_DEFAULT_MOVE_SCORE;
2345 if (!blame_copy_score)
2346 blame_copy_score = BLAME_DEFAULT_COPY_SCORE;
2349 * We have collected options unknown to us in argv[1..unk]
2350 * which are to be passed to revision machinery if we are
2351 * going to do the "bottom" processing.
2353 * The remaining are:
2355 * (1) if dashdash_pos != 0, its either
2356 * "blame [revisions] -- <path>" or
2357 * "blame -- <path> <rev>"
2359 * (2) otherwise, its one of the two:
2360 * "blame [revisions] <path>"
2361 * "blame <path> <rev>"
2363 * Note that we must strip out <path> from the arguments: we do not
2364 * want the path pruning but we may want "bottom" processing.
2367 switch (argc - dashdash_pos - 1) {
2370 usage_with_options(blame_opt_usage, options);
2371 /* reorder for the new way: <rev> -- <path> */
2377 path = add_prefix(prefix, argv[--argc]);
2381 usage_with_options(blame_opt_usage, options);
2385 usage_with_options(blame_opt_usage, options);
2386 path = add_prefix(prefix, argv[argc - 1]);
2387 if (argc == 3 && !has_path_in_work_tree(path)) { /* (2b) */
2388 path = add_prefix(prefix, argv[1]);
2391 argv[argc - 1] = "--";
2394 if (!has_path_in_work_tree(path))
2395 die("cannot stat path %s: %s", path, strerror(errno));
2398 setup_revisions(argc, argv, &revs, NULL);
2399 memset(&sb, 0, sizeof(sb));
2403 final_commit_name = prepare_final(&sb);
2404 else if (contents_from)
2405 die("--contents and --children do not blend well.");
2407 final_commit_name = prepare_initial(&sb);
2411 * "--not A B -- path" without anything positive;
2412 * do not default to HEAD, but use the working tree
2416 sb.final = fake_working_tree_commit(path, contents_from);
2417 add_pending_object(&revs, &(sb.final->object), ":");
2419 else if (contents_from)
2420 die("Cannot use --contents with final commit object name");
2423 * If we have bottom, this will mark the ancestors of the
2424 * bottom commits we would reach while traversing as
2427 if (prepare_revision_walk(&revs))
2428 die("revision walk setup failed");
2430 if (is_null_sha1(sb.final->object.sha1)) {
2433 buf = xmalloc(o->file.size + 1);
2434 memcpy(buf, o->file.ptr, o->file.size + 1);
2436 sb.final_buf_size = o->file.size;
2439 o = get_origin(&sb, sb.final, path);
2440 if (fill_blob_sha1(o))
2441 die("no such path %s in %s", path, final_commit_name);
2443 sb.final_buf = read_sha1_file(o->blob_sha1, &type,
2444 &sb.final_buf_size);
2446 die("Cannot read blob %s for path %s",
2447 sha1_to_hex(o->blob_sha1),
2451 lno = prepare_lines(&sb);
2455 prepare_blame_range(&sb, bottomtop, lno, &bottom, &top);
2456 if (bottom && top && top < bottom) {
2458 tmp = top; top = bottom; bottom = tmp;
2466 die("file %s has only %lu lines", path, lno);
2468 ent = xcalloc(1, sizeof(*ent));
2470 ent->num_lines = top - bottom;
2472 ent->s_lno = bottom;
2477 if (revs_file && read_ancestry(revs_file))
2478 die("reading graft file %s failed: %s",
2479 revs_file, strerror(errno));
2481 read_mailmap(&mailmap, ".mailmap", NULL);
2486 assign_blame(&sb, opt);
2493 if (!(output_option & OUTPUT_PORCELAIN))
2494 find_alignment(&sb, &output_option);
2496 output(&sb, output_option);
2497 free((void *)sb.final_buf);
2498 for (ent = sb.ent; ent; ) {
2499 struct blame_entry *e = ent->next;
2505 printf("num read blob: %d\n", num_read_blob);
2506 printf("num get patch: %d\n", num_get_patch);
2507 printf("num commits: %d\n", num_commits);