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"
24 static char blame_usage[] = "git blame [options] [rev-opts] [rev] [--] file";
26 static const char *blame_opt_usage[] = {
29 "[rev-opts] are documented in git-rev-list(1)",
33 static int longest_file;
34 static int longest_author;
35 static int max_orig_digits;
36 static int max_digits;
37 static int max_score_digits;
40 static int blank_boundary;
41 static int incremental;
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 * Link in a new blame entry to the scoreboard. Entries that cover the
448 * same line range have been removed from the scoreboard previously.
450 static void add_blame_entry(struct scoreboard *sb, struct blame_entry *e)
452 struct blame_entry *ent, *prev = NULL;
454 origin_incref(e->suspect);
456 for (ent = sb->ent; ent && ent->lno < e->lno; ent = ent->next)
459 /* prev, if not NULL, is the last one that is below e */
462 e->next = prev->next;
474 * src typically is on-stack; we want to copy the information in it to
475 * a malloced blame_entry that is already on the linked list of the
476 * scoreboard. The origin of dst loses a refcnt while the origin of src
479 static void dup_entry(struct blame_entry *dst, struct blame_entry *src)
481 struct blame_entry *p, *n;
485 origin_incref(src->suspect);
486 origin_decref(dst->suspect);
487 memcpy(dst, src, sizeof(*src));
493 static const char *nth_line(struct scoreboard *sb, int lno)
495 return sb->final_buf + sb->lineno[lno];
499 * It is known that lines between tlno to same came from parent, and e
500 * has an overlap with that range. it also is known that parent's
501 * line plno corresponds to e's line tlno.
507 * <------------------>
509 * Split e into potentially three parts; before this chunk, the chunk
510 * to be blamed for the parent, and after that portion.
512 static void split_overlap(struct blame_entry *split,
513 struct blame_entry *e,
514 int tlno, int plno, int same,
515 struct origin *parent)
518 memset(split, 0, sizeof(struct blame_entry [3]));
520 if (e->s_lno < tlno) {
521 /* there is a pre-chunk part not blamed on parent */
522 split[0].suspect = origin_incref(e->suspect);
523 split[0].lno = e->lno;
524 split[0].s_lno = e->s_lno;
525 split[0].num_lines = tlno - e->s_lno;
526 split[1].lno = e->lno + tlno - e->s_lno;
527 split[1].s_lno = plno;
530 split[1].lno = e->lno;
531 split[1].s_lno = plno + (e->s_lno - tlno);
534 if (same < e->s_lno + e->num_lines) {
535 /* there is a post-chunk part not blamed on parent */
536 split[2].suspect = origin_incref(e->suspect);
537 split[2].lno = e->lno + (same - e->s_lno);
538 split[2].s_lno = e->s_lno + (same - e->s_lno);
539 split[2].num_lines = e->s_lno + e->num_lines - same;
540 chunk_end_lno = split[2].lno;
543 chunk_end_lno = e->lno + e->num_lines;
544 split[1].num_lines = chunk_end_lno - split[1].lno;
547 * if it turns out there is nothing to blame the parent for,
548 * forget about the splitting. !split[1].suspect signals this.
550 if (split[1].num_lines < 1)
552 split[1].suspect = origin_incref(parent);
556 * split_overlap() divided an existing blame e into up to three parts
557 * in split. Adjust the linked list of blames in the scoreboard to
560 static void split_blame(struct scoreboard *sb,
561 struct blame_entry *split,
562 struct blame_entry *e)
564 struct blame_entry *new_entry;
566 if (split[0].suspect && split[2].suspect) {
567 /* The first part (reuse storage for the existing entry e) */
568 dup_entry(e, &split[0]);
570 /* The last part -- me */
571 new_entry = xmalloc(sizeof(*new_entry));
572 memcpy(new_entry, &(split[2]), sizeof(struct blame_entry));
573 add_blame_entry(sb, new_entry);
575 /* ... and the middle part -- parent */
576 new_entry = xmalloc(sizeof(*new_entry));
577 memcpy(new_entry, &(split[1]), sizeof(struct blame_entry));
578 add_blame_entry(sb, new_entry);
580 else if (!split[0].suspect && !split[2].suspect)
582 * The parent covers the entire area; reuse storage for
583 * e and replace it with the parent.
585 dup_entry(e, &split[1]);
586 else if (split[0].suspect) {
587 /* me and then parent */
588 dup_entry(e, &split[0]);
590 new_entry = xmalloc(sizeof(*new_entry));
591 memcpy(new_entry, &(split[1]), sizeof(struct blame_entry));
592 add_blame_entry(sb, new_entry);
595 /* parent and then me */
596 dup_entry(e, &split[1]);
598 new_entry = xmalloc(sizeof(*new_entry));
599 memcpy(new_entry, &(split[2]), sizeof(struct blame_entry));
600 add_blame_entry(sb, new_entry);
603 if (DEBUG) { /* sanity */
604 struct blame_entry *ent;
605 int lno = sb->ent->lno, corrupt = 0;
607 for (ent = sb->ent; ent; ent = ent->next) {
612 lno += ent->num_lines;
616 for (ent = sb->ent; ent; ent = ent->next) {
617 printf("L %8d l %8d n %8d\n",
618 lno, ent->lno, ent->num_lines);
619 lno = ent->lno + ent->num_lines;
627 * After splitting the blame, the origins used by the
628 * on-stack blame_entry should lose one refcnt each.
630 static void decref_split(struct blame_entry *split)
634 for (i = 0; i < 3; i++)
635 origin_decref(split[i].suspect);
639 * Helper for blame_chunk(). blame_entry e is known to overlap with
640 * the patch hunk; split it and pass blame to the parent.
642 static void blame_overlap(struct scoreboard *sb, struct blame_entry *e,
643 int tlno, int plno, int same,
644 struct origin *parent)
646 struct blame_entry split[3];
648 split_overlap(split, e, tlno, plno, same, parent);
649 if (split[1].suspect)
650 split_blame(sb, split, e);
655 * Find the line number of the last line the target is suspected for.
657 static int find_last_in_target(struct scoreboard *sb, struct origin *target)
659 struct blame_entry *e;
660 int last_in_target = -1;
662 for (e = sb->ent; e; e = e->next) {
663 if (e->guilty || !same_suspect(e->suspect, target))
665 if (last_in_target < e->s_lno + e->num_lines)
666 last_in_target = e->s_lno + e->num_lines;
668 return last_in_target;
672 * Process one hunk from the patch between the current suspect for
673 * blame_entry e and its parent. Find and split the overlap, and
674 * pass blame to the overlapping part to the parent.
676 static void blame_chunk(struct scoreboard *sb,
677 int tlno, int plno, int same,
678 struct origin *target, struct origin *parent)
680 struct blame_entry *e;
682 for (e = sb->ent; e; e = e->next) {
683 if (e->guilty || !same_suspect(e->suspect, target))
685 if (same <= e->s_lno)
687 if (tlno < e->s_lno + e->num_lines)
688 blame_overlap(sb, e, tlno, plno, same, parent);
692 struct blame_chunk_cb_data {
693 struct scoreboard *sb;
694 struct origin *target;
695 struct origin *parent;
700 static void blame_chunk_cb(void *data, long same, long p_next, long t_next)
702 struct blame_chunk_cb_data *d = data;
703 blame_chunk(d->sb, d->tlno, d->plno, same, d->target, d->parent);
709 * We are looking at the origin 'target' and aiming to pass blame
710 * for the lines it is suspected to its parent. Run diff to find
711 * which lines came from parent and pass blame for them.
713 static int pass_blame_to_parent(struct scoreboard *sb,
714 struct origin *target,
715 struct origin *parent)
718 mmfile_t file_p, file_o;
719 struct blame_chunk_cb_data d = { sb, target, parent, 0, 0 };
723 last_in_target = find_last_in_target(sb, target);
724 if (last_in_target < 0)
725 return 1; /* nothing remains for this target */
727 fill_origin_blob(parent, &file_p);
728 fill_origin_blob(target, &file_o);
731 memset(&xpp, 0, sizeof(xpp));
732 xpp.flags = xdl_opts;
733 memset(&xecfg, 0, sizeof(xecfg));
735 xdi_diff_hunks(&file_p, &file_o, blame_chunk_cb, &d, &xpp, &xecfg);
736 /* The rest (i.e. anything after tlno) are the same as the parent */
737 blame_chunk(sb, d.tlno, d.plno, last_in_target, target, parent);
743 * The lines in blame_entry after splitting blames many times can become
744 * very small and trivial, and at some point it becomes pointless to
745 * blame the parents. E.g. "\t\t}\n\t}\n\n" appears everywhere in any
746 * ordinary C program, and it is not worth to say it was copied from
747 * totally unrelated file in the parent.
749 * Compute how trivial the lines in the blame_entry are.
751 static unsigned ent_score(struct scoreboard *sb, struct blame_entry *e)
760 cp = nth_line(sb, e->lno);
761 ep = nth_line(sb, e->lno + e->num_lines);
763 unsigned ch = *((unsigned char *)cp);
773 * best_so_far[] and this[] are both a split of an existing blame_entry
774 * that passes blame to the parent. Maintain best_so_far the best split
775 * so far, by comparing this and best_so_far and copying this into
776 * bst_so_far as needed.
778 static void copy_split_if_better(struct scoreboard *sb,
779 struct blame_entry *best_so_far,
780 struct blame_entry *this)
784 if (!this[1].suspect)
786 if (best_so_far[1].suspect) {
787 if (ent_score(sb, &this[1]) < ent_score(sb, &best_so_far[1]))
791 for (i = 0; i < 3; i++)
792 origin_incref(this[i].suspect);
793 decref_split(best_so_far);
794 memcpy(best_so_far, this, sizeof(struct blame_entry [3]));
798 * We are looking at a part of the final image represented by
799 * ent (tlno and same are offset by ent->s_lno).
800 * tlno is where we are looking at in the final image.
801 * up to (but not including) same match preimage.
802 * plno is where we are looking at in the preimage.
804 * <-------------- final image ---------------------->
807 * <---------preimage----->
810 * All line numbers are 0-based.
812 static void handle_split(struct scoreboard *sb,
813 struct blame_entry *ent,
814 int tlno, int plno, int same,
815 struct origin *parent,
816 struct blame_entry *split)
818 if (ent->num_lines <= tlno)
821 struct blame_entry this[3];
824 split_overlap(this, ent, tlno, plno, same, parent);
825 copy_split_if_better(sb, split, this);
830 struct handle_split_cb_data {
831 struct scoreboard *sb;
832 struct blame_entry *ent;
833 struct origin *parent;
834 struct blame_entry *split;
839 static void handle_split_cb(void *data, long same, long p_next, long t_next)
841 struct handle_split_cb_data *d = data;
842 handle_split(d->sb, d->ent, d->tlno, d->plno, same, d->parent, d->split);
848 * Find the lines from parent that are the same as ent so that
849 * we can pass blames to it. file_p has the blob contents for
852 static void find_copy_in_blob(struct scoreboard *sb,
853 struct blame_entry *ent,
854 struct origin *parent,
855 struct blame_entry *split,
861 struct handle_split_cb_data d = { sb, ent, parent, split, 0, 0 };
866 * Prepare mmfile that contains only the lines in ent.
868 cp = nth_line(sb, ent->lno);
869 file_o.ptr = (char*) cp;
870 cnt = ent->num_lines;
872 while (cnt && cp < sb->final_buf + sb->final_buf_size) {
876 file_o.size = cp - file_o.ptr;
879 * file_o is a part of final image we are annotating.
880 * file_p partially may match that image.
882 memset(&xpp, 0, sizeof(xpp));
883 xpp.flags = xdl_opts;
884 memset(&xecfg, 0, sizeof(xecfg));
886 memset(split, 0, sizeof(struct blame_entry [3]));
887 xdi_diff_hunks(file_p, &file_o, handle_split_cb, &d, &xpp, &xecfg);
888 /* remainder, if any, all match the preimage */
889 handle_split(sb, ent, d.tlno, d.plno, ent->num_lines, parent, split);
893 * See if lines currently target is suspected for can be attributed to
896 static int find_move_in_parent(struct scoreboard *sb,
897 struct origin *target,
898 struct origin *parent)
900 int last_in_target, made_progress;
901 struct blame_entry *e, split[3];
904 last_in_target = find_last_in_target(sb, target);
905 if (last_in_target < 0)
906 return 1; /* nothing remains for this target */
908 fill_origin_blob(parent, &file_p);
913 while (made_progress) {
915 for (e = sb->ent; e; e = e->next) {
916 if (e->guilty || !same_suspect(e->suspect, target) ||
917 ent_score(sb, e) < blame_move_score)
919 find_copy_in_blob(sb, e, parent, split, &file_p);
920 if (split[1].suspect &&
921 blame_move_score < ent_score(sb, &split[1])) {
922 split_blame(sb, split, e);
932 struct blame_entry *ent;
933 struct blame_entry split[3];
937 * Count the number of entries the target is suspected for,
938 * and prepare a list of entry and the best split.
940 static struct blame_list *setup_blame_list(struct scoreboard *sb,
941 struct origin *target,
945 struct blame_entry *e;
947 struct blame_list *blame_list = NULL;
949 for (e = sb->ent, num_ents = 0; e; e = e->next)
950 if (!e->scanned && !e->guilty &&
951 same_suspect(e->suspect, target) &&
952 min_score < ent_score(sb, e))
955 blame_list = xcalloc(num_ents, sizeof(struct blame_list));
956 for (e = sb->ent, i = 0; e; e = e->next)
957 if (!e->scanned && !e->guilty &&
958 same_suspect(e->suspect, target) &&
959 min_score < ent_score(sb, e))
960 blame_list[i++].ent = e;
962 *num_ents_p = num_ents;
967 * Reset the scanned status on all entries.
969 static void reset_scanned_flag(struct scoreboard *sb)
971 struct blame_entry *e;
972 for (e = sb->ent; e; e = e->next)
977 * For lines target is suspected for, see if we can find code movement
978 * across file boundary from the parent commit. porigin is the path
979 * in the parent we already tried.
981 static int find_copy_in_parent(struct scoreboard *sb,
982 struct origin *target,
983 struct commit *parent,
984 struct origin *porigin,
987 struct diff_options diff_opts;
988 const char *paths[1];
991 struct blame_list *blame_list;
994 blame_list = setup_blame_list(sb, target, blame_copy_score, &num_ents);
996 return 1; /* nothing remains for this target */
998 diff_setup(&diff_opts);
999 DIFF_OPT_SET(&diff_opts, RECURSIVE);
1000 diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;
1003 diff_tree_setup_paths(paths, &diff_opts);
1004 if (diff_setup_done(&diff_opts) < 0)
1007 /* Try "find copies harder" on new path if requested;
1008 * we do not want to use diffcore_rename() actually to
1009 * match things up; find_copies_harder is set only to
1010 * force diff_tree_sha1() to feed all filepairs to diff_queue,
1011 * and this code needs to be after diff_setup_done(), which
1012 * usually makes find-copies-harder imply copy detection.
1014 if ((opt & PICKAXE_BLAME_COPY_HARDEST)
1015 || ((opt & PICKAXE_BLAME_COPY_HARDER)
1016 && (!porigin || strcmp(target->path, porigin->path))))
1017 DIFF_OPT_SET(&diff_opts, FIND_COPIES_HARDER);
1019 if (is_null_sha1(target->commit->object.sha1))
1020 do_diff_cache(parent->tree->object.sha1, &diff_opts);
1022 diff_tree_sha1(parent->tree->object.sha1,
1023 target->commit->tree->object.sha1,
1026 if (!DIFF_OPT_TST(&diff_opts, FIND_COPIES_HARDER))
1027 diffcore_std(&diff_opts);
1031 int made_progress = 0;
1033 for (i = 0; i < diff_queued_diff.nr; i++) {
1034 struct diff_filepair *p = diff_queued_diff.queue[i];
1035 struct origin *norigin;
1037 struct blame_entry this[3];
1039 if (!DIFF_FILE_VALID(p->one))
1040 continue; /* does not exist in parent */
1041 if (S_ISGITLINK(p->one->mode))
1042 continue; /* ignore git links */
1043 if (porigin && !strcmp(p->one->path, porigin->path))
1044 /* find_move already dealt with this path */
1047 norigin = get_origin(sb, parent, p->one->path);
1048 hashcpy(norigin->blob_sha1, p->one->sha1);
1049 fill_origin_blob(norigin, &file_p);
1053 for (j = 0; j < num_ents; j++) {
1054 find_copy_in_blob(sb, blame_list[j].ent,
1055 norigin, this, &file_p);
1056 copy_split_if_better(sb, blame_list[j].split,
1060 origin_decref(norigin);
1063 for (j = 0; j < num_ents; j++) {
1064 struct blame_entry *split = blame_list[j].split;
1065 if (split[1].suspect &&
1066 blame_copy_score < ent_score(sb, &split[1])) {
1067 split_blame(sb, split, blame_list[j].ent);
1071 blame_list[j].ent->scanned = 1;
1072 decref_split(split);
1078 blame_list = setup_blame_list(sb, target, blame_copy_score, &num_ents);
1084 reset_scanned_flag(sb);
1085 diff_flush(&diff_opts);
1086 diff_tree_release_paths(&diff_opts);
1091 * The blobs of origin and porigin exactly match, so everything
1092 * origin is suspected for can be blamed on the parent.
1094 static void pass_whole_blame(struct scoreboard *sb,
1095 struct origin *origin, struct origin *porigin)
1097 struct blame_entry *e;
1099 if (!porigin->file.ptr && origin->file.ptr) {
1100 /* Steal its file */
1101 porigin->file = origin->file;
1102 origin->file.ptr = NULL;
1104 for (e = sb->ent; e; e = e->next) {
1105 if (!same_suspect(e->suspect, origin))
1107 origin_incref(porigin);
1108 origin_decref(e->suspect);
1109 e->suspect = porigin;
1114 * We pass blame from the current commit to its parents. We keep saying
1115 * "parent" (and "porigin"), but what we mean is to find scapegoat to
1116 * exonerate ourselves.
1118 static struct commit_list *first_scapegoat(struct rev_info *revs, struct commit *commit)
1121 return commit->parents;
1122 return lookup_decoration(&revs->children, &commit->object);
1125 static int num_scapegoats(struct rev_info *revs, struct commit *commit)
1128 struct commit_list *l = first_scapegoat(revs, commit);
1129 for (cnt = 0; l; l = l->next)
1136 static void pass_blame(struct scoreboard *sb, struct origin *origin, int opt)
1138 struct rev_info *revs = sb->revs;
1139 int i, pass, num_sg;
1140 struct commit *commit = origin->commit;
1141 struct commit_list *sg;
1142 struct origin *sg_buf[MAXSG];
1143 struct origin *porigin, **sg_origin = sg_buf;
1145 num_sg = num_scapegoats(revs, commit);
1148 else if (num_sg < ARRAY_SIZE(sg_buf))
1149 memset(sg_buf, 0, sizeof(sg_buf));
1151 sg_origin = xcalloc(num_sg, sizeof(*sg_origin));
1154 * The first pass looks for unrenamed path to optimize for
1155 * common cases, then we look for renames in the second pass.
1157 for (pass = 0; pass < 2; pass++) {
1158 struct origin *(*find)(struct scoreboard *,
1159 struct commit *, struct origin *);
1160 find = pass ? find_rename : find_origin;
1162 for (i = 0, sg = first_scapegoat(revs, commit);
1164 sg = sg->next, i++) {
1165 struct commit *p = sg->item;
1170 if (parse_commit(p))
1172 porigin = find(sb, p, origin);
1175 if (!hashcmp(porigin->blob_sha1, origin->blob_sha1)) {
1176 pass_whole_blame(sb, origin, porigin);
1177 origin_decref(porigin);
1180 for (j = same = 0; j < i; j++)
1182 !hashcmp(sg_origin[j]->blob_sha1,
1183 porigin->blob_sha1)) {
1188 sg_origin[i] = porigin;
1190 origin_decref(porigin);
1195 for (i = 0, sg = first_scapegoat(revs, commit);
1197 sg = sg->next, i++) {
1198 struct origin *porigin = sg_origin[i];
1201 if (pass_blame_to_parent(sb, origin, porigin))
1206 * Optionally find moves in parents' files.
1208 if (opt & PICKAXE_BLAME_MOVE)
1209 for (i = 0, sg = first_scapegoat(revs, commit);
1211 sg = sg->next, i++) {
1212 struct origin *porigin = sg_origin[i];
1215 if (find_move_in_parent(sb, origin, porigin))
1220 * Optionally find copies from parents' files.
1222 if (opt & PICKAXE_BLAME_COPY)
1223 for (i = 0, sg = first_scapegoat(revs, commit);
1225 sg = sg->next, i++) {
1226 struct origin *porigin = sg_origin[i];
1227 if (find_copy_in_parent(sb, origin, sg->item,
1233 for (i = 0; i < num_sg; i++) {
1235 drop_origin_blob(sg_origin[i]);
1236 origin_decref(sg_origin[i]);
1239 drop_origin_blob(origin);
1240 if (sg_buf != sg_origin)
1245 * Information on commits, used for output.
1250 const char *author_mail;
1251 unsigned long author_time;
1252 const char *author_tz;
1254 /* filled only when asked for details */
1255 const char *committer;
1256 const char *committer_mail;
1257 unsigned long committer_time;
1258 const char *committer_tz;
1260 const char *summary;
1264 * Parse author/committer line in the commit object buffer
1266 static void get_ac_line(const char *inbuf, const char *what,
1267 int bufsz, char *person, const char **mail,
1268 unsigned long *time, const char **tz)
1270 int len, tzlen, maillen;
1271 char *tmp, *endp, *timepos;
1273 tmp = strstr(inbuf, what);
1276 tmp += strlen(what);
1277 endp = strchr(tmp, '\n');
1285 *mail = *tz = "(unknown)";
1289 memcpy(person, tmp, len);
1297 tzlen = (person+len)-(tmp+1);
1302 *time = strtoul(tmp, NULL, 10);
1310 maillen = timepos - tmp;
1316 * mailmap expansion may make the name longer.
1317 * make room by pushing stuff down.
1319 tmp = person + bufsz - (tzlen + 1);
1320 memmove(tmp, *tz, tzlen);
1324 tmp = tmp - (maillen + 1);
1325 memmove(tmp, *mail, maillen);
1330 * Now, convert e-mail using mailmap
1332 map_email(&mailmap, tmp + 1, person, tmp-person-1);
1335 static void get_commit_info(struct commit *commit,
1336 struct commit_info *ret,
1340 char *tmp, *endp, *reencoded, *message;
1341 static char author_buf[1024];
1342 static char committer_buf[1024];
1343 static char summary_buf[1024];
1346 * We've operated without save_commit_buffer, so
1347 * we now need to populate them for output.
1349 if (!commit->buffer) {
1350 enum object_type type;
1353 read_sha1_file(commit->object.sha1, &type, &size);
1354 if (!commit->buffer)
1355 die("Cannot read commit %s",
1356 sha1_to_hex(commit->object.sha1));
1358 reencoded = reencode_commit_message(commit, NULL);
1359 message = reencoded ? reencoded : commit->buffer;
1360 ret->author = author_buf;
1361 get_ac_line(message, "\nauthor ",
1362 sizeof(author_buf), author_buf, &ret->author_mail,
1363 &ret->author_time, &ret->author_tz);
1370 ret->committer = committer_buf;
1371 get_ac_line(message, "\ncommitter ",
1372 sizeof(committer_buf), committer_buf, &ret->committer_mail,
1373 &ret->committer_time, &ret->committer_tz);
1375 ret->summary = summary_buf;
1376 tmp = strstr(message, "\n\n");
1379 sprintf(summary_buf, "(%s)", sha1_to_hex(commit->object.sha1));
1384 endp = strchr(tmp, '\n');
1386 endp = tmp + strlen(tmp);
1388 if (len >= sizeof(summary_buf) || len == 0)
1390 memcpy(summary_buf, tmp, len);
1391 summary_buf[len] = 0;
1396 * To allow LF and other nonportable characters in pathnames,
1397 * they are c-style quoted as needed.
1399 static void write_filename_info(const char *path)
1401 printf("filename ");
1402 write_name_quoted(path, stdout, '\n');
1406 * The blame_entry is found to be guilty for the range. Mark it
1407 * as such, and show it in incremental output.
1409 static void found_guilty_entry(struct blame_entry *ent)
1415 struct origin *suspect = ent->suspect;
1417 printf("%s %d %d %d\n",
1418 sha1_to_hex(suspect->commit->object.sha1),
1419 ent->s_lno + 1, ent->lno + 1, ent->num_lines);
1420 if (!(suspect->commit->object.flags & METAINFO_SHOWN)) {
1421 struct commit_info ci;
1422 suspect->commit->object.flags |= METAINFO_SHOWN;
1423 get_commit_info(suspect->commit, &ci, 1);
1424 printf("author %s\n", ci.author);
1425 printf("author-mail %s\n", ci.author_mail);
1426 printf("author-time %lu\n", ci.author_time);
1427 printf("author-tz %s\n", ci.author_tz);
1428 printf("committer %s\n", ci.committer);
1429 printf("committer-mail %s\n", ci.committer_mail);
1430 printf("committer-time %lu\n", ci.committer_time);
1431 printf("committer-tz %s\n", ci.committer_tz);
1432 printf("summary %s\n", ci.summary);
1433 if (suspect->commit->object.flags & UNINTERESTING)
1434 printf("boundary\n");
1436 write_filename_info(suspect->path);
1437 maybe_flush_or_die(stdout, "stdout");
1442 * The main loop -- while the scoreboard has lines whose true origin
1443 * is still unknown, pick one blame_entry, and allow its current
1444 * suspect to pass blames to its parents.
1446 static void assign_blame(struct scoreboard *sb, int opt)
1448 struct rev_info *revs = sb->revs;
1451 struct blame_entry *ent;
1452 struct commit *commit;
1453 struct origin *suspect = NULL;
1455 /* find one suspect to break down */
1456 for (ent = sb->ent; !suspect && ent; ent = ent->next)
1458 suspect = ent->suspect;
1460 return; /* all done */
1463 * We will use this suspect later in the loop,
1464 * so hold onto it in the meantime.
1466 origin_incref(suspect);
1467 commit = suspect->commit;
1468 if (!commit->object.parsed)
1469 parse_commit(commit);
1471 (!(commit->object.flags & UNINTERESTING) &&
1472 !(revs->max_age != -1 && commit->date < revs->max_age)))
1473 pass_blame(sb, suspect, opt);
1475 commit->object.flags |= UNINTERESTING;
1476 if (commit->object.parsed)
1477 mark_parents_uninteresting(commit);
1479 /* treat root commit as boundary */
1480 if (!commit->parents && !show_root)
1481 commit->object.flags |= UNINTERESTING;
1483 /* Take responsibility for the remaining entries */
1484 for (ent = sb->ent; ent; ent = ent->next)
1485 if (same_suspect(ent->suspect, suspect))
1486 found_guilty_entry(ent);
1487 origin_decref(suspect);
1489 if (DEBUG) /* sanity */
1490 sanity_check_refcnt(sb);
1494 static const char *format_time(unsigned long time, const char *tz_str,
1497 static char time_buf[128];
1502 if (show_raw_time) {
1503 sprintf(time_buf, "%lu %s", time, tz_str);
1508 minutes = tz < 0 ? -tz : tz;
1509 minutes = (minutes / 100)*60 + (minutes % 100);
1510 minutes = tz < 0 ? -minutes : minutes;
1511 t = time + minutes * 60;
1514 strftime(time_buf, sizeof(time_buf), "%Y-%m-%d %H:%M:%S ", tm);
1515 strcat(time_buf, tz_str);
1519 #define OUTPUT_ANNOTATE_COMPAT 001
1520 #define OUTPUT_LONG_OBJECT_NAME 002
1521 #define OUTPUT_RAW_TIMESTAMP 004
1522 #define OUTPUT_PORCELAIN 010
1523 #define OUTPUT_SHOW_NAME 020
1524 #define OUTPUT_SHOW_NUMBER 040
1525 #define OUTPUT_SHOW_SCORE 0100
1526 #define OUTPUT_NO_AUTHOR 0200
1528 static void emit_porcelain(struct scoreboard *sb, struct blame_entry *ent)
1532 struct origin *suspect = ent->suspect;
1535 strcpy(hex, sha1_to_hex(suspect->commit->object.sha1));
1536 printf("%s%c%d %d %d\n",
1538 ent->guilty ? ' ' : '*', // purely for debugging
1542 if (!(suspect->commit->object.flags & METAINFO_SHOWN)) {
1543 struct commit_info ci;
1544 suspect->commit->object.flags |= METAINFO_SHOWN;
1545 get_commit_info(suspect->commit, &ci, 1);
1546 printf("author %s\n", ci.author);
1547 printf("author-mail %s\n", ci.author_mail);
1548 printf("author-time %lu\n", ci.author_time);
1549 printf("author-tz %s\n", ci.author_tz);
1550 printf("committer %s\n", ci.committer);
1551 printf("committer-mail %s\n", ci.committer_mail);
1552 printf("committer-time %lu\n", ci.committer_time);
1553 printf("committer-tz %s\n", ci.committer_tz);
1554 write_filename_info(suspect->path);
1555 printf("summary %s\n", ci.summary);
1556 if (suspect->commit->object.flags & UNINTERESTING)
1557 printf("boundary\n");
1559 else if (suspect->commit->object.flags & MORE_THAN_ONE_PATH)
1560 write_filename_info(suspect->path);
1562 cp = nth_line(sb, ent->lno);
1563 for (cnt = 0; cnt < ent->num_lines; cnt++) {
1566 printf("%s %d %d\n", hex,
1567 ent->s_lno + 1 + cnt,
1568 ent->lno + 1 + cnt);
1573 } while (ch != '\n' &&
1574 cp < sb->final_buf + sb->final_buf_size);
1578 static void emit_other(struct scoreboard *sb, struct blame_entry *ent, int opt)
1582 struct origin *suspect = ent->suspect;
1583 struct commit_info ci;
1585 int show_raw_time = !!(opt & OUTPUT_RAW_TIMESTAMP);
1587 get_commit_info(suspect->commit, &ci, 1);
1588 strcpy(hex, sha1_to_hex(suspect->commit->object.sha1));
1590 cp = nth_line(sb, ent->lno);
1591 for (cnt = 0; cnt < ent->num_lines; cnt++) {
1593 int length = (opt & OUTPUT_LONG_OBJECT_NAME) ? 40 : 8;
1595 if (suspect->commit->object.flags & UNINTERESTING) {
1597 memset(hex, ' ', length);
1598 else if (!(opt & OUTPUT_ANNOTATE_COMPAT)) {
1604 printf("%.*s", length, hex);
1605 if (opt & OUTPUT_ANNOTATE_COMPAT)
1606 printf("\t(%10s\t%10s\t%d)", ci.author,
1607 format_time(ci.author_time, ci.author_tz,
1609 ent->lno + 1 + cnt);
1611 if (opt & OUTPUT_SHOW_SCORE)
1613 max_score_digits, ent->score,
1614 ent->suspect->refcnt);
1615 if (opt & OUTPUT_SHOW_NAME)
1616 printf(" %-*.*s", longest_file, longest_file,
1618 if (opt & OUTPUT_SHOW_NUMBER)
1619 printf(" %*d", max_orig_digits,
1620 ent->s_lno + 1 + cnt);
1622 if (!(opt & OUTPUT_NO_AUTHOR)) {
1623 int pad = longest_author - utf8_strwidth(ci.author);
1624 printf(" (%s%*s %10s",
1626 format_time(ci.author_time,
1631 max_digits, ent->lno + 1 + cnt);
1636 } while (ch != '\n' &&
1637 cp < sb->final_buf + sb->final_buf_size);
1641 static void output(struct scoreboard *sb, int option)
1643 struct blame_entry *ent;
1645 if (option & OUTPUT_PORCELAIN) {
1646 for (ent = sb->ent; ent; ent = ent->next) {
1647 struct blame_entry *oth;
1648 struct origin *suspect = ent->suspect;
1649 struct commit *commit = suspect->commit;
1650 if (commit->object.flags & MORE_THAN_ONE_PATH)
1652 for (oth = ent->next; oth; oth = oth->next) {
1653 if ((oth->suspect->commit != commit) ||
1654 !strcmp(oth->suspect->path, suspect->path))
1656 commit->object.flags |= MORE_THAN_ONE_PATH;
1662 for (ent = sb->ent; ent; ent = ent->next) {
1663 if (option & OUTPUT_PORCELAIN)
1664 emit_porcelain(sb, ent);
1666 emit_other(sb, ent, option);
1672 * To allow quick access to the contents of nth line in the
1673 * final image, prepare an index in the scoreboard.
1675 static int prepare_lines(struct scoreboard *sb)
1677 const char *buf = sb->final_buf;
1678 unsigned long len = sb->final_buf_size;
1679 int num = 0, incomplete = 0, bol = 1;
1681 if (len && buf[len-1] != '\n')
1682 incomplete++; /* incomplete line at the end */
1685 sb->lineno = xrealloc(sb->lineno,
1686 sizeof(int* ) * (num + 1));
1687 sb->lineno[num] = buf - sb->final_buf;
1690 if (*buf++ == '\n') {
1695 sb->lineno = xrealloc(sb->lineno,
1696 sizeof(int* ) * (num + incomplete + 1));
1697 sb->lineno[num + incomplete] = buf - sb->final_buf;
1698 sb->num_lines = num + incomplete;
1699 return sb->num_lines;
1703 * Add phony grafts for use with -S; this is primarily to
1704 * support git's cvsserver that wants to give a linear history
1707 static int read_ancestry(const char *graft_file)
1709 FILE *fp = fopen(graft_file, "r");
1713 while (fgets(buf, sizeof(buf), fp)) {
1714 /* The format is just "Commit Parent1 Parent2 ...\n" */
1715 int len = strlen(buf);
1716 struct commit_graft *graft = read_graft_line(buf, len);
1718 register_commit_graft(graft, 0);
1725 * How many columns do we need to show line numbers in decimal?
1727 static int lineno_width(int lines)
1731 for (width = 1, i = 10; i <= lines + 1; width++)
1737 * How many columns do we need to show line numbers, authors,
1740 static void find_alignment(struct scoreboard *sb, int *option)
1742 int longest_src_lines = 0;
1743 int longest_dst_lines = 0;
1744 unsigned largest_score = 0;
1745 struct blame_entry *e;
1747 for (e = sb->ent; e; e = e->next) {
1748 struct origin *suspect = e->suspect;
1749 struct commit_info ci;
1752 if (strcmp(suspect->path, sb->path))
1753 *option |= OUTPUT_SHOW_NAME;
1754 num = strlen(suspect->path);
1755 if (longest_file < num)
1757 if (!(suspect->commit->object.flags & METAINFO_SHOWN)) {
1758 suspect->commit->object.flags |= METAINFO_SHOWN;
1759 get_commit_info(suspect->commit, &ci, 1);
1760 num = utf8_strwidth(ci.author);
1761 if (longest_author < num)
1762 longest_author = num;
1764 num = e->s_lno + e->num_lines;
1765 if (longest_src_lines < num)
1766 longest_src_lines = num;
1767 num = e->lno + e->num_lines;
1768 if (longest_dst_lines < num)
1769 longest_dst_lines = num;
1770 if (largest_score < ent_score(sb, e))
1771 largest_score = ent_score(sb, e);
1773 max_orig_digits = lineno_width(longest_src_lines);
1774 max_digits = lineno_width(longest_dst_lines);
1775 max_score_digits = lineno_width(largest_score);
1779 * For debugging -- origin is refcounted, and this asserts that
1780 * we do not underflow.
1782 static void sanity_check_refcnt(struct scoreboard *sb)
1785 struct blame_entry *ent;
1787 for (ent = sb->ent; ent; ent = ent->next) {
1788 /* Nobody should have zero or negative refcnt */
1789 if (ent->suspect->refcnt <= 0) {
1790 fprintf(stderr, "%s in %s has negative refcnt %d\n",
1792 sha1_to_hex(ent->suspect->commit->object.sha1),
1793 ent->suspect->refcnt);
1797 for (ent = sb->ent; ent; ent = ent->next) {
1798 /* Mark the ones that haven't been checked */
1799 if (0 < ent->suspect->refcnt)
1800 ent->suspect->refcnt = -ent->suspect->refcnt;
1802 for (ent = sb->ent; ent; ent = ent->next) {
1804 * ... then pick each and see if they have the the
1808 struct blame_entry *e;
1809 struct origin *suspect = ent->suspect;
1811 if (0 < suspect->refcnt)
1813 suspect->refcnt = -suspect->refcnt; /* Unmark */
1814 for (found = 0, e = sb->ent; e; e = e->next) {
1815 if (e->suspect != suspect)
1819 if (suspect->refcnt != found) {
1820 fprintf(stderr, "%s in %s has refcnt %d, not %d\n",
1822 sha1_to_hex(ent->suspect->commit->object.sha1),
1823 ent->suspect->refcnt, found);
1829 find_alignment(sb, &opt);
1831 die("Baa %d!", baa);
1836 * Used for the command line parsing; check if the path exists
1837 * in the working tree.
1839 static int has_string_in_work_tree(const char *path)
1842 return !lstat(path, &st);
1845 static unsigned parse_score(const char *arg)
1848 unsigned long score = strtoul(arg, &end, 10);
1854 static const char *add_prefix(const char *prefix, const char *path)
1856 return prefix_path(prefix, prefix ? strlen(prefix) : 0, path);
1860 * Parsing of (comma separated) one item in the -L option
1862 static const char *parse_loc(const char *spec,
1863 struct scoreboard *sb, long lno,
1864 long begin, long *ret)
1871 regmatch_t match[1];
1873 /* Allow "-L <something>,+20" to mean starting at <something>
1874 * for 20 lines, or "-L <something>,-5" for 5 lines ending at
1877 if (1 < begin && (spec[0] == '+' || spec[0] == '-')) {
1878 num = strtol(spec + 1, &term, 10);
1879 if (term != spec + 1) {
1883 *ret = begin + num - 2;
1892 num = strtol(spec, &term, 10);
1900 /* it could be a regexp of form /.../ */
1901 for (term = (char*) spec + 1; *term && *term != '/'; term++) {
1908 /* try [spec+1 .. term-1] as regexp */
1910 begin--; /* input is in human terms */
1911 line = nth_line(sb, begin);
1913 if (!(reg_error = regcomp(®exp, spec + 1, REG_NEWLINE)) &&
1914 !(reg_error = regexec(®exp, line, 1, match, 0))) {
1915 const char *cp = line + match[0].rm_so;
1918 while (begin++ < lno) {
1919 nline = nth_line(sb, begin);
1920 if (line <= cp && cp < nline)
1931 regerror(reg_error, ®exp, errbuf, 1024);
1932 die("-L parameter '%s': %s", spec + 1, errbuf);
1937 * Parsing of -L option
1939 static void prepare_blame_range(struct scoreboard *sb,
1940 const char *bottomtop,
1942 long *bottom, long *top)
1946 term = parse_loc(bottomtop, sb, lno, 1, bottom);
1948 term = parse_loc(term + 1, sb, lno, *bottom + 1, top);
1956 static int git_blame_config(const char *var, const char *value, void *cb)
1958 if (!strcmp(var, "blame.showroot")) {
1959 show_root = git_config_bool(var, value);
1962 if (!strcmp(var, "blame.blankboundary")) {
1963 blank_boundary = git_config_bool(var, value);
1966 return git_default_config(var, value, cb);
1970 * Prepare a dummy commit that represents the work tree (or staged) item.
1971 * Note that annotating work tree item never works in the reverse.
1973 static struct commit *fake_working_tree_commit(const char *path, const char *contents_from)
1975 struct commit *commit;
1976 struct origin *origin;
1977 unsigned char head_sha1[20];
1978 struct strbuf buf = STRBUF_INIT;
1982 struct cache_entry *ce;
1985 if (get_sha1("HEAD", head_sha1))
1986 die("No such ref: HEAD");
1989 commit = xcalloc(1, sizeof(*commit));
1990 commit->parents = xcalloc(1, sizeof(*commit->parents));
1991 commit->parents->item = lookup_commit_reference(head_sha1);
1992 commit->object.parsed = 1;
1994 commit->object.type = OBJ_COMMIT;
1996 origin = make_origin(commit, path);
1998 if (!contents_from || strcmp("-", contents_from)) {
2000 const char *read_from;
2002 if (contents_from) {
2003 if (stat(contents_from, &st) < 0)
2004 die("Cannot stat %s", contents_from);
2005 read_from = contents_from;
2008 if (lstat(path, &st) < 0)
2009 die("Cannot lstat %s", path);
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 (strbuf_readlink(&buf, read_from, st.st_size) < 0)
2020 die("cannot readlink %s", read_from);
2023 die("unsupported file type %s", read_from);
2027 /* Reading from stdin */
2028 contents_from = "standard input";
2030 if (strbuf_read(&buf, 0, 0) < 0)
2031 die("read error %s from stdin", strerror(errno));
2033 convert_to_git(path, buf.buf, buf.len, &buf, 0);
2034 origin->file.ptr = buf.buf;
2035 origin->file.size = buf.len;
2036 pretend_sha1_file(buf.buf, buf.len, OBJ_BLOB, origin->blob_sha1);
2037 commit->util = origin;
2040 * Read the current index, replace the path entry with
2041 * origin->blob_sha1 without mucking with its mode or type
2042 * bits; we are not going to write this index out -- we just
2043 * want to run "diff-index --cached".
2050 int pos = cache_name_pos(path, len);
2052 mode = active_cache[pos]->ce_mode;
2054 /* Let's not bother reading from HEAD tree */
2055 mode = S_IFREG | 0644;
2057 size = cache_entry_size(len);
2058 ce = xcalloc(1, size);
2059 hashcpy(ce->sha1, origin->blob_sha1);
2060 memcpy(ce->name, path, len);
2061 ce->ce_flags = create_ce_flags(len, 0);
2062 ce->ce_mode = create_ce_mode(mode);
2063 add_cache_entry(ce, ADD_CACHE_OK_TO_ADD|ADD_CACHE_OK_TO_REPLACE);
2066 * We are not going to write this out, so this does not matter
2067 * right now, but someday we might optimize diff-index --cached
2068 * with cache-tree information.
2070 cache_tree_invalidate_path(active_cache_tree, path);
2072 commit->buffer = xmalloc(400);
2073 ident = fmt_ident("Not Committed Yet", "not.committed.yet", NULL, 0);
2074 snprintf(commit->buffer, 400,
2075 "tree 0000000000000000000000000000000000000000\n"
2079 "Version of %s from %s\n",
2080 sha1_to_hex(head_sha1),
2081 ident, ident, path, contents_from ? contents_from : path);
2085 static const char *prepare_final(struct scoreboard *sb)
2088 const char *final_commit_name = NULL;
2089 struct rev_info *revs = sb->revs;
2092 * There must be one and only one positive commit in the
2093 * revs->pending array.
2095 for (i = 0; i < revs->pending.nr; i++) {
2096 struct object *obj = revs->pending.objects[i].item;
2097 if (obj->flags & UNINTERESTING)
2099 while (obj->type == OBJ_TAG)
2100 obj = deref_tag(obj, NULL, 0);
2101 if (obj->type != OBJ_COMMIT)
2102 die("Non commit %s?", revs->pending.objects[i].name);
2104 die("More than one commit to dig from %s and %s?",
2105 revs->pending.objects[i].name,
2107 sb->final = (struct commit *) obj;
2108 final_commit_name = revs->pending.objects[i].name;
2110 return final_commit_name;
2113 static const char *prepare_initial(struct scoreboard *sb)
2116 const char *final_commit_name = NULL;
2117 struct rev_info *revs = sb->revs;
2120 * There must be one and only one negative commit, and it must be
2123 for (i = 0; i < revs->pending.nr; i++) {
2124 struct object *obj = revs->pending.objects[i].item;
2125 if (!(obj->flags & UNINTERESTING))
2127 while (obj->type == OBJ_TAG)
2128 obj = deref_tag(obj, NULL, 0);
2129 if (obj->type != OBJ_COMMIT)
2130 die("Non commit %s?", revs->pending.objects[i].name);
2132 die("More than one commit to dig down to %s and %s?",
2133 revs->pending.objects[i].name,
2135 sb->final = (struct commit *) obj;
2136 final_commit_name = revs->pending.objects[i].name;
2138 if (!final_commit_name)
2139 die("No commit to dig down to?");
2140 return final_commit_name;
2143 static int blame_copy_callback(const struct option *option, const char *arg, int unset)
2145 int *opt = option->value;
2148 * -C enables copy from removed files;
2149 * -C -C enables copy from existing files, but only
2150 * when blaming a new file;
2151 * -C -C -C enables copy from existing files for
2154 if (*opt & PICKAXE_BLAME_COPY_HARDER)
2155 *opt |= PICKAXE_BLAME_COPY_HARDEST;
2156 if (*opt & PICKAXE_BLAME_COPY)
2157 *opt |= PICKAXE_BLAME_COPY_HARDER;
2158 *opt |= PICKAXE_BLAME_COPY | PICKAXE_BLAME_MOVE;
2161 blame_copy_score = parse_score(arg);
2165 static int blame_move_callback(const struct option *option, const char *arg, int unset)
2167 int *opt = option->value;
2169 *opt |= PICKAXE_BLAME_MOVE;
2172 blame_move_score = parse_score(arg);
2176 static int blame_bottomtop_callback(const struct option *option, const char *arg, int unset)
2178 const char **bottomtop = option->value;
2182 die("More than one '-L n,m' option given");
2187 int cmd_blame(int argc, const char **argv, const char *prefix)
2189 struct rev_info revs;
2191 struct scoreboard sb;
2193 struct blame_entry *ent;
2194 long dashdash_pos, bottom, top, lno;
2195 const char *final_commit_name = NULL;
2196 enum object_type type;
2198 static const char *bottomtop = NULL;
2199 static int output_option = 0, opt = 0;
2200 static int show_stats = 0;
2201 static const char *revs_file = NULL;
2202 static const char *contents_from = NULL;
2203 static const struct option options[] = {
2204 OPT_BOOLEAN(0, "incremental", &incremental, "Show blame entries as we find them, incrementally"),
2205 OPT_BOOLEAN('b', NULL, &blank_boundary, "Show blank SHA-1 for boundary commits (Default: off)"),
2206 OPT_BOOLEAN(0, "root", &show_root, "Do not treat root commits as boundaries (Default: off)"),
2207 OPT_BOOLEAN(0, "show-stats", &show_stats, "Show work cost statistics"),
2208 OPT_BIT(0, "score-debug", &output_option, "Show output score for blame entries", OUTPUT_SHOW_SCORE),
2209 OPT_BIT('f', "show-name", &output_option, "Show original filename (Default: auto)", OUTPUT_SHOW_NAME),
2210 OPT_BIT('n', "show-number", &output_option, "Show original linenumber (Default: off)", OUTPUT_SHOW_NUMBER),
2211 OPT_BIT('p', "porcelain", &output_option, "Show in a format designed for machine consumption", OUTPUT_PORCELAIN),
2212 OPT_BIT('c', NULL, &output_option, "Use the same output mode as git-annotate (Default: off)", OUTPUT_ANNOTATE_COMPAT),
2213 OPT_BIT('t', NULL, &output_option, "Show raw timestamp (Default: off)", OUTPUT_RAW_TIMESTAMP),
2214 OPT_BIT('l', NULL, &output_option, "Show long commit SHA1 (Default: off)", OUTPUT_LONG_OBJECT_NAME),
2215 OPT_BIT('s', NULL, &output_option, "Suppress author name and timestamp (Default: off)", OUTPUT_NO_AUTHOR),
2216 OPT_BIT('w', NULL, &xdl_opts, "Ignore whitespace differences", XDF_IGNORE_WHITESPACE),
2217 OPT_STRING('S', NULL, &revs_file, "file", "Use revisions from <file> instead of calling git-rev-list"),
2218 OPT_STRING(0, "contents", &contents_from, "file", "Use <file>'s contents as the final image"),
2219 { OPTION_CALLBACK, 'C', NULL, &opt, "score", "Find line copies within and across files", PARSE_OPT_OPTARG, blame_copy_callback },
2220 { OPTION_CALLBACK, 'M', NULL, &opt, "score", "Find line movements within and across files", PARSE_OPT_OPTARG, blame_move_callback },
2221 OPT_CALLBACK('L', NULL, &bottomtop, "n,m", "Process only line range n,m, counting from 1", blame_bottomtop_callback),
2225 struct parse_opt_ctx_t ctx;
2226 int cmd_is_annotate = !strcmp(argv[0], "annotate");
2228 git_config(git_blame_config, NULL);
2229 init_revisions(&revs, NULL);
2230 save_commit_buffer = 0;
2233 parse_options_start(&ctx, argc, argv, PARSE_OPT_KEEP_DASHDASH |
2234 PARSE_OPT_KEEP_ARGV0);
2236 switch (parse_options_step(&ctx, options, blame_opt_usage)) {
2237 case PARSE_OPT_HELP:
2239 case PARSE_OPT_DONE:
2241 dashdash_pos = ctx.cpidx;
2245 if (!strcmp(ctx.argv[0], "--reverse")) {
2246 ctx.argv[0] = "--children";
2249 parse_revision_opt(&revs, &ctx, options, blame_opt_usage);
2252 argc = parse_options_end(&ctx);
2254 if (cmd_is_annotate)
2255 output_option |= OUTPUT_ANNOTATE_COMPAT;
2257 if (DIFF_OPT_TST(&revs.diffopt, FIND_COPIES_HARDER))
2258 opt |= (PICKAXE_BLAME_COPY | PICKAXE_BLAME_MOVE |
2259 PICKAXE_BLAME_COPY_HARDER);
2261 if (!blame_move_score)
2262 blame_move_score = BLAME_DEFAULT_MOVE_SCORE;
2263 if (!blame_copy_score)
2264 blame_copy_score = BLAME_DEFAULT_COPY_SCORE;
2267 * We have collected options unknown to us in argv[1..unk]
2268 * which are to be passed to revision machinery if we are
2269 * going to do the "bottom" processing.
2271 * The remaining are:
2273 * (1) if dashdash_pos != 0, its either
2274 * "blame [revisions] -- <path>" or
2275 * "blame -- <path> <rev>"
2277 * (2) otherwise, its one of the two:
2278 * "blame [revisions] <path>"
2279 * "blame <path> <rev>"
2281 * Note that we must strip out <path> from the arguments: we do not
2282 * want the path pruning but we may want "bottom" processing.
2285 switch (argc - dashdash_pos - 1) {
2288 usage_with_options(blame_opt_usage, options);
2289 /* reorder for the new way: <rev> -- <path> */
2295 path = add_prefix(prefix, argv[--argc]);
2299 usage_with_options(blame_opt_usage, options);
2303 usage_with_options(blame_opt_usage, options);
2304 path = add_prefix(prefix, argv[argc - 1]);
2305 if (argc == 3 && !has_string_in_work_tree(path)) { /* (2b) */
2306 path = add_prefix(prefix, argv[1]);
2309 argv[argc - 1] = "--";
2312 if (!has_string_in_work_tree(path))
2313 die("cannot stat path %s: %s", path, strerror(errno));
2316 setup_revisions(argc, argv, &revs, NULL);
2317 memset(&sb, 0, sizeof(sb));
2321 final_commit_name = prepare_final(&sb);
2322 else if (contents_from)
2323 die("--contents and --children do not blend well.");
2325 final_commit_name = prepare_initial(&sb);
2329 * "--not A B -- path" without anything positive;
2330 * do not default to HEAD, but use the working tree
2334 sb.final = fake_working_tree_commit(path, contents_from);
2335 add_pending_object(&revs, &(sb.final->object), ":");
2337 else if (contents_from)
2338 die("Cannot use --contents with final commit object name");
2341 * If we have bottom, this will mark the ancestors of the
2342 * bottom commits we would reach while traversing as
2345 if (prepare_revision_walk(&revs))
2346 die("revision walk setup failed");
2348 if (is_null_sha1(sb.final->object.sha1)) {
2351 buf = xmalloc(o->file.size + 1);
2352 memcpy(buf, o->file.ptr, o->file.size + 1);
2354 sb.final_buf_size = o->file.size;
2357 o = get_origin(&sb, sb.final, path);
2358 if (fill_blob_sha1(o))
2359 die("no such path %s in %s", path, final_commit_name);
2361 sb.final_buf = read_sha1_file(o->blob_sha1, &type,
2362 &sb.final_buf_size);
2364 die("Cannot read blob %s for path %s",
2365 sha1_to_hex(o->blob_sha1),
2369 lno = prepare_lines(&sb);
2373 prepare_blame_range(&sb, bottomtop, lno, &bottom, &top);
2374 if (bottom && top && top < bottom) {
2376 tmp = top; top = bottom; bottom = tmp;
2384 die("file %s has only %lu lines", path, lno);
2386 ent = xcalloc(1, sizeof(*ent));
2388 ent->num_lines = top - bottom;
2390 ent->s_lno = bottom;
2395 if (revs_file && read_ancestry(revs_file))
2396 die("reading graft file %s failed: %s",
2397 revs_file, strerror(errno));
2399 read_mailmap(&mailmap, ".mailmap", NULL);
2404 assign_blame(&sb, opt);
2411 if (!(output_option & OUTPUT_PORCELAIN))
2412 find_alignment(&sb, &output_option);
2414 output(&sb, output_option);
2415 free((void *)sb.final_buf);
2416 for (ent = sb.ent; ent; ) {
2417 struct blame_entry *e = ent->next;
2423 printf("num read blob: %d\n", num_read_blob);
2424 printf("num get patch: %d\n", num_get_patch);
2425 printf("num commits: %d\n", num_commits);