4 * Copyright (c) 2006, Junio C Hamano
12 #include "tree-walk.h"
17 #include "xdiff-interface.h"
18 #include "cache-tree.h"
19 #include "string-list.h"
21 #include "parse-options.h"
23 static char blame_usage[] = "git blame [options] [rev-opts] [rev] [--] file";
25 static const char *blame_opt_usage[] = {
28 "[rev-opts] are documented in git-rev-list(1)",
32 static int longest_file;
33 static int longest_author;
34 static int max_orig_digits;
35 static int max_digits;
36 static int max_score_digits;
39 static int blank_boundary;
40 static int incremental;
41 static int xdl_opts = XDF_NEED_MINIMAL;
42 static struct string_list mailmap;
49 static int num_read_blob;
50 static int num_get_patch;
51 static int num_commits;
53 #define PICKAXE_BLAME_MOVE 01
54 #define PICKAXE_BLAME_COPY 02
55 #define PICKAXE_BLAME_COPY_HARDER 04
56 #define PICKAXE_BLAME_COPY_HARDEST 010
59 * blame for a blame_entry with score lower than these thresholds
60 * is not passed to the parent using move/copy logic.
62 static unsigned blame_move_score;
63 static unsigned blame_copy_score;
64 #define BLAME_DEFAULT_MOVE_SCORE 20
65 #define BLAME_DEFAULT_COPY_SCORE 40
67 /* bits #0..7 in revision.h, #8..11 used for merge_bases() in commit.c */
68 #define METAINFO_SHOWN (1u<<12)
69 #define MORE_THAN_ONE_PATH (1u<<13)
72 * One blob in a commit that is being suspected
76 struct commit *commit;
78 unsigned char blob_sha1[20];
79 char path[FLEX_ARRAY];
83 * Given an origin, prepare mmfile_t structure to be used by the
86 static void fill_origin_blob(struct origin *o, mmfile_t *file)
89 enum object_type type;
91 file->ptr = read_sha1_file(o->blob_sha1, &type,
92 (unsigned long *)(&(file->size)));
94 die("Cannot read blob %s for path %s",
95 sha1_to_hex(o->blob_sha1),
104 * Origin is refcounted and usually we keep the blob contents to be
107 static inline struct origin *origin_incref(struct origin *o)
114 static void origin_decref(struct origin *o)
116 if (o && --o->refcnt <= 0) {
122 static void drop_origin_blob(struct origin *o)
131 * Each group of lines is described by a blame_entry; it can be split
132 * as we pass blame to the parents. They form a linked list in the
133 * scoreboard structure, sorted by the target line number.
136 struct blame_entry *prev;
137 struct blame_entry *next;
139 /* the first line of this group in the final image;
140 * internally all line numbers are 0 based.
144 /* how many lines this group has */
147 /* the commit that introduced this group into the final image */
148 struct origin *suspect;
150 /* true if the suspect is truly guilty; false while we have not
151 * checked if the group came from one of its parents.
155 /* true if the entry has been scanned for copies in the current parent
159 /* the line number of the first line of this group in the
160 * suspect's file; internally all line numbers are 0 based.
164 /* how significant this entry is -- cached to avoid
165 * scanning the lines over and over.
171 * The current state of the blame assignment.
174 /* the final commit (i.e. where we started digging from) */
175 struct commit *final;
176 struct rev_info *revs;
180 * The contents in the final image.
181 * Used by many functions to obtain contents of the nth line,
182 * indexed with scoreboard.lineno[blame_entry.lno].
184 const char *final_buf;
185 unsigned long final_buf_size;
187 /* linked list of blames */
188 struct blame_entry *ent;
190 /* look-up a line in the final buffer */
195 static inline int same_suspect(struct origin *a, struct origin *b)
199 if (a->commit != b->commit)
201 return !strcmp(a->path, b->path);
204 static void sanity_check_refcnt(struct scoreboard *);
207 * If two blame entries that are next to each other came from
208 * contiguous lines in the same origin (i.e. <commit, path> pair),
209 * merge them together.
211 static void coalesce(struct scoreboard *sb)
213 struct blame_entry *ent, *next;
215 for (ent = sb->ent; ent && (next = ent->next); ent = next) {
216 if (same_suspect(ent->suspect, next->suspect) &&
217 ent->guilty == next->guilty &&
218 ent->s_lno + ent->num_lines == next->s_lno) {
219 ent->num_lines += next->num_lines;
220 ent->next = next->next;
222 ent->next->prev = ent;
223 origin_decref(next->suspect);
226 next = ent; /* again */
230 if (DEBUG) /* sanity */
231 sanity_check_refcnt(sb);
235 * Given a commit and a path in it, create a new origin structure.
236 * The callers that add blame to the scoreboard should use
237 * get_origin() to obtain shared, refcounted copy instead of calling
238 * this function directly.
240 static struct origin *make_origin(struct commit *commit, const char *path)
243 o = xcalloc(1, sizeof(*o) + strlen(path) + 1);
246 strcpy(o->path, path);
251 * Locate an existing origin or create a new one.
253 static struct origin *get_origin(struct scoreboard *sb,
254 struct commit *commit,
257 struct blame_entry *e;
259 for (e = sb->ent; e; e = e->next) {
260 if (e->suspect->commit == commit &&
261 !strcmp(e->suspect->path, path))
262 return origin_incref(e->suspect);
264 return make_origin(commit, path);
268 * Fill the blob_sha1 field of an origin if it hasn't, so that later
269 * call to fill_origin_blob() can use it to locate the data. blob_sha1
270 * for an origin is also used to pass the blame for the entire file to
271 * the parent to detect the case where a child's blob is identical to
272 * that of its parent's.
274 static int fill_blob_sha1(struct origin *origin)
278 if (!is_null_sha1(origin->blob_sha1))
280 if (get_tree_entry(origin->commit->object.sha1,
282 origin->blob_sha1, &mode))
284 if (sha1_object_info(origin->blob_sha1, NULL) != OBJ_BLOB)
288 hashclr(origin->blob_sha1);
293 * We have an origin -- check if the same path exists in the
294 * parent and return an origin structure to represent it.
296 static struct origin *find_origin(struct scoreboard *sb,
297 struct commit *parent,
298 struct origin *origin)
300 struct origin *porigin = NULL;
301 struct diff_options diff_opts;
302 const char *paths[2];
306 * Each commit object can cache one origin in that
307 * commit. This is a freestanding copy of origin and
310 struct origin *cached = parent->util;
311 if (!strcmp(cached->path, origin->path)) {
313 * The same path between origin and its parent
314 * without renaming -- the most common case.
316 porigin = get_origin(sb, parent, cached->path);
319 * If the origin was newly created (i.e. get_origin
320 * would call make_origin if none is found in the
321 * scoreboard), it does not know the blob_sha1,
322 * so copy it. Otherwise porigin was in the
323 * scoreboard and already knows blob_sha1.
325 if (porigin->refcnt == 1)
326 hashcpy(porigin->blob_sha1, cached->blob_sha1);
329 /* otherwise it was not very useful; free it */
334 /* See if the origin->path is different between parent
335 * and origin first. Most of the time they are the
336 * same and diff-tree is fairly efficient about this.
338 diff_setup(&diff_opts);
339 DIFF_OPT_SET(&diff_opts, RECURSIVE);
340 diff_opts.detect_rename = 0;
341 diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;
342 paths[0] = origin->path;
345 diff_tree_setup_paths(paths, &diff_opts);
346 if (diff_setup_done(&diff_opts) < 0)
349 if (is_null_sha1(origin->commit->object.sha1))
350 do_diff_cache(parent->tree->object.sha1, &diff_opts);
352 diff_tree_sha1(parent->tree->object.sha1,
353 origin->commit->tree->object.sha1,
355 diffcore_std(&diff_opts);
357 /* It is either one entry that says "modified", or "created",
360 if (!diff_queued_diff.nr) {
361 /* The path is the same as parent */
362 porigin = get_origin(sb, parent, origin->path);
363 hashcpy(porigin->blob_sha1, origin->blob_sha1);
365 else if (diff_queued_diff.nr != 1)
366 die("internal error in blame::find_origin");
368 struct diff_filepair *p = diff_queued_diff.queue[0];
371 die("internal error in blame::find_origin (%c)",
374 porigin = get_origin(sb, parent, origin->path);
375 hashcpy(porigin->blob_sha1, p->one->sha1);
379 /* Did not exist in parent, or type changed */
383 diff_flush(&diff_opts);
384 diff_tree_release_paths(&diff_opts);
387 * Create a freestanding copy that is not part of
388 * the refcounted origin found in the scoreboard, and
389 * cache it in the commit.
391 struct origin *cached;
393 cached = make_origin(porigin->commit, porigin->path);
394 hashcpy(cached->blob_sha1, porigin->blob_sha1);
395 parent->util = cached;
401 * We have an origin -- find the path that corresponds to it in its
402 * parent and return an origin structure to represent it.
404 static struct origin *find_rename(struct scoreboard *sb,
405 struct commit *parent,
406 struct origin *origin)
408 struct origin *porigin = NULL;
409 struct diff_options diff_opts;
411 const char *paths[2];
413 diff_setup(&diff_opts);
414 DIFF_OPT_SET(&diff_opts, RECURSIVE);
415 diff_opts.detect_rename = DIFF_DETECT_RENAME;
416 diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;
417 diff_opts.single_follow = origin->path;
419 diff_tree_setup_paths(paths, &diff_opts);
420 if (diff_setup_done(&diff_opts) < 0)
423 if (is_null_sha1(origin->commit->object.sha1))
424 do_diff_cache(parent->tree->object.sha1, &diff_opts);
426 diff_tree_sha1(parent->tree->object.sha1,
427 origin->commit->tree->object.sha1,
429 diffcore_std(&diff_opts);
431 for (i = 0; i < diff_queued_diff.nr; i++) {
432 struct diff_filepair *p = diff_queued_diff.queue[i];
433 if ((p->status == 'R' || p->status == 'C') &&
434 !strcmp(p->two->path, origin->path)) {
435 porigin = get_origin(sb, parent, p->one->path);
436 hashcpy(porigin->blob_sha1, p->one->sha1);
440 diff_flush(&diff_opts);
441 diff_tree_release_paths(&diff_opts);
446 * Link in a new blame entry to the scoreboard. Entries that cover the
447 * same line range have been removed from the scoreboard previously.
449 static void add_blame_entry(struct scoreboard *sb, struct blame_entry *e)
451 struct blame_entry *ent, *prev = NULL;
453 origin_incref(e->suspect);
455 for (ent = sb->ent; ent && ent->lno < e->lno; ent = ent->next)
458 /* prev, if not NULL, is the last one that is below e */
461 e->next = prev->next;
473 * src typically is on-stack; we want to copy the information in it to
474 * a malloced blame_entry that is already on the linked list of the
475 * scoreboard. The origin of dst loses a refcnt while the origin of src
478 static void dup_entry(struct blame_entry *dst, struct blame_entry *src)
480 struct blame_entry *p, *n;
484 origin_incref(src->suspect);
485 origin_decref(dst->suspect);
486 memcpy(dst, src, sizeof(*src));
492 static const char *nth_line(struct scoreboard *sb, int lno)
494 return sb->final_buf + sb->lineno[lno];
498 * It is known that lines between tlno to same came from parent, and e
499 * has an overlap with that range. it also is known that parent's
500 * line plno corresponds to e's line tlno.
506 * <------------------>
508 * Split e into potentially three parts; before this chunk, the chunk
509 * to be blamed for the parent, and after that portion.
511 static void split_overlap(struct blame_entry *split,
512 struct blame_entry *e,
513 int tlno, int plno, int same,
514 struct origin *parent)
517 memset(split, 0, sizeof(struct blame_entry [3]));
519 if (e->s_lno < tlno) {
520 /* there is a pre-chunk part not blamed on parent */
521 split[0].suspect = origin_incref(e->suspect);
522 split[0].lno = e->lno;
523 split[0].s_lno = e->s_lno;
524 split[0].num_lines = tlno - e->s_lno;
525 split[1].lno = e->lno + tlno - e->s_lno;
526 split[1].s_lno = plno;
529 split[1].lno = e->lno;
530 split[1].s_lno = plno + (e->s_lno - tlno);
533 if (same < e->s_lno + e->num_lines) {
534 /* there is a post-chunk part not blamed on parent */
535 split[2].suspect = origin_incref(e->suspect);
536 split[2].lno = e->lno + (same - e->s_lno);
537 split[2].s_lno = e->s_lno + (same - e->s_lno);
538 split[2].num_lines = e->s_lno + e->num_lines - same;
539 chunk_end_lno = split[2].lno;
542 chunk_end_lno = e->lno + e->num_lines;
543 split[1].num_lines = chunk_end_lno - split[1].lno;
546 * if it turns out there is nothing to blame the parent for,
547 * forget about the splitting. !split[1].suspect signals this.
549 if (split[1].num_lines < 1)
551 split[1].suspect = origin_incref(parent);
555 * split_overlap() divided an existing blame e into up to three parts
556 * in split. Adjust the linked list of blames in the scoreboard to
559 static void split_blame(struct scoreboard *sb,
560 struct blame_entry *split,
561 struct blame_entry *e)
563 struct blame_entry *new_entry;
565 if (split[0].suspect && split[2].suspect) {
566 /* The first part (reuse storage for the existing entry e) */
567 dup_entry(e, &split[0]);
569 /* The last part -- me */
570 new_entry = xmalloc(sizeof(*new_entry));
571 memcpy(new_entry, &(split[2]), sizeof(struct blame_entry));
572 add_blame_entry(sb, new_entry);
574 /* ... and the middle part -- parent */
575 new_entry = xmalloc(sizeof(*new_entry));
576 memcpy(new_entry, &(split[1]), sizeof(struct blame_entry));
577 add_blame_entry(sb, new_entry);
579 else if (!split[0].suspect && !split[2].suspect)
581 * The parent covers the entire area; reuse storage for
582 * e and replace it with the parent.
584 dup_entry(e, &split[1]);
585 else if (split[0].suspect) {
586 /* me and then parent */
587 dup_entry(e, &split[0]);
589 new_entry = xmalloc(sizeof(*new_entry));
590 memcpy(new_entry, &(split[1]), sizeof(struct blame_entry));
591 add_blame_entry(sb, new_entry);
594 /* parent and then me */
595 dup_entry(e, &split[1]);
597 new_entry = xmalloc(sizeof(*new_entry));
598 memcpy(new_entry, &(split[2]), sizeof(struct blame_entry));
599 add_blame_entry(sb, new_entry);
602 if (DEBUG) { /* sanity */
603 struct blame_entry *ent;
604 int lno = sb->ent->lno, corrupt = 0;
606 for (ent = sb->ent; ent; ent = ent->next) {
611 lno += ent->num_lines;
615 for (ent = sb->ent; ent; ent = ent->next) {
616 printf("L %8d l %8d n %8d\n",
617 lno, ent->lno, ent->num_lines);
618 lno = ent->lno + ent->num_lines;
626 * After splitting the blame, the origins used by the
627 * on-stack blame_entry should lose one refcnt each.
629 static void decref_split(struct blame_entry *split)
633 for (i = 0; i < 3; i++)
634 origin_decref(split[i].suspect);
638 * Helper for blame_chunk(). blame_entry e is known to overlap with
639 * the patch hunk; split it and pass blame to the parent.
641 static void blame_overlap(struct scoreboard *sb, struct blame_entry *e,
642 int tlno, int plno, int same,
643 struct origin *parent)
645 struct blame_entry split[3];
647 split_overlap(split, e, tlno, plno, same, parent);
648 if (split[1].suspect)
649 split_blame(sb, split, e);
654 * Find the line number of the last line the target is suspected for.
656 static int find_last_in_target(struct scoreboard *sb, struct origin *target)
658 struct blame_entry *e;
659 int last_in_target = -1;
661 for (e = sb->ent; e; e = e->next) {
662 if (e->guilty || !same_suspect(e->suspect, target))
664 if (last_in_target < e->s_lno + e->num_lines)
665 last_in_target = e->s_lno + e->num_lines;
667 return last_in_target;
671 * Process one hunk from the patch between the current suspect for
672 * blame_entry e and its parent. Find and split the overlap, and
673 * pass blame to the overlapping part to the parent.
675 static void blame_chunk(struct scoreboard *sb,
676 int tlno, int plno, int same,
677 struct origin *target, struct origin *parent)
679 struct blame_entry *e;
681 for (e = sb->ent; e; e = e->next) {
682 if (e->guilty || !same_suspect(e->suspect, target))
684 if (same <= e->s_lno)
686 if (tlno < e->s_lno + e->num_lines)
687 blame_overlap(sb, e, tlno, plno, same, parent);
691 struct blame_chunk_cb_data {
692 struct scoreboard *sb;
693 struct origin *target;
694 struct origin *parent;
699 static void blame_chunk_cb(void *data, long same, long p_next, long t_next)
701 struct blame_chunk_cb_data *d = data;
702 blame_chunk(d->sb, d->tlno, d->plno, same, d->target, d->parent);
708 * We are looking at the origin 'target' and aiming to pass blame
709 * for the lines it is suspected to its parent. Run diff to find
710 * which lines came from parent and pass blame for them.
712 static int pass_blame_to_parent(struct scoreboard *sb,
713 struct origin *target,
714 struct origin *parent)
717 mmfile_t file_p, file_o;
718 struct blame_chunk_cb_data d = { sb, target, parent, 0, 0 };
722 last_in_target = find_last_in_target(sb, target);
723 if (last_in_target < 0)
724 return 1; /* nothing remains for this target */
726 fill_origin_blob(parent, &file_p);
727 fill_origin_blob(target, &file_o);
730 memset(&xpp, 0, sizeof(xpp));
731 xpp.flags = xdl_opts;
732 memset(&xecfg, 0, sizeof(xecfg));
734 xdi_diff_hunks(&file_p, &file_o, blame_chunk_cb, &d, &xpp, &xecfg);
735 /* The rest (i.e. anything after tlno) are the same as the parent */
736 blame_chunk(sb, d.tlno, d.plno, last_in_target, target, parent);
742 * The lines in blame_entry after splitting blames many times can become
743 * very small and trivial, and at some point it becomes pointless to
744 * blame the parents. E.g. "\t\t}\n\t}\n\n" appears everywhere in any
745 * ordinary C program, and it is not worth to say it was copied from
746 * totally unrelated file in the parent.
748 * Compute how trivial the lines in the blame_entry are.
750 static unsigned ent_score(struct scoreboard *sb, struct blame_entry *e)
759 cp = nth_line(sb, e->lno);
760 ep = nth_line(sb, e->lno + e->num_lines);
762 unsigned ch = *((unsigned char *)cp);
772 * best_so_far[] and this[] are both a split of an existing blame_entry
773 * that passes blame to the parent. Maintain best_so_far the best split
774 * so far, by comparing this and best_so_far and copying this into
775 * bst_so_far as needed.
777 static void copy_split_if_better(struct scoreboard *sb,
778 struct blame_entry *best_so_far,
779 struct blame_entry *this)
783 if (!this[1].suspect)
785 if (best_so_far[1].suspect) {
786 if (ent_score(sb, &this[1]) < ent_score(sb, &best_so_far[1]))
790 for (i = 0; i < 3; i++)
791 origin_incref(this[i].suspect);
792 decref_split(best_so_far);
793 memcpy(best_so_far, this, sizeof(struct blame_entry [3]));
797 * We are looking at a part of the final image represented by
798 * ent (tlno and same are offset by ent->s_lno).
799 * tlno is where we are looking at in the final image.
800 * up to (but not including) same match preimage.
801 * plno is where we are looking at in the preimage.
803 * <-------------- final image ---------------------->
806 * <---------preimage----->
809 * All line numbers are 0-based.
811 static void handle_split(struct scoreboard *sb,
812 struct blame_entry *ent,
813 int tlno, int plno, int same,
814 struct origin *parent,
815 struct blame_entry *split)
817 if (ent->num_lines <= tlno)
820 struct blame_entry this[3];
823 split_overlap(this, ent, tlno, plno, same, parent);
824 copy_split_if_better(sb, split, this);
829 struct handle_split_cb_data {
830 struct scoreboard *sb;
831 struct blame_entry *ent;
832 struct origin *parent;
833 struct blame_entry *split;
838 static void handle_split_cb(void *data, long same, long p_next, long t_next)
840 struct handle_split_cb_data *d = data;
841 handle_split(d->sb, d->ent, d->tlno, d->plno, same, d->parent, d->split);
847 * Find the lines from parent that are the same as ent so that
848 * we can pass blames to it. file_p has the blob contents for
851 static void find_copy_in_blob(struct scoreboard *sb,
852 struct blame_entry *ent,
853 struct origin *parent,
854 struct blame_entry *split,
860 struct handle_split_cb_data d = { sb, ent, parent, split, 0, 0 };
865 * Prepare mmfile that contains only the lines in ent.
867 cp = nth_line(sb, ent->lno);
868 file_o.ptr = (char*) cp;
869 cnt = ent->num_lines;
871 while (cnt && cp < sb->final_buf + sb->final_buf_size) {
875 file_o.size = cp - file_o.ptr;
878 * file_o is a part of final image we are annotating.
879 * file_p partially may match that image.
881 memset(&xpp, 0, sizeof(xpp));
882 xpp.flags = xdl_opts;
883 memset(&xecfg, 0, sizeof(xecfg));
885 memset(split, 0, sizeof(struct blame_entry [3]));
886 xdi_diff_hunks(file_p, &file_o, handle_split_cb, &d, &xpp, &xecfg);
887 /* remainder, if any, all match the preimage */
888 handle_split(sb, ent, d.tlno, d.plno, ent->num_lines, parent, split);
892 * See if lines currently target is suspected for can be attributed to
895 static int find_move_in_parent(struct scoreboard *sb,
896 struct origin *target,
897 struct origin *parent)
899 int last_in_target, made_progress;
900 struct blame_entry *e, split[3];
903 last_in_target = find_last_in_target(sb, target);
904 if (last_in_target < 0)
905 return 1; /* nothing remains for this target */
907 fill_origin_blob(parent, &file_p);
912 while (made_progress) {
914 for (e = sb->ent; e; e = e->next) {
915 if (e->guilty || !same_suspect(e->suspect, target) ||
916 ent_score(sb, e) < blame_move_score)
918 find_copy_in_blob(sb, e, parent, split, &file_p);
919 if (split[1].suspect &&
920 blame_move_score < ent_score(sb, &split[1])) {
921 split_blame(sb, split, e);
931 struct blame_entry *ent;
932 struct blame_entry split[3];
936 * Count the number of entries the target is suspected for,
937 * and prepare a list of entry and the best split.
939 static struct blame_list *setup_blame_list(struct scoreboard *sb,
940 struct origin *target,
944 struct blame_entry *e;
946 struct blame_list *blame_list = NULL;
948 for (e = sb->ent, num_ents = 0; e; e = e->next)
949 if (!e->scanned && !e->guilty &&
950 same_suspect(e->suspect, target) &&
951 min_score < ent_score(sb, e))
954 blame_list = xcalloc(num_ents, sizeof(struct blame_list));
955 for (e = sb->ent, i = 0; e; e = e->next)
956 if (!e->scanned && !e->guilty &&
957 same_suspect(e->suspect, target) &&
958 min_score < ent_score(sb, e))
959 blame_list[i++].ent = e;
961 *num_ents_p = num_ents;
966 * Reset the scanned status on all entries.
968 static void reset_scanned_flag(struct scoreboard *sb)
970 struct blame_entry *e;
971 for (e = sb->ent; e; e = e->next)
976 * For lines target is suspected for, see if we can find code movement
977 * across file boundary from the parent commit. porigin is the path
978 * in the parent we already tried.
980 static int find_copy_in_parent(struct scoreboard *sb,
981 struct origin *target,
982 struct commit *parent,
983 struct origin *porigin,
986 struct diff_options diff_opts;
987 const char *paths[1];
990 struct blame_list *blame_list;
993 blame_list = setup_blame_list(sb, target, blame_copy_score, &num_ents);
995 return 1; /* nothing remains for this target */
997 diff_setup(&diff_opts);
998 DIFF_OPT_SET(&diff_opts, RECURSIVE);
999 diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;
1002 diff_tree_setup_paths(paths, &diff_opts);
1003 if (diff_setup_done(&diff_opts) < 0)
1006 /* Try "find copies harder" on new path if requested;
1007 * we do not want to use diffcore_rename() actually to
1008 * match things up; find_copies_harder is set only to
1009 * force diff_tree_sha1() to feed all filepairs to diff_queue,
1010 * and this code needs to be after diff_setup_done(), which
1011 * usually makes find-copies-harder imply copy detection.
1013 if ((opt & PICKAXE_BLAME_COPY_HARDEST)
1014 || ((opt & PICKAXE_BLAME_COPY_HARDER)
1015 && (!porigin || strcmp(target->path, porigin->path))))
1016 DIFF_OPT_SET(&diff_opts, FIND_COPIES_HARDER);
1018 if (is_null_sha1(target->commit->object.sha1))
1019 do_diff_cache(parent->tree->object.sha1, &diff_opts);
1021 diff_tree_sha1(parent->tree->object.sha1,
1022 target->commit->tree->object.sha1,
1025 if (!DIFF_OPT_TST(&diff_opts, FIND_COPIES_HARDER))
1026 diffcore_std(&diff_opts);
1030 int made_progress = 0;
1032 for (i = 0; i < diff_queued_diff.nr; i++) {
1033 struct diff_filepair *p = diff_queued_diff.queue[i];
1034 struct origin *norigin;
1036 struct blame_entry this[3];
1038 if (!DIFF_FILE_VALID(p->one))
1039 continue; /* does not exist in parent */
1040 if (S_ISGITLINK(p->one->mode))
1041 continue; /* ignore git links */
1042 if (porigin && !strcmp(p->one->path, porigin->path))
1043 /* find_move already dealt with this path */
1046 norigin = get_origin(sb, parent, p->one->path);
1047 hashcpy(norigin->blob_sha1, p->one->sha1);
1048 fill_origin_blob(norigin, &file_p);
1052 for (j = 0; j < num_ents; j++) {
1053 find_copy_in_blob(sb, blame_list[j].ent,
1054 norigin, this, &file_p);
1055 copy_split_if_better(sb, blame_list[j].split,
1059 origin_decref(norigin);
1062 for (j = 0; j < num_ents; j++) {
1063 struct blame_entry *split = blame_list[j].split;
1064 if (split[1].suspect &&
1065 blame_copy_score < ent_score(sb, &split[1])) {
1066 split_blame(sb, split, blame_list[j].ent);
1070 blame_list[j].ent->scanned = 1;
1071 decref_split(split);
1077 blame_list = setup_blame_list(sb, target, blame_copy_score, &num_ents);
1083 reset_scanned_flag(sb);
1084 diff_flush(&diff_opts);
1085 diff_tree_release_paths(&diff_opts);
1090 * The blobs of origin and porigin exactly match, so everything
1091 * origin is suspected for can be blamed on the parent.
1093 static void pass_whole_blame(struct scoreboard *sb,
1094 struct origin *origin, struct origin *porigin)
1096 struct blame_entry *e;
1098 if (!porigin->file.ptr && origin->file.ptr) {
1099 /* Steal its file */
1100 porigin->file = origin->file;
1101 origin->file.ptr = NULL;
1103 for (e = sb->ent; e; e = e->next) {
1104 if (!same_suspect(e->suspect, origin))
1106 origin_incref(porigin);
1107 origin_decref(e->suspect);
1108 e->suspect = porigin;
1113 * We pass blame from the current commit to its parents. We keep saying
1114 * "parent" (and "porigin"), but what we mean is to find scapegoat to
1115 * exonerate ourselves.
1117 static struct commit_list *first_scapegoat(struct rev_info *revs, struct commit *commit)
1120 return commit->parents;
1121 return lookup_decoration(&revs->children, &commit->object);
1124 static int num_scapegoats(struct rev_info *revs, struct commit *commit)
1127 struct commit_list *l = first_scapegoat(revs, commit);
1128 for (cnt = 0; l; l = l->next)
1135 static void pass_blame(struct scoreboard *sb, struct origin *origin, int opt)
1137 struct rev_info *revs = sb->revs;
1138 int i, pass, num_sg;
1139 struct commit *commit = origin->commit;
1140 struct commit_list *sg;
1141 struct origin *sg_buf[MAXSG];
1142 struct origin *porigin, **sg_origin = sg_buf;
1144 num_sg = num_scapegoats(revs, commit);
1147 else if (num_sg < ARRAY_SIZE(sg_buf))
1148 memset(sg_buf, 0, sizeof(sg_buf));
1150 sg_origin = xcalloc(num_sg, sizeof(*sg_origin));
1153 * The first pass looks for unrenamed path to optimize for
1154 * common cases, then we look for renames in the second pass.
1156 for (pass = 0; pass < 2; pass++) {
1157 struct origin *(*find)(struct scoreboard *,
1158 struct commit *, struct origin *);
1159 find = pass ? find_rename : find_origin;
1161 for (i = 0, sg = first_scapegoat(revs, commit);
1163 sg = sg->next, i++) {
1164 struct commit *p = sg->item;
1169 if (parse_commit(p))
1171 porigin = find(sb, p, origin);
1174 if (!hashcmp(porigin->blob_sha1, origin->blob_sha1)) {
1175 pass_whole_blame(sb, origin, porigin);
1176 origin_decref(porigin);
1179 for (j = same = 0; j < i; j++)
1181 !hashcmp(sg_origin[j]->blob_sha1,
1182 porigin->blob_sha1)) {
1187 sg_origin[i] = porigin;
1189 origin_decref(porigin);
1194 for (i = 0, sg = first_scapegoat(revs, commit);
1196 sg = sg->next, i++) {
1197 struct origin *porigin = sg_origin[i];
1200 if (pass_blame_to_parent(sb, origin, porigin))
1205 * Optionally find moves in parents' files.
1207 if (opt & PICKAXE_BLAME_MOVE)
1208 for (i = 0, sg = first_scapegoat(revs, commit);
1210 sg = sg->next, i++) {
1211 struct origin *porigin = sg_origin[i];
1214 if (find_move_in_parent(sb, origin, porigin))
1219 * Optionally find copies from parents' files.
1221 if (opt & PICKAXE_BLAME_COPY)
1222 for (i = 0, sg = first_scapegoat(revs, commit);
1224 sg = sg->next, i++) {
1225 struct origin *porigin = sg_origin[i];
1226 if (find_copy_in_parent(sb, origin, sg->item,
1232 for (i = 0; i < num_sg; i++) {
1234 drop_origin_blob(sg_origin[i]);
1235 origin_decref(sg_origin[i]);
1238 drop_origin_blob(origin);
1239 if (sg_buf != sg_origin)
1244 * Information on commits, used for output.
1249 const char *author_mail;
1250 unsigned long author_time;
1251 const char *author_tz;
1253 /* filled only when asked for details */
1254 const char *committer;
1255 const char *committer_mail;
1256 unsigned long committer_time;
1257 const char *committer_tz;
1259 const char *summary;
1263 * Parse author/committer line in the commit object buffer
1265 static void get_ac_line(const char *inbuf, const char *what,
1266 int bufsz, char *person, const char **mail,
1267 unsigned long *time, const char **tz)
1269 int len, tzlen, maillen;
1270 char *tmp, *endp, *timepos;
1272 tmp = strstr(inbuf, what);
1275 tmp += strlen(what);
1276 endp = strchr(tmp, '\n');
1284 *mail = *tz = "(unknown)";
1288 memcpy(person, tmp, len);
1296 tzlen = (person+len)-(tmp+1);
1301 *time = strtoul(tmp, NULL, 10);
1309 maillen = timepos - tmp;
1315 * mailmap expansion may make the name longer.
1316 * make room by pushing stuff down.
1318 tmp = person + bufsz - (tzlen + 1);
1319 memmove(tmp, *tz, tzlen);
1323 tmp = tmp - (maillen + 1);
1324 memmove(tmp, *mail, maillen);
1329 * Now, convert e-mail using mailmap
1331 map_email(&mailmap, tmp + 1, person, tmp-person-1);
1334 static void get_commit_info(struct commit *commit,
1335 struct commit_info *ret,
1339 char *tmp, *endp, *reencoded, *message;
1340 static char author_buf[1024];
1341 static char committer_buf[1024];
1342 static char summary_buf[1024];
1345 * We've operated without save_commit_buffer, so
1346 * we now need to populate them for output.
1348 if (!commit->buffer) {
1349 enum object_type type;
1352 read_sha1_file(commit->object.sha1, &type, &size);
1353 if (!commit->buffer)
1354 die("Cannot read commit %s",
1355 sha1_to_hex(commit->object.sha1));
1357 reencoded = reencode_commit_message(commit, NULL);
1358 message = reencoded ? reencoded : commit->buffer;
1359 ret->author = author_buf;
1360 get_ac_line(message, "\nauthor ",
1361 sizeof(author_buf), author_buf, &ret->author_mail,
1362 &ret->author_time, &ret->author_tz);
1369 ret->committer = committer_buf;
1370 get_ac_line(message, "\ncommitter ",
1371 sizeof(committer_buf), committer_buf, &ret->committer_mail,
1372 &ret->committer_time, &ret->committer_tz);
1374 ret->summary = summary_buf;
1375 tmp = strstr(message, "\n\n");
1378 sprintf(summary_buf, "(%s)", sha1_to_hex(commit->object.sha1));
1383 endp = strchr(tmp, '\n');
1385 endp = tmp + strlen(tmp);
1387 if (len >= sizeof(summary_buf) || len == 0)
1389 memcpy(summary_buf, tmp, len);
1390 summary_buf[len] = 0;
1395 * To allow LF and other nonportable characters in pathnames,
1396 * they are c-style quoted as needed.
1398 static void write_filename_info(const char *path)
1400 printf("filename ");
1401 write_name_quoted(path, stdout, '\n');
1405 * The blame_entry is found to be guilty for the range. Mark it
1406 * as such, and show it in incremental output.
1408 static void found_guilty_entry(struct blame_entry *ent)
1414 struct origin *suspect = ent->suspect;
1416 printf("%s %d %d %d\n",
1417 sha1_to_hex(suspect->commit->object.sha1),
1418 ent->s_lno + 1, ent->lno + 1, ent->num_lines);
1419 if (!(suspect->commit->object.flags & METAINFO_SHOWN)) {
1420 struct commit_info ci;
1421 suspect->commit->object.flags |= METAINFO_SHOWN;
1422 get_commit_info(suspect->commit, &ci, 1);
1423 printf("author %s\n", ci.author);
1424 printf("author-mail %s\n", ci.author_mail);
1425 printf("author-time %lu\n", ci.author_time);
1426 printf("author-tz %s\n", ci.author_tz);
1427 printf("committer %s\n", ci.committer);
1428 printf("committer-mail %s\n", ci.committer_mail);
1429 printf("committer-time %lu\n", ci.committer_time);
1430 printf("committer-tz %s\n", ci.committer_tz);
1431 printf("summary %s\n", ci.summary);
1432 if (suspect->commit->object.flags & UNINTERESTING)
1433 printf("boundary\n");
1435 write_filename_info(suspect->path);
1436 maybe_flush_or_die(stdout, "stdout");
1441 * The main loop -- while the scoreboard has lines whose true origin
1442 * is still unknown, pick one blame_entry, and allow its current
1443 * suspect to pass blames to its parents.
1445 static void assign_blame(struct scoreboard *sb, int opt)
1447 struct rev_info *revs = sb->revs;
1450 struct blame_entry *ent;
1451 struct commit *commit;
1452 struct origin *suspect = NULL;
1454 /* find one suspect to break down */
1455 for (ent = sb->ent; !suspect && ent; ent = ent->next)
1457 suspect = ent->suspect;
1459 return; /* all done */
1462 * We will use this suspect later in the loop,
1463 * so hold onto it in the meantime.
1465 origin_incref(suspect);
1466 commit = suspect->commit;
1467 if (!commit->object.parsed)
1468 parse_commit(commit);
1470 (!(commit->object.flags & UNINTERESTING) &&
1471 !(revs->max_age != -1 && commit->date < revs->max_age)))
1472 pass_blame(sb, suspect, opt);
1474 commit->object.flags |= UNINTERESTING;
1475 if (commit->object.parsed)
1476 mark_parents_uninteresting(commit);
1478 /* treat root commit as boundary */
1479 if (!commit->parents && !show_root)
1480 commit->object.flags |= UNINTERESTING;
1482 /* Take responsibility for the remaining entries */
1483 for (ent = sb->ent; ent; ent = ent->next)
1484 if (same_suspect(ent->suspect, suspect))
1485 found_guilty_entry(ent);
1486 origin_decref(suspect);
1488 if (DEBUG) /* sanity */
1489 sanity_check_refcnt(sb);
1493 static const char *format_time(unsigned long time, const char *tz_str,
1496 static char time_buf[128];
1501 if (show_raw_time) {
1502 sprintf(time_buf, "%lu %s", time, tz_str);
1507 minutes = tz < 0 ? -tz : tz;
1508 minutes = (minutes / 100)*60 + (minutes % 100);
1509 minutes = tz < 0 ? -minutes : minutes;
1510 t = time + minutes * 60;
1513 strftime(time_buf, sizeof(time_buf), "%Y-%m-%d %H:%M:%S ", tm);
1514 strcat(time_buf, tz_str);
1518 #define OUTPUT_ANNOTATE_COMPAT 001
1519 #define OUTPUT_LONG_OBJECT_NAME 002
1520 #define OUTPUT_RAW_TIMESTAMP 004
1521 #define OUTPUT_PORCELAIN 010
1522 #define OUTPUT_SHOW_NAME 020
1523 #define OUTPUT_SHOW_NUMBER 040
1524 #define OUTPUT_SHOW_SCORE 0100
1525 #define OUTPUT_NO_AUTHOR 0200
1527 static void emit_porcelain(struct scoreboard *sb, struct blame_entry *ent)
1531 struct origin *suspect = ent->suspect;
1534 strcpy(hex, sha1_to_hex(suspect->commit->object.sha1));
1535 printf("%s%c%d %d %d\n",
1537 ent->guilty ? ' ' : '*', // purely for debugging
1541 if (!(suspect->commit->object.flags & METAINFO_SHOWN)) {
1542 struct commit_info ci;
1543 suspect->commit->object.flags |= METAINFO_SHOWN;
1544 get_commit_info(suspect->commit, &ci, 1);
1545 printf("author %s\n", ci.author);
1546 printf("author-mail %s\n", ci.author_mail);
1547 printf("author-time %lu\n", ci.author_time);
1548 printf("author-tz %s\n", ci.author_tz);
1549 printf("committer %s\n", ci.committer);
1550 printf("committer-mail %s\n", ci.committer_mail);
1551 printf("committer-time %lu\n", ci.committer_time);
1552 printf("committer-tz %s\n", ci.committer_tz);
1553 write_filename_info(suspect->path);
1554 printf("summary %s\n", ci.summary);
1555 if (suspect->commit->object.flags & UNINTERESTING)
1556 printf("boundary\n");
1558 else if (suspect->commit->object.flags & MORE_THAN_ONE_PATH)
1559 write_filename_info(suspect->path);
1561 cp = nth_line(sb, ent->lno);
1562 for (cnt = 0; cnt < ent->num_lines; cnt++) {
1565 printf("%s %d %d\n", hex,
1566 ent->s_lno + 1 + cnt,
1567 ent->lno + 1 + cnt);
1572 } while (ch != '\n' &&
1573 cp < sb->final_buf + sb->final_buf_size);
1577 static void emit_other(struct scoreboard *sb, struct blame_entry *ent, int opt)
1581 struct origin *suspect = ent->suspect;
1582 struct commit_info ci;
1584 int show_raw_time = !!(opt & OUTPUT_RAW_TIMESTAMP);
1586 get_commit_info(suspect->commit, &ci, 1);
1587 strcpy(hex, sha1_to_hex(suspect->commit->object.sha1));
1589 cp = nth_line(sb, ent->lno);
1590 for (cnt = 0; cnt < ent->num_lines; cnt++) {
1592 int length = (opt & OUTPUT_LONG_OBJECT_NAME) ? 40 : 8;
1594 if (suspect->commit->object.flags & UNINTERESTING) {
1596 memset(hex, ' ', length);
1597 else if (!(opt & OUTPUT_ANNOTATE_COMPAT)) {
1603 printf("%.*s", length, hex);
1604 if (opt & OUTPUT_ANNOTATE_COMPAT)
1605 printf("\t(%10s\t%10s\t%d)", ci.author,
1606 format_time(ci.author_time, ci.author_tz,
1608 ent->lno + 1 + cnt);
1610 if (opt & OUTPUT_SHOW_SCORE)
1612 max_score_digits, ent->score,
1613 ent->suspect->refcnt);
1614 if (opt & OUTPUT_SHOW_NAME)
1615 printf(" %-*.*s", longest_file, longest_file,
1617 if (opt & OUTPUT_SHOW_NUMBER)
1618 printf(" %*d", max_orig_digits,
1619 ent->s_lno + 1 + cnt);
1621 if (!(opt & OUTPUT_NO_AUTHOR))
1622 printf(" (%-*.*s %10s",
1623 longest_author, longest_author,
1625 format_time(ci.author_time,
1629 max_digits, ent->lno + 1 + cnt);
1634 } while (ch != '\n' &&
1635 cp < sb->final_buf + sb->final_buf_size);
1639 static void output(struct scoreboard *sb, int option)
1641 struct blame_entry *ent;
1643 if (option & OUTPUT_PORCELAIN) {
1644 for (ent = sb->ent; ent; ent = ent->next) {
1645 struct blame_entry *oth;
1646 struct origin *suspect = ent->suspect;
1647 struct commit *commit = suspect->commit;
1648 if (commit->object.flags & MORE_THAN_ONE_PATH)
1650 for (oth = ent->next; oth; oth = oth->next) {
1651 if ((oth->suspect->commit != commit) ||
1652 !strcmp(oth->suspect->path, suspect->path))
1654 commit->object.flags |= MORE_THAN_ONE_PATH;
1660 for (ent = sb->ent; ent; ent = ent->next) {
1661 if (option & OUTPUT_PORCELAIN)
1662 emit_porcelain(sb, ent);
1664 emit_other(sb, ent, option);
1670 * To allow quick access to the contents of nth line in the
1671 * final image, prepare an index in the scoreboard.
1673 static int prepare_lines(struct scoreboard *sb)
1675 const char *buf = sb->final_buf;
1676 unsigned long len = sb->final_buf_size;
1677 int num = 0, incomplete = 0, bol = 1;
1679 if (len && buf[len-1] != '\n')
1680 incomplete++; /* incomplete line at the end */
1683 sb->lineno = xrealloc(sb->lineno,
1684 sizeof(int* ) * (num + 1));
1685 sb->lineno[num] = buf - sb->final_buf;
1688 if (*buf++ == '\n') {
1693 sb->lineno = xrealloc(sb->lineno,
1694 sizeof(int* ) * (num + incomplete + 1));
1695 sb->lineno[num + incomplete] = buf - sb->final_buf;
1696 sb->num_lines = num + incomplete;
1697 return sb->num_lines;
1701 * Add phony grafts for use with -S; this is primarily to
1702 * support git's cvsserver that wants to give a linear history
1705 static int read_ancestry(const char *graft_file)
1707 FILE *fp = fopen(graft_file, "r");
1711 while (fgets(buf, sizeof(buf), fp)) {
1712 /* The format is just "Commit Parent1 Parent2 ...\n" */
1713 int len = strlen(buf);
1714 struct commit_graft *graft = read_graft_line(buf, len);
1716 register_commit_graft(graft, 0);
1723 * How many columns do we need to show line numbers in decimal?
1725 static int lineno_width(int lines)
1729 for (width = 1, i = 10; i <= lines + 1; width++)
1735 * How many columns do we need to show line numbers, authors,
1738 static void find_alignment(struct scoreboard *sb, int *option)
1740 int longest_src_lines = 0;
1741 int longest_dst_lines = 0;
1742 unsigned largest_score = 0;
1743 struct blame_entry *e;
1745 for (e = sb->ent; e; e = e->next) {
1746 struct origin *suspect = e->suspect;
1747 struct commit_info ci;
1750 if (strcmp(suspect->path, sb->path))
1751 *option |= OUTPUT_SHOW_NAME;
1752 num = strlen(suspect->path);
1753 if (longest_file < num)
1755 if (!(suspect->commit->object.flags & METAINFO_SHOWN)) {
1756 suspect->commit->object.flags |= METAINFO_SHOWN;
1757 get_commit_info(suspect->commit, &ci, 1);
1758 num = strlen(ci.author);
1759 if (longest_author < num)
1760 longest_author = num;
1762 num = e->s_lno + e->num_lines;
1763 if (longest_src_lines < num)
1764 longest_src_lines = num;
1765 num = e->lno + e->num_lines;
1766 if (longest_dst_lines < num)
1767 longest_dst_lines = num;
1768 if (largest_score < ent_score(sb, e))
1769 largest_score = ent_score(sb, e);
1771 max_orig_digits = lineno_width(longest_src_lines);
1772 max_digits = lineno_width(longest_dst_lines);
1773 max_score_digits = lineno_width(largest_score);
1777 * For debugging -- origin is refcounted, and this asserts that
1778 * we do not underflow.
1780 static void sanity_check_refcnt(struct scoreboard *sb)
1783 struct blame_entry *ent;
1785 for (ent = sb->ent; ent; ent = ent->next) {
1786 /* Nobody should have zero or negative refcnt */
1787 if (ent->suspect->refcnt <= 0) {
1788 fprintf(stderr, "%s in %s has negative refcnt %d\n",
1790 sha1_to_hex(ent->suspect->commit->object.sha1),
1791 ent->suspect->refcnt);
1795 for (ent = sb->ent; ent; ent = ent->next) {
1796 /* Mark the ones that haven't been checked */
1797 if (0 < ent->suspect->refcnt)
1798 ent->suspect->refcnt = -ent->suspect->refcnt;
1800 for (ent = sb->ent; ent; ent = ent->next) {
1802 * ... then pick each and see if they have the the
1806 struct blame_entry *e;
1807 struct origin *suspect = ent->suspect;
1809 if (0 < suspect->refcnt)
1811 suspect->refcnt = -suspect->refcnt; /* Unmark */
1812 for (found = 0, e = sb->ent; e; e = e->next) {
1813 if (e->suspect != suspect)
1817 if (suspect->refcnt != found) {
1818 fprintf(stderr, "%s in %s has refcnt %d, not %d\n",
1820 sha1_to_hex(ent->suspect->commit->object.sha1),
1821 ent->suspect->refcnt, found);
1827 find_alignment(sb, &opt);
1829 die("Baa %d!", baa);
1834 * Used for the command line parsing; check if the path exists
1835 * in the working tree.
1837 static int has_string_in_work_tree(const char *path)
1840 return !lstat(path, &st);
1843 static unsigned parse_score(const char *arg)
1846 unsigned long score = strtoul(arg, &end, 10);
1852 static const char *add_prefix(const char *prefix, const char *path)
1854 return prefix_path(prefix, prefix ? strlen(prefix) : 0, path);
1858 * Parsing of (comma separated) one item in the -L option
1860 static const char *parse_loc(const char *spec,
1861 struct scoreboard *sb, long lno,
1862 long begin, long *ret)
1869 regmatch_t match[1];
1871 /* Allow "-L <something>,+20" to mean starting at <something>
1872 * for 20 lines, or "-L <something>,-5" for 5 lines ending at
1875 if (1 < begin && (spec[0] == '+' || spec[0] == '-')) {
1876 num = strtol(spec + 1, &term, 10);
1877 if (term != spec + 1) {
1881 *ret = begin + num - 2;
1890 num = strtol(spec, &term, 10);
1898 /* it could be a regexp of form /.../ */
1899 for (term = (char*) spec + 1; *term && *term != '/'; term++) {
1906 /* try [spec+1 .. term-1] as regexp */
1908 begin--; /* input is in human terms */
1909 line = nth_line(sb, begin);
1911 if (!(reg_error = regcomp(®exp, spec + 1, REG_NEWLINE)) &&
1912 !(reg_error = regexec(®exp, line, 1, match, 0))) {
1913 const char *cp = line + match[0].rm_so;
1916 while (begin++ < lno) {
1917 nline = nth_line(sb, begin);
1918 if (line <= cp && cp < nline)
1929 regerror(reg_error, ®exp, errbuf, 1024);
1930 die("-L parameter '%s': %s", spec + 1, errbuf);
1935 * Parsing of -L option
1937 static void prepare_blame_range(struct scoreboard *sb,
1938 const char *bottomtop,
1940 long *bottom, long *top)
1944 term = parse_loc(bottomtop, sb, lno, 1, bottom);
1946 term = parse_loc(term + 1, sb, lno, *bottom + 1, top);
1954 static int git_blame_config(const char *var, const char *value, void *cb)
1956 if (!strcmp(var, "blame.showroot")) {
1957 show_root = git_config_bool(var, value);
1960 if (!strcmp(var, "blame.blankboundary")) {
1961 blank_boundary = git_config_bool(var, value);
1964 return git_default_config(var, value, cb);
1968 * Prepare a dummy commit that represents the work tree (or staged) item.
1969 * Note that annotating work tree item never works in the reverse.
1971 static struct commit *fake_working_tree_commit(const char *path, const char *contents_from)
1973 struct commit *commit;
1974 struct origin *origin;
1975 unsigned char head_sha1[20];
1976 struct strbuf buf = STRBUF_INIT;
1980 struct cache_entry *ce;
1983 if (get_sha1("HEAD", head_sha1))
1984 die("No such ref: HEAD");
1987 commit = xcalloc(1, sizeof(*commit));
1988 commit->parents = xcalloc(1, sizeof(*commit->parents));
1989 commit->parents->item = lookup_commit_reference(head_sha1);
1990 commit->object.parsed = 1;
1992 commit->object.type = OBJ_COMMIT;
1994 origin = make_origin(commit, path);
1996 if (!contents_from || strcmp("-", contents_from)) {
1998 const char *read_from;
1999 unsigned long fin_size;
2001 if (contents_from) {
2002 if (stat(contents_from, &st) < 0)
2003 die("Cannot stat %s", contents_from);
2004 read_from = contents_from;
2007 if (lstat(path, &st) < 0)
2008 die("Cannot lstat %s", path);
2011 fin_size = xsize_t(st.st_size);
2012 mode = canon_mode(st.st_mode);
2013 switch (st.st_mode & S_IFMT) {
2015 if (strbuf_read_file(&buf, read_from, st.st_size) != st.st_size)
2016 die("cannot open or read %s", read_from);
2019 if (readlink(read_from, buf.buf, buf.alloc) != fin_size)
2020 die("cannot readlink %s", read_from);
2024 die("unsupported file type %s", read_from);
2028 /* Reading from stdin */
2029 contents_from = "standard input";
2031 if (strbuf_read(&buf, 0, 0) < 0)
2032 die("read error %s from stdin", strerror(errno));
2034 convert_to_git(path, buf.buf, buf.len, &buf, 0);
2035 origin->file.ptr = buf.buf;
2036 origin->file.size = buf.len;
2037 pretend_sha1_file(buf.buf, buf.len, OBJ_BLOB, origin->blob_sha1);
2038 commit->util = origin;
2041 * Read the current index, replace the path entry with
2042 * origin->blob_sha1 without mucking with its mode or type
2043 * bits; we are not going to write this index out -- we just
2044 * want to run "diff-index --cached".
2051 int pos = cache_name_pos(path, len);
2053 mode = active_cache[pos]->ce_mode;
2055 /* Let's not bother reading from HEAD tree */
2056 mode = S_IFREG | 0644;
2058 size = cache_entry_size(len);
2059 ce = xcalloc(1, size);
2060 hashcpy(ce->sha1, origin->blob_sha1);
2061 memcpy(ce->name, path, len);
2062 ce->ce_flags = create_ce_flags(len, 0);
2063 ce->ce_mode = create_ce_mode(mode);
2064 add_cache_entry(ce, ADD_CACHE_OK_TO_ADD|ADD_CACHE_OK_TO_REPLACE);
2067 * We are not going to write this out, so this does not matter
2068 * right now, but someday we might optimize diff-index --cached
2069 * with cache-tree information.
2071 cache_tree_invalidate_path(active_cache_tree, path);
2073 commit->buffer = xmalloc(400);
2074 ident = fmt_ident("Not Committed Yet", "not.committed.yet", NULL, 0);
2075 snprintf(commit->buffer, 400,
2076 "tree 0000000000000000000000000000000000000000\n"
2080 "Version of %s from %s\n",
2081 sha1_to_hex(head_sha1),
2082 ident, ident, path, contents_from ? contents_from : path);
2086 static const char *prepare_final(struct scoreboard *sb)
2089 const char *final_commit_name = NULL;
2090 struct rev_info *revs = sb->revs;
2093 * There must be one and only one positive commit in the
2094 * revs->pending array.
2096 for (i = 0; i < revs->pending.nr; i++) {
2097 struct object *obj = revs->pending.objects[i].item;
2098 if (obj->flags & UNINTERESTING)
2100 while (obj->type == OBJ_TAG)
2101 obj = deref_tag(obj, NULL, 0);
2102 if (obj->type != OBJ_COMMIT)
2103 die("Non commit %s?", revs->pending.objects[i].name);
2105 die("More than one commit to dig from %s and %s?",
2106 revs->pending.objects[i].name,
2108 sb->final = (struct commit *) obj;
2109 final_commit_name = revs->pending.objects[i].name;
2111 return final_commit_name;
2114 static const char *prepare_initial(struct scoreboard *sb)
2117 const char *final_commit_name = NULL;
2118 struct rev_info *revs = sb->revs;
2121 * There must be one and only one negative commit, and it must be
2124 for (i = 0; i < revs->pending.nr; i++) {
2125 struct object *obj = revs->pending.objects[i].item;
2126 if (!(obj->flags & UNINTERESTING))
2128 while (obj->type == OBJ_TAG)
2129 obj = deref_tag(obj, NULL, 0);
2130 if (obj->type != OBJ_COMMIT)
2131 die("Non commit %s?", revs->pending.objects[i].name);
2133 die("More than one commit to dig down to %s and %s?",
2134 revs->pending.objects[i].name,
2136 sb->final = (struct commit *) obj;
2137 final_commit_name = revs->pending.objects[i].name;
2139 if (!final_commit_name)
2140 die("No commit to dig down to?");
2141 return final_commit_name;
2144 static int blame_copy_callback(const struct option *option, const char *arg, int unset)
2146 int *opt = option->value;
2149 * -C enables copy from removed files;
2150 * -C -C enables copy from existing files, but only
2151 * when blaming a new file;
2152 * -C -C -C enables copy from existing files for
2155 if (*opt & PICKAXE_BLAME_COPY_HARDER)
2156 *opt |= PICKAXE_BLAME_COPY_HARDEST;
2157 if (*opt & PICKAXE_BLAME_COPY)
2158 *opt |= PICKAXE_BLAME_COPY_HARDER;
2159 *opt |= PICKAXE_BLAME_COPY | PICKAXE_BLAME_MOVE;
2162 blame_copy_score = parse_score(arg);
2166 static int blame_move_callback(const struct option *option, const char *arg, int unset)
2168 int *opt = option->value;
2170 *opt |= PICKAXE_BLAME_MOVE;
2173 blame_move_score = parse_score(arg);
2177 static int blame_bottomtop_callback(const struct option *option, const char *arg, int unset)
2179 const char **bottomtop = option->value;
2183 die("More than one '-L n,m' option given");
2188 int cmd_blame(int argc, const char **argv, const char *prefix)
2190 struct rev_info revs;
2192 struct scoreboard sb;
2194 struct blame_entry *ent;
2195 long dashdash_pos, bottom, top, lno;
2196 const char *final_commit_name = NULL;
2197 enum object_type type;
2199 static const char *bottomtop = NULL;
2200 static int output_option = 0, opt = 0;
2201 static int show_stats = 0;
2202 static const char *revs_file = NULL;
2203 static const char *contents_from = NULL;
2204 static const struct option options[] = {
2205 OPT_BOOLEAN(0, "incremental", &incremental, "Show blame entries as we find them, incrementally"),
2206 OPT_BOOLEAN('b', NULL, &blank_boundary, "Show blank SHA-1 for boundary commits (Default: off)"),
2207 OPT_BOOLEAN(0, "root", &show_root, "Do not treat root commits as boundaries (Default: off)"),
2208 OPT_BOOLEAN(0, "show-stats", &show_stats, "Show work cost statistics"),
2209 OPT_BIT(0, "score-debug", &output_option, "Show output score for blame entries", OUTPUT_SHOW_SCORE),
2210 OPT_BIT('f', "show-name", &output_option, "Show original filename (Default: auto)", OUTPUT_SHOW_NAME),
2211 OPT_BIT('n', "show-number", &output_option, "Show original linenumber (Default: off)", OUTPUT_SHOW_NUMBER),
2212 OPT_BIT('p', "porcelain", &output_option, "Show in a format designed for machine consumption", OUTPUT_PORCELAIN),
2213 OPT_BIT('c', NULL, &output_option, "Use the same output mode as git-annotate (Default: off)", OUTPUT_ANNOTATE_COMPAT),
2214 OPT_BIT('t', NULL, &output_option, "Show raw timestamp (Default: off)", OUTPUT_RAW_TIMESTAMP),
2215 OPT_BIT('l', NULL, &output_option, "Show long commit SHA1 (Default: off)", OUTPUT_LONG_OBJECT_NAME),
2216 OPT_BIT('s', NULL, &output_option, "Suppress author name and timestamp (Default: off)", OUTPUT_NO_AUTHOR),
2217 OPT_BIT('w', NULL, &xdl_opts, "Ignore whitespace differences", XDF_IGNORE_WHITESPACE),
2218 OPT_STRING('S', NULL, &revs_file, "file", "Use revisions from <file> instead of calling git-rev-list"),
2219 OPT_STRING(0, "contents", &contents_from, "file", "Use <file>'s contents as the final image"),
2220 { OPTION_CALLBACK, 'C', NULL, &opt, "score", "Find line copies within and across files", PARSE_OPT_OPTARG, blame_copy_callback },
2221 { OPTION_CALLBACK, 'M', NULL, &opt, "score", "Find line movements within and across files", PARSE_OPT_OPTARG, blame_move_callback },
2222 OPT_CALLBACK('L', NULL, &bottomtop, "n,m", "Process only line range n,m, counting from 1", blame_bottomtop_callback),
2226 struct parse_opt_ctx_t ctx;
2227 int cmd_is_annotate = !strcmp(argv[0], "annotate");
2229 git_config(git_blame_config, NULL);
2230 init_revisions(&revs, NULL);
2231 save_commit_buffer = 0;
2234 parse_options_start(&ctx, argc, argv, PARSE_OPT_KEEP_DASHDASH |
2235 PARSE_OPT_KEEP_ARGV0);
2237 switch (parse_options_step(&ctx, options, blame_opt_usage)) {
2238 case PARSE_OPT_HELP:
2240 case PARSE_OPT_DONE:
2242 dashdash_pos = ctx.cpidx;
2246 if (!strcmp(ctx.argv[0], "--reverse")) {
2247 ctx.argv[0] = "--children";
2250 parse_revision_opt(&revs, &ctx, options, blame_opt_usage);
2253 argc = parse_options_end(&ctx);
2255 if (cmd_is_annotate)
2256 output_option |= OUTPUT_ANNOTATE_COMPAT;
2258 if (DIFF_OPT_TST(&revs.diffopt, FIND_COPIES_HARDER))
2259 opt |= (PICKAXE_BLAME_COPY | PICKAXE_BLAME_MOVE |
2260 PICKAXE_BLAME_COPY_HARDER);
2262 if (!blame_move_score)
2263 blame_move_score = BLAME_DEFAULT_MOVE_SCORE;
2264 if (!blame_copy_score)
2265 blame_copy_score = BLAME_DEFAULT_COPY_SCORE;
2268 * We have collected options unknown to us in argv[1..unk]
2269 * which are to be passed to revision machinery if we are
2270 * going to do the "bottom" processing.
2272 * The remaining are:
2274 * (1) if dashdash_pos != 0, its either
2275 * "blame [revisions] -- <path>" or
2276 * "blame -- <path> <rev>"
2278 * (2) otherwise, its one of the two:
2279 * "blame [revisions] <path>"
2280 * "blame <path> <rev>"
2282 * Note that we must strip out <path> from the arguments: we do not
2283 * want the path pruning but we may want "bottom" processing.
2286 switch (argc - dashdash_pos - 1) {
2289 usage_with_options(blame_opt_usage, options);
2290 /* reorder for the new way: <rev> -- <path> */
2296 path = add_prefix(prefix, argv[--argc]);
2300 usage_with_options(blame_opt_usage, options);
2304 usage_with_options(blame_opt_usage, options);
2305 path = add_prefix(prefix, argv[argc - 1]);
2306 if (argc == 3 && !has_string_in_work_tree(path)) { /* (2b) */
2307 path = add_prefix(prefix, argv[1]);
2310 argv[argc - 1] = "--";
2313 if (!has_string_in_work_tree(path))
2314 die("cannot stat path %s: %s", path, strerror(errno));
2317 setup_revisions(argc, argv, &revs, NULL);
2318 memset(&sb, 0, sizeof(sb));
2322 final_commit_name = prepare_final(&sb);
2323 else if (contents_from)
2324 die("--contents and --children do not blend well.");
2326 final_commit_name = prepare_initial(&sb);
2330 * "--not A B -- path" without anything positive;
2331 * do not default to HEAD, but use the working tree
2335 sb.final = fake_working_tree_commit(path, contents_from);
2336 add_pending_object(&revs, &(sb.final->object), ":");
2338 else if (contents_from)
2339 die("Cannot use --contents with final commit object name");
2342 * If we have bottom, this will mark the ancestors of the
2343 * bottom commits we would reach while traversing as
2346 if (prepare_revision_walk(&revs))
2347 die("revision walk setup failed");
2349 if (is_null_sha1(sb.final->object.sha1)) {
2352 buf = xmalloc(o->file.size + 1);
2353 memcpy(buf, o->file.ptr, o->file.size + 1);
2355 sb.final_buf_size = o->file.size;
2358 o = get_origin(&sb, sb.final, path);
2359 if (fill_blob_sha1(o))
2360 die("no such path %s in %s", path, final_commit_name);
2362 sb.final_buf = read_sha1_file(o->blob_sha1, &type,
2363 &sb.final_buf_size);
2365 die("Cannot read blob %s for path %s",
2366 sha1_to_hex(o->blob_sha1),
2370 lno = prepare_lines(&sb);
2374 prepare_blame_range(&sb, bottomtop, lno, &bottom, &top);
2375 if (bottom && top && top < bottom) {
2377 tmp = top; top = bottom; bottom = tmp;
2385 die("file %s has only %lu lines", path, lno);
2387 ent = xcalloc(1, sizeof(*ent));
2389 ent->num_lines = top - bottom;
2391 ent->s_lno = bottom;
2396 if (revs_file && read_ancestry(revs_file))
2397 die("reading graft file %s failed: %s",
2398 revs_file, strerror(errno));
2400 read_mailmap(&mailmap, ".mailmap", NULL);
2405 assign_blame(&sb, opt);
2412 if (!(output_option & OUTPUT_PORCELAIN))
2413 find_alignment(&sb, &output_option);
2415 output(&sb, output_option);
2416 free((void *)sb.final_buf);
2417 for (ent = sb.ent; ent; ) {
2418 struct blame_entry *e = ent->next;
2424 printf("num read blob: %d\n", num_read_blob);
2425 printf("num get patch: %d\n", num_get_patch);
2426 printf("num commits: %d\n", num_commits);