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 cmd_is_annotate;
42 static int xdl_opts = XDF_NEED_MINIMAL;
43 static struct string_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 memset(&state, 0, sizeof(state));
532 state.xm.consume = process_u_diff;
533 state.ret = xmalloc(sizeof(struct patch));
534 state.ret->chunks = NULL;
537 xdi_diff_outf(file_p, file_o, &state.xm, &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 (porigin && !strcmp(p->one->path, porigin->path))
1139 /* find_move already dealt with this path */
1142 norigin = get_origin(sb, parent, p->one->path);
1143 hashcpy(norigin->blob_sha1, p->one->sha1);
1144 fill_origin_blob(norigin, &file_p);
1148 for (j = 0; j < num_ents; j++) {
1149 find_copy_in_blob(sb, blame_list[j].ent,
1150 norigin, this, &file_p);
1151 copy_split_if_better(sb, blame_list[j].split,
1155 origin_decref(norigin);
1158 for (j = 0; j < num_ents; j++) {
1159 struct blame_entry *split = blame_list[j].split;
1160 if (split[1].suspect &&
1161 blame_copy_score < ent_score(sb, &split[1])) {
1162 split_blame(sb, split, blame_list[j].ent);
1166 blame_list[j].ent->scanned = 1;
1167 decref_split(split);
1173 blame_list = setup_blame_list(sb, target, blame_copy_score, &num_ents);
1179 reset_scanned_flag(sb);
1180 diff_flush(&diff_opts);
1181 diff_tree_release_paths(&diff_opts);
1186 * The blobs of origin and porigin exactly match, so everything
1187 * origin is suspected for can be blamed on the parent.
1189 static void pass_whole_blame(struct scoreboard *sb,
1190 struct origin *origin, struct origin *porigin)
1192 struct blame_entry *e;
1194 if (!porigin->file.ptr && origin->file.ptr) {
1195 /* Steal its file */
1196 porigin->file = origin->file;
1197 origin->file.ptr = NULL;
1199 for (e = sb->ent; e; e = e->next) {
1200 if (!same_suspect(e->suspect, origin))
1202 origin_incref(porigin);
1203 origin_decref(e->suspect);
1204 e->suspect = porigin;
1209 * We pass blame from the current commit to its parents. We keep saying
1210 * "parent" (and "porigin"), but what we mean is to find scapegoat to
1211 * exonerate ourselves.
1213 static struct commit_list *first_scapegoat(struct rev_info *revs, struct commit *commit)
1216 return commit->parents;
1217 return lookup_decoration(&revs->children, &commit->object);
1220 static int num_scapegoats(struct rev_info *revs, struct commit *commit)
1223 struct commit_list *l = first_scapegoat(revs, commit);
1224 for (cnt = 0; l; l = l->next)
1231 static void pass_blame(struct scoreboard *sb, struct origin *origin, int opt)
1233 struct rev_info *revs = sb->revs;
1234 int i, pass, num_sg;
1235 struct commit *commit = origin->commit;
1236 struct commit_list *sg;
1237 struct origin *sg_buf[MAXSG];
1238 struct origin *porigin, **sg_origin = sg_buf;
1240 num_sg = num_scapegoats(revs, commit);
1243 else if (num_sg < ARRAY_SIZE(sg_buf))
1244 memset(sg_buf, 0, sizeof(sg_buf));
1246 sg_origin = xcalloc(num_sg, sizeof(*sg_origin));
1249 * The first pass looks for unrenamed path to optimize for
1250 * common cases, then we look for renames in the second pass.
1252 for (pass = 0; pass < 2; pass++) {
1253 struct origin *(*find)(struct scoreboard *,
1254 struct commit *, struct origin *);
1255 find = pass ? find_rename : find_origin;
1257 for (i = 0, sg = first_scapegoat(revs, commit);
1259 sg = sg->next, i++) {
1260 struct commit *p = sg->item;
1265 if (parse_commit(p))
1267 porigin = find(sb, p, origin);
1270 if (!hashcmp(porigin->blob_sha1, origin->blob_sha1)) {
1271 pass_whole_blame(sb, origin, porigin);
1272 origin_decref(porigin);
1275 for (j = same = 0; j < i; j++)
1277 !hashcmp(sg_origin[j]->blob_sha1,
1278 porigin->blob_sha1)) {
1283 sg_origin[i] = porigin;
1285 origin_decref(porigin);
1290 for (i = 0, sg = first_scapegoat(revs, commit);
1292 sg = sg->next, i++) {
1293 struct origin *porigin = sg_origin[i];
1296 if (pass_blame_to_parent(sb, origin, porigin))
1301 * Optionally find moves in parents' files.
1303 if (opt & PICKAXE_BLAME_MOVE)
1304 for (i = 0, sg = first_scapegoat(revs, commit);
1306 sg = sg->next, i++) {
1307 struct origin *porigin = sg_origin[i];
1310 if (find_move_in_parent(sb, origin, porigin))
1315 * Optionally find copies from parents' files.
1317 if (opt & PICKAXE_BLAME_COPY)
1318 for (i = 0, sg = first_scapegoat(revs, commit);
1320 sg = sg->next, i++) {
1321 struct origin *porigin = sg_origin[i];
1322 if (find_copy_in_parent(sb, origin, sg->item,
1328 for (i = 0; i < num_sg; i++) {
1330 drop_origin_blob(sg_origin[i]);
1331 origin_decref(sg_origin[i]);
1334 drop_origin_blob(origin);
1335 if (sg_buf != sg_origin)
1340 * Information on commits, used for output.
1345 const char *author_mail;
1346 unsigned long author_time;
1347 const char *author_tz;
1349 /* filled only when asked for details */
1350 const char *committer;
1351 const char *committer_mail;
1352 unsigned long committer_time;
1353 const char *committer_tz;
1355 const char *summary;
1359 * Parse author/committer line in the commit object buffer
1361 static void get_ac_line(const char *inbuf, const char *what,
1362 int bufsz, char *person, const char **mail,
1363 unsigned long *time, const char **tz)
1365 int len, tzlen, maillen;
1366 char *tmp, *endp, *timepos;
1368 tmp = strstr(inbuf, what);
1371 tmp += strlen(what);
1372 endp = strchr(tmp, '\n');
1380 *mail = *tz = "(unknown)";
1384 memcpy(person, tmp, len);
1392 tzlen = (person+len)-(tmp+1);
1397 *time = strtoul(tmp, NULL, 10);
1405 maillen = timepos - tmp;
1411 * mailmap expansion may make the name longer.
1412 * make room by pushing stuff down.
1414 tmp = person + bufsz - (tzlen + 1);
1415 memmove(tmp, *tz, tzlen);
1419 tmp = tmp - (maillen + 1);
1420 memmove(tmp, *mail, maillen);
1425 * Now, convert e-mail using mailmap
1427 map_email(&mailmap, tmp + 1, person, tmp-person-1);
1430 static void get_commit_info(struct commit *commit,
1431 struct commit_info *ret,
1436 static char author_buf[1024];
1437 static char committer_buf[1024];
1438 static char summary_buf[1024];
1441 * We've operated without save_commit_buffer, so
1442 * we now need to populate them for output.
1444 if (!commit->buffer) {
1445 enum object_type type;
1448 read_sha1_file(commit->object.sha1, &type, &size);
1449 if (!commit->buffer)
1450 die("Cannot read commit %s",
1451 sha1_to_hex(commit->object.sha1));
1453 ret->author = author_buf;
1454 get_ac_line(commit->buffer, "\nauthor ",
1455 sizeof(author_buf), author_buf, &ret->author_mail,
1456 &ret->author_time, &ret->author_tz);
1461 ret->committer = committer_buf;
1462 get_ac_line(commit->buffer, "\ncommitter ",
1463 sizeof(committer_buf), committer_buf, &ret->committer_mail,
1464 &ret->committer_time, &ret->committer_tz);
1466 ret->summary = summary_buf;
1467 tmp = strstr(commit->buffer, "\n\n");
1470 sprintf(summary_buf, "(%s)", sha1_to_hex(commit->object.sha1));
1474 endp = strchr(tmp, '\n');
1476 endp = tmp + strlen(tmp);
1478 if (len >= sizeof(summary_buf) || len == 0)
1480 memcpy(summary_buf, tmp, len);
1481 summary_buf[len] = 0;
1485 * To allow LF and other nonportable characters in pathnames,
1486 * they are c-style quoted as needed.
1488 static void write_filename_info(const char *path)
1490 printf("filename ");
1491 write_name_quoted(path, stdout, '\n');
1495 * The blame_entry is found to be guilty for the range. Mark it
1496 * as such, and show it in incremental output.
1498 static void found_guilty_entry(struct blame_entry *ent)
1504 struct origin *suspect = ent->suspect;
1506 printf("%s %d %d %d\n",
1507 sha1_to_hex(suspect->commit->object.sha1),
1508 ent->s_lno + 1, ent->lno + 1, ent->num_lines);
1509 if (!(suspect->commit->object.flags & METAINFO_SHOWN)) {
1510 struct commit_info ci;
1511 suspect->commit->object.flags |= METAINFO_SHOWN;
1512 get_commit_info(suspect->commit, &ci, 1);
1513 printf("author %s\n", ci.author);
1514 printf("author-mail %s\n", ci.author_mail);
1515 printf("author-time %lu\n", ci.author_time);
1516 printf("author-tz %s\n", ci.author_tz);
1517 printf("committer %s\n", ci.committer);
1518 printf("committer-mail %s\n", ci.committer_mail);
1519 printf("committer-time %lu\n", ci.committer_time);
1520 printf("committer-tz %s\n", ci.committer_tz);
1521 printf("summary %s\n", ci.summary);
1522 if (suspect->commit->object.flags & UNINTERESTING)
1523 printf("boundary\n");
1525 write_filename_info(suspect->path);
1526 maybe_flush_or_die(stdout, "stdout");
1531 * The main loop -- while the scoreboard has lines whose true origin
1532 * is still unknown, pick one blame_entry, and allow its current
1533 * suspect to pass blames to its parents.
1535 static void assign_blame(struct scoreboard *sb, int opt)
1537 struct rev_info *revs = sb->revs;
1540 struct blame_entry *ent;
1541 struct commit *commit;
1542 struct origin *suspect = NULL;
1544 /* find one suspect to break down */
1545 for (ent = sb->ent; !suspect && ent; ent = ent->next)
1547 suspect = ent->suspect;
1549 return; /* all done */
1552 * We will use this suspect later in the loop,
1553 * so hold onto it in the meantime.
1555 origin_incref(suspect);
1556 commit = suspect->commit;
1557 if (!commit->object.parsed)
1558 parse_commit(commit);
1560 (!(commit->object.flags & UNINTERESTING) &&
1561 !(revs->max_age != -1 && commit->date < revs->max_age)))
1562 pass_blame(sb, suspect, opt);
1564 commit->object.flags |= UNINTERESTING;
1565 if (commit->object.parsed)
1566 mark_parents_uninteresting(commit);
1568 /* treat root commit as boundary */
1569 if (!commit->parents && !show_root)
1570 commit->object.flags |= UNINTERESTING;
1572 /* Take responsibility for the remaining entries */
1573 for (ent = sb->ent; ent; ent = ent->next)
1574 if (same_suspect(ent->suspect, suspect))
1575 found_guilty_entry(ent);
1576 origin_decref(suspect);
1578 if (DEBUG) /* sanity */
1579 sanity_check_refcnt(sb);
1583 static const char *format_time(unsigned long time, const char *tz_str,
1586 static char time_buf[128];
1591 if (show_raw_time) {
1592 sprintf(time_buf, "%lu %s", time, tz_str);
1597 minutes = tz < 0 ? -tz : tz;
1598 minutes = (minutes / 100)*60 + (minutes % 100);
1599 minutes = tz < 0 ? -minutes : minutes;
1600 t = time + minutes * 60;
1603 strftime(time_buf, sizeof(time_buf), "%Y-%m-%d %H:%M:%S ", tm);
1604 strcat(time_buf, tz_str);
1608 #define OUTPUT_ANNOTATE_COMPAT 001
1609 #define OUTPUT_LONG_OBJECT_NAME 002
1610 #define OUTPUT_RAW_TIMESTAMP 004
1611 #define OUTPUT_PORCELAIN 010
1612 #define OUTPUT_SHOW_NAME 020
1613 #define OUTPUT_SHOW_NUMBER 040
1614 #define OUTPUT_SHOW_SCORE 0100
1615 #define OUTPUT_NO_AUTHOR 0200
1617 static void emit_porcelain(struct scoreboard *sb, struct blame_entry *ent)
1621 struct origin *suspect = ent->suspect;
1624 strcpy(hex, sha1_to_hex(suspect->commit->object.sha1));
1625 printf("%s%c%d %d %d\n",
1627 ent->guilty ? ' ' : '*', // purely for debugging
1631 if (!(suspect->commit->object.flags & METAINFO_SHOWN)) {
1632 struct commit_info ci;
1633 suspect->commit->object.flags |= METAINFO_SHOWN;
1634 get_commit_info(suspect->commit, &ci, 1);
1635 printf("author %s\n", ci.author);
1636 printf("author-mail %s\n", ci.author_mail);
1637 printf("author-time %lu\n", ci.author_time);
1638 printf("author-tz %s\n", ci.author_tz);
1639 printf("committer %s\n", ci.committer);
1640 printf("committer-mail %s\n", ci.committer_mail);
1641 printf("committer-time %lu\n", ci.committer_time);
1642 printf("committer-tz %s\n", ci.committer_tz);
1643 write_filename_info(suspect->path);
1644 printf("summary %s\n", ci.summary);
1645 if (suspect->commit->object.flags & UNINTERESTING)
1646 printf("boundary\n");
1648 else if (suspect->commit->object.flags & MORE_THAN_ONE_PATH)
1649 write_filename_info(suspect->path);
1651 cp = nth_line(sb, ent->lno);
1652 for (cnt = 0; cnt < ent->num_lines; cnt++) {
1655 printf("%s %d %d\n", hex,
1656 ent->s_lno + 1 + cnt,
1657 ent->lno + 1 + cnt);
1662 } while (ch != '\n' &&
1663 cp < sb->final_buf + sb->final_buf_size);
1667 static void emit_other(struct scoreboard *sb, struct blame_entry *ent, int opt)
1671 struct origin *suspect = ent->suspect;
1672 struct commit_info ci;
1674 int show_raw_time = !!(opt & OUTPUT_RAW_TIMESTAMP);
1676 get_commit_info(suspect->commit, &ci, 1);
1677 strcpy(hex, sha1_to_hex(suspect->commit->object.sha1));
1679 cp = nth_line(sb, ent->lno);
1680 for (cnt = 0; cnt < ent->num_lines; cnt++) {
1682 int length = (opt & OUTPUT_LONG_OBJECT_NAME) ? 40 : 8;
1684 if (suspect->commit->object.flags & UNINTERESTING) {
1686 memset(hex, ' ', length);
1687 else if (!cmd_is_annotate) {
1693 printf("%.*s", length, hex);
1694 if (opt & OUTPUT_ANNOTATE_COMPAT)
1695 printf("\t(%10s\t%10s\t%d)", ci.author,
1696 format_time(ci.author_time, ci.author_tz,
1698 ent->lno + 1 + cnt);
1700 if (opt & OUTPUT_SHOW_SCORE)
1702 max_score_digits, ent->score,
1703 ent->suspect->refcnt);
1704 if (opt & OUTPUT_SHOW_NAME)
1705 printf(" %-*.*s", longest_file, longest_file,
1707 if (opt & OUTPUT_SHOW_NUMBER)
1708 printf(" %*d", max_orig_digits,
1709 ent->s_lno + 1 + cnt);
1711 if (!(opt & OUTPUT_NO_AUTHOR))
1712 printf(" (%-*.*s %10s",
1713 longest_author, longest_author,
1715 format_time(ci.author_time,
1719 max_digits, ent->lno + 1 + cnt);
1724 } while (ch != '\n' &&
1725 cp < sb->final_buf + sb->final_buf_size);
1729 static void output(struct scoreboard *sb, int option)
1731 struct blame_entry *ent;
1733 if (option & OUTPUT_PORCELAIN) {
1734 for (ent = sb->ent; ent; ent = ent->next) {
1735 struct blame_entry *oth;
1736 struct origin *suspect = ent->suspect;
1737 struct commit *commit = suspect->commit;
1738 if (commit->object.flags & MORE_THAN_ONE_PATH)
1740 for (oth = ent->next; oth; oth = oth->next) {
1741 if ((oth->suspect->commit != commit) ||
1742 !strcmp(oth->suspect->path, suspect->path))
1744 commit->object.flags |= MORE_THAN_ONE_PATH;
1750 for (ent = sb->ent; ent; ent = ent->next) {
1751 if (option & OUTPUT_PORCELAIN)
1752 emit_porcelain(sb, ent);
1754 emit_other(sb, ent, option);
1760 * To allow quick access to the contents of nth line in the
1761 * final image, prepare an index in the scoreboard.
1763 static int prepare_lines(struct scoreboard *sb)
1765 const char *buf = sb->final_buf;
1766 unsigned long len = sb->final_buf_size;
1767 int num = 0, incomplete = 0, bol = 1;
1769 if (len && buf[len-1] != '\n')
1770 incomplete++; /* incomplete line at the end */
1773 sb->lineno = xrealloc(sb->lineno,
1774 sizeof(int* ) * (num + 1));
1775 sb->lineno[num] = buf - sb->final_buf;
1778 if (*buf++ == '\n') {
1783 sb->lineno = xrealloc(sb->lineno,
1784 sizeof(int* ) * (num + incomplete + 1));
1785 sb->lineno[num + incomplete] = buf - sb->final_buf;
1786 sb->num_lines = num + incomplete;
1787 return sb->num_lines;
1791 * Add phony grafts for use with -S; this is primarily to
1792 * support git-cvsserver that wants to give a linear history
1795 static int read_ancestry(const char *graft_file)
1797 FILE *fp = fopen(graft_file, "r");
1801 while (fgets(buf, sizeof(buf), fp)) {
1802 /* The format is just "Commit Parent1 Parent2 ...\n" */
1803 int len = strlen(buf);
1804 struct commit_graft *graft = read_graft_line(buf, len);
1806 register_commit_graft(graft, 0);
1813 * How many columns do we need to show line numbers in decimal?
1815 static int lineno_width(int lines)
1819 for (width = 1, i = 10; i <= lines + 1; width++)
1825 * How many columns do we need to show line numbers, authors,
1828 static void find_alignment(struct scoreboard *sb, int *option)
1830 int longest_src_lines = 0;
1831 int longest_dst_lines = 0;
1832 unsigned largest_score = 0;
1833 struct blame_entry *e;
1835 for (e = sb->ent; e; e = e->next) {
1836 struct origin *suspect = e->suspect;
1837 struct commit_info ci;
1840 if (strcmp(suspect->path, sb->path))
1841 *option |= OUTPUT_SHOW_NAME;
1842 num = strlen(suspect->path);
1843 if (longest_file < num)
1845 if (!(suspect->commit->object.flags & METAINFO_SHOWN)) {
1846 suspect->commit->object.flags |= METAINFO_SHOWN;
1847 get_commit_info(suspect->commit, &ci, 1);
1848 num = strlen(ci.author);
1849 if (longest_author < num)
1850 longest_author = num;
1852 num = e->s_lno + e->num_lines;
1853 if (longest_src_lines < num)
1854 longest_src_lines = num;
1855 num = e->lno + e->num_lines;
1856 if (longest_dst_lines < num)
1857 longest_dst_lines = num;
1858 if (largest_score < ent_score(sb, e))
1859 largest_score = ent_score(sb, e);
1861 max_orig_digits = lineno_width(longest_src_lines);
1862 max_digits = lineno_width(longest_dst_lines);
1863 max_score_digits = lineno_width(largest_score);
1867 * For debugging -- origin is refcounted, and this asserts that
1868 * we do not underflow.
1870 static void sanity_check_refcnt(struct scoreboard *sb)
1873 struct blame_entry *ent;
1875 for (ent = sb->ent; ent; ent = ent->next) {
1876 /* Nobody should have zero or negative refcnt */
1877 if (ent->suspect->refcnt <= 0) {
1878 fprintf(stderr, "%s in %s has negative refcnt %d\n",
1880 sha1_to_hex(ent->suspect->commit->object.sha1),
1881 ent->suspect->refcnt);
1885 for (ent = sb->ent; ent; ent = ent->next) {
1886 /* Mark the ones that haven't been checked */
1887 if (0 < ent->suspect->refcnt)
1888 ent->suspect->refcnt = -ent->suspect->refcnt;
1890 for (ent = sb->ent; ent; ent = ent->next) {
1892 * ... then pick each and see if they have the the
1896 struct blame_entry *e;
1897 struct origin *suspect = ent->suspect;
1899 if (0 < suspect->refcnt)
1901 suspect->refcnt = -suspect->refcnt; /* Unmark */
1902 for (found = 0, e = sb->ent; e; e = e->next) {
1903 if (e->suspect != suspect)
1907 if (suspect->refcnt != found) {
1908 fprintf(stderr, "%s in %s has refcnt %d, not %d\n",
1910 sha1_to_hex(ent->suspect->commit->object.sha1),
1911 ent->suspect->refcnt, found);
1917 find_alignment(sb, &opt);
1919 die("Baa %d!", baa);
1924 * Used for the command line parsing; check if the path exists
1925 * in the working tree.
1927 static int has_string_in_work_tree(const char *path)
1930 return !lstat(path, &st);
1933 static unsigned parse_score(const char *arg)
1936 unsigned long score = strtoul(arg, &end, 10);
1942 static const char *add_prefix(const char *prefix, const char *path)
1944 return prefix_path(prefix, prefix ? strlen(prefix) : 0, path);
1948 * Parsing of (comma separated) one item in the -L option
1950 static const char *parse_loc(const char *spec,
1951 struct scoreboard *sb, long lno,
1952 long begin, long *ret)
1959 regmatch_t match[1];
1961 /* Allow "-L <something>,+20" to mean starting at <something>
1962 * for 20 lines, or "-L <something>,-5" for 5 lines ending at
1965 if (1 < begin && (spec[0] == '+' || spec[0] == '-')) {
1966 num = strtol(spec + 1, &term, 10);
1967 if (term != spec + 1) {
1971 *ret = begin + num - 2;
1980 num = strtol(spec, &term, 10);
1988 /* it could be a regexp of form /.../ */
1989 for (term = (char*) spec + 1; *term && *term != '/'; term++) {
1996 /* try [spec+1 .. term-1] as regexp */
1998 begin--; /* input is in human terms */
1999 line = nth_line(sb, begin);
2001 if (!(reg_error = regcomp(®exp, spec + 1, REG_NEWLINE)) &&
2002 !(reg_error = regexec(®exp, line, 1, match, 0))) {
2003 const char *cp = line + match[0].rm_so;
2006 while (begin++ < lno) {
2007 nline = nth_line(sb, begin);
2008 if (line <= cp && cp < nline)
2019 regerror(reg_error, ®exp, errbuf, 1024);
2020 die("-L parameter '%s': %s", spec + 1, errbuf);
2025 * Parsing of -L option
2027 static void prepare_blame_range(struct scoreboard *sb,
2028 const char *bottomtop,
2030 long *bottom, long *top)
2034 term = parse_loc(bottomtop, sb, lno, 1, bottom);
2036 term = parse_loc(term + 1, sb, lno, *bottom + 1, top);
2044 static int git_blame_config(const char *var, const char *value, void *cb)
2046 if (!strcmp(var, "blame.showroot")) {
2047 show_root = git_config_bool(var, value);
2050 if (!strcmp(var, "blame.blankboundary")) {
2051 blank_boundary = git_config_bool(var, value);
2054 return git_default_config(var, value, cb);
2058 * Prepare a dummy commit that represents the work tree (or staged) item.
2059 * Note that annotating work tree item never works in the reverse.
2061 static struct commit *fake_working_tree_commit(const char *path, const char *contents_from)
2063 struct commit *commit;
2064 struct origin *origin;
2065 unsigned char head_sha1[20];
2070 struct cache_entry *ce;
2073 if (get_sha1("HEAD", head_sha1))
2074 die("No such ref: HEAD");
2077 commit = xcalloc(1, sizeof(*commit));
2078 commit->parents = xcalloc(1, sizeof(*commit->parents));
2079 commit->parents->item = lookup_commit_reference(head_sha1);
2080 commit->object.parsed = 1;
2082 commit->object.type = OBJ_COMMIT;
2084 origin = make_origin(commit, path);
2086 strbuf_init(&buf, 0);
2087 if (!contents_from || strcmp("-", contents_from)) {
2089 const char *read_from;
2090 unsigned long fin_size;
2092 if (contents_from) {
2093 if (stat(contents_from, &st) < 0)
2094 die("Cannot stat %s", contents_from);
2095 read_from = contents_from;
2098 if (lstat(path, &st) < 0)
2099 die("Cannot lstat %s", path);
2102 fin_size = xsize_t(st.st_size);
2103 mode = canon_mode(st.st_mode);
2104 switch (st.st_mode & S_IFMT) {
2106 if (strbuf_read_file(&buf, read_from, st.st_size) != st.st_size)
2107 die("cannot open or read %s", read_from);
2110 if (readlink(read_from, buf.buf, buf.alloc) != fin_size)
2111 die("cannot readlink %s", read_from);
2115 die("unsupported file type %s", read_from);
2119 /* Reading from stdin */
2120 contents_from = "standard input";
2122 if (strbuf_read(&buf, 0, 0) < 0)
2123 die("read error %s from stdin", strerror(errno));
2125 convert_to_git(path, buf.buf, buf.len, &buf, 0);
2126 origin->file.ptr = buf.buf;
2127 origin->file.size = buf.len;
2128 pretend_sha1_file(buf.buf, buf.len, OBJ_BLOB, origin->blob_sha1);
2129 commit->util = origin;
2132 * Read the current index, replace the path entry with
2133 * origin->blob_sha1 without mucking with its mode or type
2134 * bits; we are not going to write this index out -- we just
2135 * want to run "diff-index --cached".
2142 int pos = cache_name_pos(path, len);
2144 mode = active_cache[pos]->ce_mode;
2146 /* Let's not bother reading from HEAD tree */
2147 mode = S_IFREG | 0644;
2149 size = cache_entry_size(len);
2150 ce = xcalloc(1, size);
2151 hashcpy(ce->sha1, origin->blob_sha1);
2152 memcpy(ce->name, path, len);
2153 ce->ce_flags = create_ce_flags(len, 0);
2154 ce->ce_mode = create_ce_mode(mode);
2155 add_cache_entry(ce, ADD_CACHE_OK_TO_ADD|ADD_CACHE_OK_TO_REPLACE);
2158 * We are not going to write this out, so this does not matter
2159 * right now, but someday we might optimize diff-index --cached
2160 * with cache-tree information.
2162 cache_tree_invalidate_path(active_cache_tree, path);
2164 commit->buffer = xmalloc(400);
2165 ident = fmt_ident("Not Committed Yet", "not.committed.yet", NULL, 0);
2166 snprintf(commit->buffer, 400,
2167 "tree 0000000000000000000000000000000000000000\n"
2171 "Version of %s from %s\n",
2172 sha1_to_hex(head_sha1),
2173 ident, ident, path, contents_from ? contents_from : path);
2177 static const char *prepare_final(struct scoreboard *sb)
2180 const char *final_commit_name = NULL;
2181 struct rev_info *revs = sb->revs;
2184 * There must be one and only one positive commit in the
2185 * revs->pending array.
2187 for (i = 0; i < revs->pending.nr; i++) {
2188 struct object *obj = revs->pending.objects[i].item;
2189 if (obj->flags & UNINTERESTING)
2191 while (obj->type == OBJ_TAG)
2192 obj = deref_tag(obj, NULL, 0);
2193 if (obj->type != OBJ_COMMIT)
2194 die("Non commit %s?", revs->pending.objects[i].name);
2196 die("More than one commit to dig from %s and %s?",
2197 revs->pending.objects[i].name,
2199 sb->final = (struct commit *) obj;
2200 final_commit_name = revs->pending.objects[i].name;
2202 return final_commit_name;
2205 static const char *prepare_initial(struct scoreboard *sb)
2208 const char *final_commit_name = NULL;
2209 struct rev_info *revs = sb->revs;
2212 * There must be one and only one negative commit, and it must be
2215 for (i = 0; i < revs->pending.nr; i++) {
2216 struct object *obj = revs->pending.objects[i].item;
2217 if (!(obj->flags & UNINTERESTING))
2219 while (obj->type == OBJ_TAG)
2220 obj = deref_tag(obj, NULL, 0);
2221 if (obj->type != OBJ_COMMIT)
2222 die("Non commit %s?", revs->pending.objects[i].name);
2224 die("More than one commit to dig down to %s and %s?",
2225 revs->pending.objects[i].name,
2227 sb->final = (struct commit *) obj;
2228 final_commit_name = revs->pending.objects[i].name;
2230 if (!final_commit_name)
2231 die("No commit to dig down to?");
2232 return final_commit_name;
2235 static int blame_copy_callback(const struct option *option, const char *arg, int unset)
2237 int *opt = option->value;
2240 * -C enables copy from removed files;
2241 * -C -C enables copy from existing files, but only
2242 * when blaming a new file;
2243 * -C -C -C enables copy from existing files for
2246 if (*opt & PICKAXE_BLAME_COPY_HARDER)
2247 *opt |= PICKAXE_BLAME_COPY_HARDEST;
2248 if (*opt & PICKAXE_BLAME_COPY)
2249 *opt |= PICKAXE_BLAME_COPY_HARDER;
2250 *opt |= PICKAXE_BLAME_COPY | PICKAXE_BLAME_MOVE;
2253 blame_copy_score = parse_score(arg);
2257 static int blame_move_callback(const struct option *option, const char *arg, int unset)
2259 int *opt = option->value;
2261 *opt |= PICKAXE_BLAME_MOVE;
2264 blame_move_score = parse_score(arg);
2268 static int blame_bottomtop_callback(const struct option *option, const char *arg, int unset)
2270 const char **bottomtop = option->value;
2274 die("More than one '-L n,m' option given");
2279 int cmd_blame(int argc, const char **argv, const char *prefix)
2281 struct rev_info revs;
2283 struct scoreboard sb;
2285 struct blame_entry *ent;
2286 long dashdash_pos, bottom, top, lno;
2287 const char *final_commit_name = NULL;
2288 enum object_type type;
2290 static const char *bottomtop = NULL;
2291 static int output_option = 0, opt = 0;
2292 static int show_stats = 0;
2293 static const char *revs_file = NULL;
2294 static const char *contents_from = NULL;
2295 static const struct option options[] = {
2296 OPT_BOOLEAN(0, "incremental", &incremental, "Show blame entries as we find them, incrementally"),
2297 OPT_BOOLEAN('b', NULL, &blank_boundary, "Show blank SHA-1 for boundary commits (Default: off)"),
2298 OPT_BOOLEAN(0, "root", &show_root, "Do not treat root commits as boundaries (Default: off)"),
2299 OPT_BOOLEAN(0, "show-stats", &show_stats, "Show work cost statistics"),
2300 OPT_BIT(0, "score-debug", &output_option, "Show output score for blame entries", OUTPUT_SHOW_SCORE),
2301 OPT_BIT('f', "show-name", &output_option, "Show original filename (Default: auto)", OUTPUT_SHOW_NAME),
2302 OPT_BIT('n', "show-number", &output_option, "Show original linenumber (Default: off)", OUTPUT_SHOW_NUMBER),
2303 OPT_BIT('p', "porcelain", &output_option, "Show in a format designed for machine consumption", OUTPUT_PORCELAIN),
2304 OPT_BIT('c', NULL, &output_option, "Use the same output mode as git-annotate (Default: off)", OUTPUT_ANNOTATE_COMPAT),
2305 OPT_BIT('t', NULL, &output_option, "Show raw timestamp (Default: off)", OUTPUT_RAW_TIMESTAMP),
2306 OPT_BIT('l', NULL, &output_option, "Show long commit SHA1 (Default: off)", OUTPUT_LONG_OBJECT_NAME),
2307 OPT_BIT('s', NULL, &output_option, "Suppress author name and timestamp (Default: off)", OUTPUT_NO_AUTHOR),
2308 OPT_BIT('w', NULL, &xdl_opts, "Ignore whitespace differences", XDF_IGNORE_WHITESPACE),
2309 OPT_STRING('S', NULL, &revs_file, "file", "Use revisions from <file> instead of calling git-rev-list"),
2310 OPT_STRING(0, "contents", &contents_from, "file", "Use <file>'s contents as the final image"),
2311 { OPTION_CALLBACK, 'C', NULL, &opt, "score", "Find line copies within and across files", PARSE_OPT_OPTARG, blame_copy_callback },
2312 { OPTION_CALLBACK, 'M', NULL, &opt, "score", "Find line movements within and across files", PARSE_OPT_OPTARG, blame_move_callback },
2313 OPT_CALLBACK('L', NULL, &bottomtop, "n,m", "Process only line range n,m, counting from 1", blame_bottomtop_callback),
2317 struct parse_opt_ctx_t ctx;
2319 cmd_is_annotate = !strcmp(argv[0], "annotate");
2321 git_config(git_blame_config, NULL);
2322 init_revisions(&revs, NULL);
2323 save_commit_buffer = 0;
2326 parse_options_start(&ctx, argc, argv, PARSE_OPT_KEEP_DASHDASH |
2327 PARSE_OPT_KEEP_ARGV0);
2329 switch (parse_options_step(&ctx, options, blame_opt_usage)) {
2330 case PARSE_OPT_HELP:
2332 case PARSE_OPT_DONE:
2334 dashdash_pos = ctx.cpidx;
2338 if (!strcmp(ctx.argv[0], "--reverse")) {
2339 ctx.argv[0] = "--children";
2342 parse_revision_opt(&revs, &ctx, options, blame_opt_usage);
2345 argc = parse_options_end(&ctx);
2347 if (DIFF_OPT_TST(&revs.diffopt, FIND_COPIES_HARDER))
2348 opt |= (PICKAXE_BLAME_COPY | PICKAXE_BLAME_MOVE |
2349 PICKAXE_BLAME_COPY_HARDER);
2351 if (!blame_move_score)
2352 blame_move_score = BLAME_DEFAULT_MOVE_SCORE;
2353 if (!blame_copy_score)
2354 blame_copy_score = BLAME_DEFAULT_COPY_SCORE;
2357 * We have collected options unknown to us in argv[1..unk]
2358 * which are to be passed to revision machinery if we are
2359 * going to do the "bottom" processing.
2361 * The remaining are:
2363 * (1) if dashdash_pos != 0, its either
2364 * "blame [revisions] -- <path>" or
2365 * "blame -- <path> <rev>"
2367 * (2) otherwise, its one of the two:
2368 * "blame [revisions] <path>"
2369 * "blame <path> <rev>"
2371 * Note that we must strip out <path> from the arguments: we do not
2372 * want the path pruning but we may want "bottom" processing.
2375 switch (argc - dashdash_pos - 1) {
2378 usage_with_options(blame_opt_usage, options);
2379 /* reorder for the new way: <rev> -- <path> */
2385 path = add_prefix(prefix, argv[--argc]);
2389 usage_with_options(blame_opt_usage, options);
2393 usage_with_options(blame_opt_usage, options);
2394 path = add_prefix(prefix, argv[argc - 1]);
2395 if (argc == 3 && !has_string_in_work_tree(path)) { /* (2b) */
2396 path = add_prefix(prefix, argv[1]);
2399 argv[argc - 1] = "--";
2402 if (!has_string_in_work_tree(path))
2403 die("cannot stat path %s: %s", path, strerror(errno));
2406 setup_revisions(argc, argv, &revs, NULL);
2407 memset(&sb, 0, sizeof(sb));
2411 final_commit_name = prepare_final(&sb);
2412 else if (contents_from)
2413 die("--contents and --children do not blend well.");
2415 final_commit_name = prepare_initial(&sb);
2419 * "--not A B -- path" without anything positive;
2420 * do not default to HEAD, but use the working tree
2424 sb.final = fake_working_tree_commit(path, contents_from);
2425 add_pending_object(&revs, &(sb.final->object), ":");
2427 else if (contents_from)
2428 die("Cannot use --contents with final commit object name");
2431 * If we have bottom, this will mark the ancestors of the
2432 * bottom commits we would reach while traversing as
2435 if (prepare_revision_walk(&revs))
2436 die("revision walk setup failed");
2438 if (is_null_sha1(sb.final->object.sha1)) {
2441 buf = xmalloc(o->file.size + 1);
2442 memcpy(buf, o->file.ptr, o->file.size + 1);
2444 sb.final_buf_size = o->file.size;
2447 o = get_origin(&sb, sb.final, path);
2448 if (fill_blob_sha1(o))
2449 die("no such path %s in %s", path, final_commit_name);
2451 sb.final_buf = read_sha1_file(o->blob_sha1, &type,
2452 &sb.final_buf_size);
2454 die("Cannot read blob %s for path %s",
2455 sha1_to_hex(o->blob_sha1),
2459 lno = prepare_lines(&sb);
2463 prepare_blame_range(&sb, bottomtop, lno, &bottom, &top);
2464 if (bottom && top && top < bottom) {
2466 tmp = top; top = bottom; bottom = tmp;
2474 die("file %s has only %lu lines", path, lno);
2476 ent = xcalloc(1, sizeof(*ent));
2478 ent->num_lines = top - bottom;
2480 ent->s_lno = bottom;
2485 if (revs_file && read_ancestry(revs_file))
2486 die("reading graft file %s failed: %s",
2487 revs_file, strerror(errno));
2489 read_mailmap(&mailmap, ".mailmap", NULL);
2494 assign_blame(&sb, opt);
2501 if (!(output_option & OUTPUT_PORCELAIN))
2502 find_alignment(&sb, &output_option);
2504 output(&sb, output_option);
2505 free((void *)sb.final_buf);
2506 for (ent = sb.ent; ent; ) {
2507 struct blame_entry *e = ent->next;
2513 printf("num read blob: %d\n", num_read_blob);
2514 printf("num get patch: %d\n", num_get_patch);
2515 printf("num commits: %d\n", num_commits);