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;
44 static enum date_mode blame_date_mode = DATE_ISO8601;
45 static size_t blame_date_width;
47 static struct string_list mailmap;
54 static int num_read_blob;
55 static int num_get_patch;
56 static int num_commits;
58 #define PICKAXE_BLAME_MOVE 01
59 #define PICKAXE_BLAME_COPY 02
60 #define PICKAXE_BLAME_COPY_HARDER 04
61 #define PICKAXE_BLAME_COPY_HARDEST 010
64 * blame for a blame_entry with score lower than these thresholds
65 * is not passed to the parent using move/copy logic.
67 static unsigned blame_move_score;
68 static unsigned blame_copy_score;
69 #define BLAME_DEFAULT_MOVE_SCORE 20
70 #define BLAME_DEFAULT_COPY_SCORE 40
72 /* bits #0..7 in revision.h, #8..11 used for merge_bases() in commit.c */
73 #define METAINFO_SHOWN (1u<<12)
74 #define MORE_THAN_ONE_PATH (1u<<13)
77 * One blob in a commit that is being suspected
81 struct commit *commit;
83 unsigned char blob_sha1[20];
84 char path[FLEX_ARRAY];
88 * Given an origin, prepare mmfile_t structure to be used by the
91 static void fill_origin_blob(struct origin *o, mmfile_t *file)
94 enum object_type type;
96 file->ptr = read_sha1_file(o->blob_sha1, &type,
97 (unsigned long *)(&(file->size)));
99 die("Cannot read blob %s for path %s",
100 sha1_to_hex(o->blob_sha1),
109 * Origin is refcounted and usually we keep the blob contents to be
112 static inline struct origin *origin_incref(struct origin *o)
119 static void origin_decref(struct origin *o)
121 if (o && --o->refcnt <= 0) {
127 static void drop_origin_blob(struct origin *o)
136 * Each group of lines is described by a blame_entry; it can be split
137 * as we pass blame to the parents. They form a linked list in the
138 * scoreboard structure, sorted by the target line number.
141 struct blame_entry *prev;
142 struct blame_entry *next;
144 /* the first line of this group in the final image;
145 * internally all line numbers are 0 based.
149 /* how many lines this group has */
152 /* the commit that introduced this group into the final image */
153 struct origin *suspect;
155 /* true if the suspect is truly guilty; false while we have not
156 * checked if the group came from one of its parents.
160 /* true if the entry has been scanned for copies in the current parent
164 /* the line number of the first line of this group in the
165 * suspect's file; internally all line numbers are 0 based.
169 /* how significant this entry is -- cached to avoid
170 * scanning the lines over and over.
176 * The current state of the blame assignment.
179 /* the final commit (i.e. where we started digging from) */
180 struct commit *final;
181 struct rev_info *revs;
185 * The contents in the final image.
186 * Used by many functions to obtain contents of the nth line,
187 * indexed with scoreboard.lineno[blame_entry.lno].
189 const char *final_buf;
190 unsigned long final_buf_size;
192 /* linked list of blames */
193 struct blame_entry *ent;
195 /* look-up a line in the final buffer */
200 static inline int same_suspect(struct origin *a, struct origin *b)
204 if (a->commit != b->commit)
206 return !strcmp(a->path, b->path);
209 static void sanity_check_refcnt(struct scoreboard *);
212 * If two blame entries that are next to each other came from
213 * contiguous lines in the same origin (i.e. <commit, path> pair),
214 * merge them together.
216 static void coalesce(struct scoreboard *sb)
218 struct blame_entry *ent, *next;
220 for (ent = sb->ent; ent && (next = ent->next); ent = next) {
221 if (same_suspect(ent->suspect, next->suspect) &&
222 ent->guilty == next->guilty &&
223 ent->s_lno + ent->num_lines == next->s_lno) {
224 ent->num_lines += next->num_lines;
225 ent->next = next->next;
227 ent->next->prev = ent;
228 origin_decref(next->suspect);
231 next = ent; /* again */
235 if (DEBUG) /* sanity */
236 sanity_check_refcnt(sb);
240 * Given a commit and a path in it, create a new origin structure.
241 * The callers that add blame to the scoreboard should use
242 * get_origin() to obtain shared, refcounted copy instead of calling
243 * this function directly.
245 static struct origin *make_origin(struct commit *commit, const char *path)
248 o = xcalloc(1, sizeof(*o) + strlen(path) + 1);
251 strcpy(o->path, path);
256 * Locate an existing origin or create a new one.
258 static struct origin *get_origin(struct scoreboard *sb,
259 struct commit *commit,
262 struct blame_entry *e;
264 for (e = sb->ent; e; e = e->next) {
265 if (e->suspect->commit == commit &&
266 !strcmp(e->suspect->path, path))
267 return origin_incref(e->suspect);
269 return make_origin(commit, path);
273 * Fill the blob_sha1 field of an origin if it hasn't, so that later
274 * call to fill_origin_blob() can use it to locate the data. blob_sha1
275 * for an origin is also used to pass the blame for the entire file to
276 * the parent to detect the case where a child's blob is identical to
277 * that of its parent's.
279 static int fill_blob_sha1(struct origin *origin)
283 if (!is_null_sha1(origin->blob_sha1))
285 if (get_tree_entry(origin->commit->object.sha1,
287 origin->blob_sha1, &mode))
289 if (sha1_object_info(origin->blob_sha1, NULL) != OBJ_BLOB)
293 hashclr(origin->blob_sha1);
298 * We have an origin -- check if the same path exists in the
299 * parent and return an origin structure to represent it.
301 static struct origin *find_origin(struct scoreboard *sb,
302 struct commit *parent,
303 struct origin *origin)
305 struct origin *porigin = NULL;
306 struct diff_options diff_opts;
307 const char *paths[2];
311 * Each commit object can cache one origin in that
312 * commit. This is a freestanding copy of origin and
315 struct origin *cached = parent->util;
316 if (!strcmp(cached->path, origin->path)) {
318 * The same path between origin and its parent
319 * without renaming -- the most common case.
321 porigin = get_origin(sb, parent, cached->path);
324 * If the origin was newly created (i.e. get_origin
325 * would call make_origin if none is found in the
326 * scoreboard), it does not know the blob_sha1,
327 * so copy it. Otherwise porigin was in the
328 * scoreboard and already knows blob_sha1.
330 if (porigin->refcnt == 1)
331 hashcpy(porigin->blob_sha1, cached->blob_sha1);
334 /* otherwise it was not very useful; free it */
339 /* See if the origin->path is different between parent
340 * and origin first. Most of the time they are the
341 * same and diff-tree is fairly efficient about this.
343 diff_setup(&diff_opts);
344 DIFF_OPT_SET(&diff_opts, RECURSIVE);
345 diff_opts.detect_rename = 0;
346 diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;
347 paths[0] = origin->path;
350 diff_tree_setup_paths(paths, &diff_opts);
351 if (diff_setup_done(&diff_opts) < 0)
354 if (is_null_sha1(origin->commit->object.sha1))
355 do_diff_cache(parent->tree->object.sha1, &diff_opts);
357 diff_tree_sha1(parent->tree->object.sha1,
358 origin->commit->tree->object.sha1,
360 diffcore_std(&diff_opts);
362 /* It is either one entry that says "modified", or "created",
365 if (!diff_queued_diff.nr) {
366 /* The path is the same as parent */
367 porigin = get_origin(sb, parent, origin->path);
368 hashcpy(porigin->blob_sha1, origin->blob_sha1);
370 else if (diff_queued_diff.nr != 1)
371 die("internal error in blame::find_origin");
373 struct diff_filepair *p = diff_queued_diff.queue[0];
376 die("internal error in blame::find_origin (%c)",
379 porigin = get_origin(sb, parent, origin->path);
380 hashcpy(porigin->blob_sha1, p->one->sha1);
384 /* Did not exist in parent, or type changed */
388 diff_flush(&diff_opts);
389 diff_tree_release_paths(&diff_opts);
392 * Create a freestanding copy that is not part of
393 * the refcounted origin found in the scoreboard, and
394 * cache it in the commit.
396 struct origin *cached;
398 cached = make_origin(porigin->commit, porigin->path);
399 hashcpy(cached->blob_sha1, porigin->blob_sha1);
400 parent->util = cached;
406 * We have an origin -- find the path that corresponds to it in its
407 * parent and return an origin structure to represent it.
409 static struct origin *find_rename(struct scoreboard *sb,
410 struct commit *parent,
411 struct origin *origin)
413 struct origin *porigin = NULL;
414 struct diff_options diff_opts;
416 const char *paths[2];
418 diff_setup(&diff_opts);
419 DIFF_OPT_SET(&diff_opts, RECURSIVE);
420 diff_opts.detect_rename = DIFF_DETECT_RENAME;
421 diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;
422 diff_opts.single_follow = origin->path;
424 diff_tree_setup_paths(paths, &diff_opts);
425 if (diff_setup_done(&diff_opts) < 0)
428 if (is_null_sha1(origin->commit->object.sha1))
429 do_diff_cache(parent->tree->object.sha1, &diff_opts);
431 diff_tree_sha1(parent->tree->object.sha1,
432 origin->commit->tree->object.sha1,
434 diffcore_std(&diff_opts);
436 for (i = 0; i < diff_queued_diff.nr; i++) {
437 struct diff_filepair *p = diff_queued_diff.queue[i];
438 if ((p->status == 'R' || p->status == 'C') &&
439 !strcmp(p->two->path, origin->path)) {
440 porigin = get_origin(sb, parent, p->one->path);
441 hashcpy(porigin->blob_sha1, p->one->sha1);
445 diff_flush(&diff_opts);
446 diff_tree_release_paths(&diff_opts);
451 * Link in a new blame entry to the scoreboard. Entries that cover the
452 * same line range have been removed from the scoreboard previously.
454 static void add_blame_entry(struct scoreboard *sb, struct blame_entry *e)
456 struct blame_entry *ent, *prev = NULL;
458 origin_incref(e->suspect);
460 for (ent = sb->ent; ent && ent->lno < e->lno; ent = ent->next)
463 /* prev, if not NULL, is the last one that is below e */
466 e->next = prev->next;
478 * src typically is on-stack; we want to copy the information in it to
479 * a malloced blame_entry that is already on the linked list of the
480 * scoreboard. The origin of dst loses a refcnt while the origin of src
483 static void dup_entry(struct blame_entry *dst, struct blame_entry *src)
485 struct blame_entry *p, *n;
489 origin_incref(src->suspect);
490 origin_decref(dst->suspect);
491 memcpy(dst, src, sizeof(*src));
497 static const char *nth_line(struct scoreboard *sb, int lno)
499 return sb->final_buf + sb->lineno[lno];
503 * It is known that lines between tlno to same came from parent, and e
504 * has an overlap with that range. it also is known that parent's
505 * line plno corresponds to e's line tlno.
511 * <------------------>
513 * Split e into potentially three parts; before this chunk, the chunk
514 * to be blamed for the parent, and after that portion.
516 static void split_overlap(struct blame_entry *split,
517 struct blame_entry *e,
518 int tlno, int plno, int same,
519 struct origin *parent)
522 memset(split, 0, sizeof(struct blame_entry [3]));
524 if (e->s_lno < tlno) {
525 /* there is a pre-chunk part not blamed on parent */
526 split[0].suspect = origin_incref(e->suspect);
527 split[0].lno = e->lno;
528 split[0].s_lno = e->s_lno;
529 split[0].num_lines = tlno - e->s_lno;
530 split[1].lno = e->lno + tlno - e->s_lno;
531 split[1].s_lno = plno;
534 split[1].lno = e->lno;
535 split[1].s_lno = plno + (e->s_lno - tlno);
538 if (same < e->s_lno + e->num_lines) {
539 /* there is a post-chunk part not blamed on parent */
540 split[2].suspect = origin_incref(e->suspect);
541 split[2].lno = e->lno + (same - e->s_lno);
542 split[2].s_lno = e->s_lno + (same - e->s_lno);
543 split[2].num_lines = e->s_lno + e->num_lines - same;
544 chunk_end_lno = split[2].lno;
547 chunk_end_lno = e->lno + e->num_lines;
548 split[1].num_lines = chunk_end_lno - split[1].lno;
551 * if it turns out there is nothing to blame the parent for,
552 * forget about the splitting. !split[1].suspect signals this.
554 if (split[1].num_lines < 1)
556 split[1].suspect = origin_incref(parent);
560 * split_overlap() divided an existing blame e into up to three parts
561 * in split. Adjust the linked list of blames in the scoreboard to
564 static void split_blame(struct scoreboard *sb,
565 struct blame_entry *split,
566 struct blame_entry *e)
568 struct blame_entry *new_entry;
570 if (split[0].suspect && split[2].suspect) {
571 /* The first part (reuse storage for the existing entry e) */
572 dup_entry(e, &split[0]);
574 /* The last part -- me */
575 new_entry = xmalloc(sizeof(*new_entry));
576 memcpy(new_entry, &(split[2]), sizeof(struct blame_entry));
577 add_blame_entry(sb, new_entry);
579 /* ... and the middle part -- parent */
580 new_entry = xmalloc(sizeof(*new_entry));
581 memcpy(new_entry, &(split[1]), sizeof(struct blame_entry));
582 add_blame_entry(sb, new_entry);
584 else if (!split[0].suspect && !split[2].suspect)
586 * The parent covers the entire area; reuse storage for
587 * e and replace it with the parent.
589 dup_entry(e, &split[1]);
590 else if (split[0].suspect) {
591 /* me and then parent */
592 dup_entry(e, &split[0]);
594 new_entry = xmalloc(sizeof(*new_entry));
595 memcpy(new_entry, &(split[1]), sizeof(struct blame_entry));
596 add_blame_entry(sb, new_entry);
599 /* parent and then me */
600 dup_entry(e, &split[1]);
602 new_entry = xmalloc(sizeof(*new_entry));
603 memcpy(new_entry, &(split[2]), sizeof(struct blame_entry));
604 add_blame_entry(sb, new_entry);
607 if (DEBUG) { /* sanity */
608 struct blame_entry *ent;
609 int lno = sb->ent->lno, corrupt = 0;
611 for (ent = sb->ent; ent; ent = ent->next) {
616 lno += ent->num_lines;
620 for (ent = sb->ent; ent; ent = ent->next) {
621 printf("L %8d l %8d n %8d\n",
622 lno, ent->lno, ent->num_lines);
623 lno = ent->lno + ent->num_lines;
631 * After splitting the blame, the origins used by the
632 * on-stack blame_entry should lose one refcnt each.
634 static void decref_split(struct blame_entry *split)
638 for (i = 0; i < 3; i++)
639 origin_decref(split[i].suspect);
643 * Helper for blame_chunk(). blame_entry e is known to overlap with
644 * the patch hunk; split it and pass blame to the parent.
646 static void blame_overlap(struct scoreboard *sb, struct blame_entry *e,
647 int tlno, int plno, int same,
648 struct origin *parent)
650 struct blame_entry split[3];
652 split_overlap(split, e, tlno, plno, same, parent);
653 if (split[1].suspect)
654 split_blame(sb, split, e);
659 * Find the line number of the last line the target is suspected for.
661 static int find_last_in_target(struct scoreboard *sb, struct origin *target)
663 struct blame_entry *e;
664 int last_in_target = -1;
666 for (e = sb->ent; e; e = e->next) {
667 if (e->guilty || !same_suspect(e->suspect, target))
669 if (last_in_target < e->s_lno + e->num_lines)
670 last_in_target = e->s_lno + e->num_lines;
672 return last_in_target;
676 * Process one hunk from the patch between the current suspect for
677 * blame_entry e and its parent. Find and split the overlap, and
678 * pass blame to the overlapping part to the parent.
680 static void blame_chunk(struct scoreboard *sb,
681 int tlno, int plno, int same,
682 struct origin *target, struct origin *parent)
684 struct blame_entry *e;
686 for (e = sb->ent; e; e = e->next) {
687 if (e->guilty || !same_suspect(e->suspect, target))
689 if (same <= e->s_lno)
691 if (tlno < e->s_lno + e->num_lines)
692 blame_overlap(sb, e, tlno, plno, same, parent);
696 struct blame_chunk_cb_data {
697 struct scoreboard *sb;
698 struct origin *target;
699 struct origin *parent;
704 static void blame_chunk_cb(void *data, long same, long p_next, long t_next)
706 struct blame_chunk_cb_data *d = data;
707 blame_chunk(d->sb, d->tlno, d->plno, same, d->target, d->parent);
713 * We are looking at the origin 'target' and aiming to pass blame
714 * for the lines it is suspected to its parent. Run diff to find
715 * which lines came from parent and pass blame for them.
717 static int pass_blame_to_parent(struct scoreboard *sb,
718 struct origin *target,
719 struct origin *parent)
722 mmfile_t file_p, file_o;
723 struct blame_chunk_cb_data d = { sb, target, parent, 0, 0 };
727 last_in_target = find_last_in_target(sb, target);
728 if (last_in_target < 0)
729 return 1; /* nothing remains for this target */
731 fill_origin_blob(parent, &file_p);
732 fill_origin_blob(target, &file_o);
735 memset(&xpp, 0, sizeof(xpp));
736 xpp.flags = xdl_opts;
737 memset(&xecfg, 0, sizeof(xecfg));
739 xdi_diff_hunks(&file_p, &file_o, blame_chunk_cb, &d, &xpp, &xecfg);
740 /* The rest (i.e. anything after tlno) are the same as the parent */
741 blame_chunk(sb, d.tlno, d.plno, last_in_target, target, parent);
747 * The lines in blame_entry after splitting blames many times can become
748 * very small and trivial, and at some point it becomes pointless to
749 * blame the parents. E.g. "\t\t}\n\t}\n\n" appears everywhere in any
750 * ordinary C program, and it is not worth to say it was copied from
751 * totally unrelated file in the parent.
753 * Compute how trivial the lines in the blame_entry are.
755 static unsigned ent_score(struct scoreboard *sb, struct blame_entry *e)
764 cp = nth_line(sb, e->lno);
765 ep = nth_line(sb, e->lno + e->num_lines);
767 unsigned ch = *((unsigned char *)cp);
777 * best_so_far[] and this[] are both a split of an existing blame_entry
778 * that passes blame to the parent. Maintain best_so_far the best split
779 * so far, by comparing this and best_so_far and copying this into
780 * bst_so_far as needed.
782 static void copy_split_if_better(struct scoreboard *sb,
783 struct blame_entry *best_so_far,
784 struct blame_entry *this)
788 if (!this[1].suspect)
790 if (best_so_far[1].suspect) {
791 if (ent_score(sb, &this[1]) < ent_score(sb, &best_so_far[1]))
795 for (i = 0; i < 3; i++)
796 origin_incref(this[i].suspect);
797 decref_split(best_so_far);
798 memcpy(best_so_far, this, sizeof(struct blame_entry [3]));
802 * We are looking at a part of the final image represented by
803 * ent (tlno and same are offset by ent->s_lno).
804 * tlno is where we are looking at in the final image.
805 * up to (but not including) same match preimage.
806 * plno is where we are looking at in the preimage.
808 * <-------------- final image ---------------------->
811 * <---------preimage----->
814 * All line numbers are 0-based.
816 static void handle_split(struct scoreboard *sb,
817 struct blame_entry *ent,
818 int tlno, int plno, int same,
819 struct origin *parent,
820 struct blame_entry *split)
822 if (ent->num_lines <= tlno)
825 struct blame_entry this[3];
828 split_overlap(this, ent, tlno, plno, same, parent);
829 copy_split_if_better(sb, split, this);
834 struct handle_split_cb_data {
835 struct scoreboard *sb;
836 struct blame_entry *ent;
837 struct origin *parent;
838 struct blame_entry *split;
843 static void handle_split_cb(void *data, long same, long p_next, long t_next)
845 struct handle_split_cb_data *d = data;
846 handle_split(d->sb, d->ent, d->tlno, d->plno, same, d->parent, d->split);
852 * Find the lines from parent that are the same as ent so that
853 * we can pass blames to it. file_p has the blob contents for
856 static void find_copy_in_blob(struct scoreboard *sb,
857 struct blame_entry *ent,
858 struct origin *parent,
859 struct blame_entry *split,
865 struct handle_split_cb_data d = { sb, ent, parent, split, 0, 0 };
870 * Prepare mmfile that contains only the lines in ent.
872 cp = nth_line(sb, ent->lno);
873 file_o.ptr = (char*) cp;
874 cnt = ent->num_lines;
876 while (cnt && cp < sb->final_buf + sb->final_buf_size) {
880 file_o.size = cp - file_o.ptr;
883 * file_o is a part of final image we are annotating.
884 * file_p partially may match that image.
886 memset(&xpp, 0, sizeof(xpp));
887 xpp.flags = xdl_opts;
888 memset(&xecfg, 0, sizeof(xecfg));
890 memset(split, 0, sizeof(struct blame_entry [3]));
891 xdi_diff_hunks(file_p, &file_o, handle_split_cb, &d, &xpp, &xecfg);
892 /* remainder, if any, all match the preimage */
893 handle_split(sb, ent, d.tlno, d.plno, ent->num_lines, parent, split);
897 * See if lines currently target is suspected for can be attributed to
900 static int find_move_in_parent(struct scoreboard *sb,
901 struct origin *target,
902 struct origin *parent)
904 int last_in_target, made_progress;
905 struct blame_entry *e, split[3];
908 last_in_target = find_last_in_target(sb, target);
909 if (last_in_target < 0)
910 return 1; /* nothing remains for this target */
912 fill_origin_blob(parent, &file_p);
917 while (made_progress) {
919 for (e = sb->ent; e; e = e->next) {
920 if (e->guilty || !same_suspect(e->suspect, target) ||
921 ent_score(sb, e) < blame_move_score)
923 find_copy_in_blob(sb, e, parent, split, &file_p);
924 if (split[1].suspect &&
925 blame_move_score < ent_score(sb, &split[1])) {
926 split_blame(sb, split, e);
936 struct blame_entry *ent;
937 struct blame_entry split[3];
941 * Count the number of entries the target is suspected for,
942 * and prepare a list of entry and the best split.
944 static struct blame_list *setup_blame_list(struct scoreboard *sb,
945 struct origin *target,
949 struct blame_entry *e;
951 struct blame_list *blame_list = NULL;
953 for (e = sb->ent, num_ents = 0; e; e = e->next)
954 if (!e->scanned && !e->guilty &&
955 same_suspect(e->suspect, target) &&
956 min_score < ent_score(sb, e))
959 blame_list = xcalloc(num_ents, sizeof(struct blame_list));
960 for (e = sb->ent, i = 0; e; e = e->next)
961 if (!e->scanned && !e->guilty &&
962 same_suspect(e->suspect, target) &&
963 min_score < ent_score(sb, e))
964 blame_list[i++].ent = e;
966 *num_ents_p = num_ents;
971 * Reset the scanned status on all entries.
973 static void reset_scanned_flag(struct scoreboard *sb)
975 struct blame_entry *e;
976 for (e = sb->ent; e; e = e->next)
981 * For lines target is suspected for, see if we can find code movement
982 * across file boundary from the parent commit. porigin is the path
983 * in the parent we already tried.
985 static int find_copy_in_parent(struct scoreboard *sb,
986 struct origin *target,
987 struct commit *parent,
988 struct origin *porigin,
991 struct diff_options diff_opts;
992 const char *paths[1];
995 struct blame_list *blame_list;
998 blame_list = setup_blame_list(sb, target, blame_copy_score, &num_ents);
1000 return 1; /* nothing remains for this target */
1002 diff_setup(&diff_opts);
1003 DIFF_OPT_SET(&diff_opts, RECURSIVE);
1004 diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;
1007 diff_tree_setup_paths(paths, &diff_opts);
1008 if (diff_setup_done(&diff_opts) < 0)
1011 /* Try "find copies harder" on new path if requested;
1012 * we do not want to use diffcore_rename() actually to
1013 * match things up; find_copies_harder is set only to
1014 * force diff_tree_sha1() to feed all filepairs to diff_queue,
1015 * and this code needs to be after diff_setup_done(), which
1016 * usually makes find-copies-harder imply copy detection.
1018 if ((opt & PICKAXE_BLAME_COPY_HARDEST)
1019 || ((opt & PICKAXE_BLAME_COPY_HARDER)
1020 && (!porigin || strcmp(target->path, porigin->path))))
1021 DIFF_OPT_SET(&diff_opts, FIND_COPIES_HARDER);
1023 if (is_null_sha1(target->commit->object.sha1))
1024 do_diff_cache(parent->tree->object.sha1, &diff_opts);
1026 diff_tree_sha1(parent->tree->object.sha1,
1027 target->commit->tree->object.sha1,
1030 if (!DIFF_OPT_TST(&diff_opts, FIND_COPIES_HARDER))
1031 diffcore_std(&diff_opts);
1035 int made_progress = 0;
1037 for (i = 0; i < diff_queued_diff.nr; i++) {
1038 struct diff_filepair *p = diff_queued_diff.queue[i];
1039 struct origin *norigin;
1041 struct blame_entry this[3];
1043 if (!DIFF_FILE_VALID(p->one))
1044 continue; /* does not exist in parent */
1045 if (S_ISGITLINK(p->one->mode))
1046 continue; /* ignore git links */
1047 if (porigin && !strcmp(p->one->path, porigin->path))
1048 /* find_move already dealt with this path */
1051 norigin = get_origin(sb, parent, p->one->path);
1052 hashcpy(norigin->blob_sha1, p->one->sha1);
1053 fill_origin_blob(norigin, &file_p);
1057 for (j = 0; j < num_ents; j++) {
1058 find_copy_in_blob(sb, blame_list[j].ent,
1059 norigin, this, &file_p);
1060 copy_split_if_better(sb, blame_list[j].split,
1064 origin_decref(norigin);
1067 for (j = 0; j < num_ents; j++) {
1068 struct blame_entry *split = blame_list[j].split;
1069 if (split[1].suspect &&
1070 blame_copy_score < ent_score(sb, &split[1])) {
1071 split_blame(sb, split, blame_list[j].ent);
1075 blame_list[j].ent->scanned = 1;
1076 decref_split(split);
1082 blame_list = setup_blame_list(sb, target, blame_copy_score, &num_ents);
1088 reset_scanned_flag(sb);
1089 diff_flush(&diff_opts);
1090 diff_tree_release_paths(&diff_opts);
1095 * The blobs of origin and porigin exactly match, so everything
1096 * origin is suspected for can be blamed on the parent.
1098 static void pass_whole_blame(struct scoreboard *sb,
1099 struct origin *origin, struct origin *porigin)
1101 struct blame_entry *e;
1103 if (!porigin->file.ptr && origin->file.ptr) {
1104 /* Steal its file */
1105 porigin->file = origin->file;
1106 origin->file.ptr = NULL;
1108 for (e = sb->ent; e; e = e->next) {
1109 if (!same_suspect(e->suspect, origin))
1111 origin_incref(porigin);
1112 origin_decref(e->suspect);
1113 e->suspect = porigin;
1118 * We pass blame from the current commit to its parents. We keep saying
1119 * "parent" (and "porigin"), but what we mean is to find scapegoat to
1120 * exonerate ourselves.
1122 static struct commit_list *first_scapegoat(struct rev_info *revs, struct commit *commit)
1125 return commit->parents;
1126 return lookup_decoration(&revs->children, &commit->object);
1129 static int num_scapegoats(struct rev_info *revs, struct commit *commit)
1132 struct commit_list *l = first_scapegoat(revs, commit);
1133 for (cnt = 0; l; l = l->next)
1140 static void pass_blame(struct scoreboard *sb, struct origin *origin, int opt)
1142 struct rev_info *revs = sb->revs;
1143 int i, pass, num_sg;
1144 struct commit *commit = origin->commit;
1145 struct commit_list *sg;
1146 struct origin *sg_buf[MAXSG];
1147 struct origin *porigin, **sg_origin = sg_buf;
1149 num_sg = num_scapegoats(revs, commit);
1152 else if (num_sg < ARRAY_SIZE(sg_buf))
1153 memset(sg_buf, 0, sizeof(sg_buf));
1155 sg_origin = xcalloc(num_sg, sizeof(*sg_origin));
1158 * The first pass looks for unrenamed path to optimize for
1159 * common cases, then we look for renames in the second pass.
1161 for (pass = 0; pass < 2; pass++) {
1162 struct origin *(*find)(struct scoreboard *,
1163 struct commit *, struct origin *);
1164 find = pass ? find_rename : find_origin;
1166 for (i = 0, sg = first_scapegoat(revs, commit);
1168 sg = sg->next, i++) {
1169 struct commit *p = sg->item;
1174 if (parse_commit(p))
1176 porigin = find(sb, p, origin);
1179 if (!hashcmp(porigin->blob_sha1, origin->blob_sha1)) {
1180 pass_whole_blame(sb, origin, porigin);
1181 origin_decref(porigin);
1184 for (j = same = 0; j < i; j++)
1186 !hashcmp(sg_origin[j]->blob_sha1,
1187 porigin->blob_sha1)) {
1192 sg_origin[i] = porigin;
1194 origin_decref(porigin);
1199 for (i = 0, sg = first_scapegoat(revs, commit);
1201 sg = sg->next, i++) {
1202 struct origin *porigin = sg_origin[i];
1205 if (pass_blame_to_parent(sb, origin, porigin))
1210 * Optionally find moves in parents' files.
1212 if (opt & PICKAXE_BLAME_MOVE)
1213 for (i = 0, sg = first_scapegoat(revs, commit);
1215 sg = sg->next, i++) {
1216 struct origin *porigin = sg_origin[i];
1219 if (find_move_in_parent(sb, origin, porigin))
1224 * Optionally find copies from parents' files.
1226 if (opt & PICKAXE_BLAME_COPY)
1227 for (i = 0, sg = first_scapegoat(revs, commit);
1229 sg = sg->next, i++) {
1230 struct origin *porigin = sg_origin[i];
1231 if (find_copy_in_parent(sb, origin, sg->item,
1237 for (i = 0; i < num_sg; i++) {
1239 drop_origin_blob(sg_origin[i]);
1240 origin_decref(sg_origin[i]);
1243 drop_origin_blob(origin);
1244 if (sg_buf != sg_origin)
1249 * Information on commits, used for output.
1254 const char *author_mail;
1255 unsigned long author_time;
1256 const char *author_tz;
1258 /* filled only when asked for details */
1259 const char *committer;
1260 const char *committer_mail;
1261 unsigned long committer_time;
1262 const char *committer_tz;
1264 const char *summary;
1268 * Parse author/committer line in the commit object buffer
1270 static void get_ac_line(const char *inbuf, const char *what,
1271 int person_len, char *person,
1272 int mail_len, char *mail,
1273 unsigned long *time, const char **tz)
1275 int len, tzlen, maillen;
1276 char *tmp, *endp, *timepos, *mailpos;
1278 tmp = strstr(inbuf, what);
1281 tmp += strlen(what);
1282 endp = strchr(tmp, '\n');
1287 if (person_len <= len) {
1295 memcpy(person, tmp, len);
1303 tzlen = (person+len)-(tmp+1);
1308 *time = strtoul(tmp, NULL, 10);
1316 maillen = timepos - tmp;
1317 memcpy(mail, mailpos, maillen);
1323 * mailmap expansion may make the name longer.
1324 * make room by pushing stuff down.
1326 tmp = person + person_len - (tzlen + 1);
1327 memmove(tmp, *tz, tzlen);
1332 * Now, convert both name and e-mail using mailmap
1334 if(map_user(&mailmap, mail+1, mail_len-1, person, tmp-person-1)) {
1335 /* Add a trailing '>' to email, since map_user returns plain emails
1336 Note: It already has '<', since we replace from mail+1 */
1337 mailpos = memchr(mail, '\0', mail_len);
1338 if (mailpos && mailpos-mail < mail_len - 1) {
1340 *(mailpos+1) = '\0';
1345 static void get_commit_info(struct commit *commit,
1346 struct commit_info *ret,
1350 char *tmp, *endp, *reencoded, *message;
1351 static char author_name[1024];
1352 static char author_mail[1024];
1353 static char committer_name[1024];
1354 static char committer_mail[1024];
1355 static char summary_buf[1024];
1358 * We've operated without save_commit_buffer, so
1359 * we now need to populate them for output.
1361 if (!commit->buffer) {
1362 enum object_type type;
1365 read_sha1_file(commit->object.sha1, &type, &size);
1366 if (!commit->buffer)
1367 die("Cannot read commit %s",
1368 sha1_to_hex(commit->object.sha1));
1370 reencoded = reencode_commit_message(commit, NULL);
1371 message = reencoded ? reencoded : commit->buffer;
1372 ret->author = author_name;
1373 ret->author_mail = author_mail;
1374 get_ac_line(message, "\nauthor ",
1375 sizeof(author_name), author_name,
1376 sizeof(author_mail), author_mail,
1377 &ret->author_time, &ret->author_tz);
1384 ret->committer = committer_name;
1385 ret->committer_mail = committer_mail;
1386 get_ac_line(message, "\ncommitter ",
1387 sizeof(committer_name), committer_name,
1388 sizeof(committer_mail), committer_mail,
1389 &ret->committer_time, &ret->committer_tz);
1391 ret->summary = summary_buf;
1392 tmp = strstr(message, "\n\n");
1395 sprintf(summary_buf, "(%s)", sha1_to_hex(commit->object.sha1));
1400 endp = strchr(tmp, '\n');
1402 endp = tmp + strlen(tmp);
1404 if (len >= sizeof(summary_buf) || len == 0)
1406 memcpy(summary_buf, tmp, len);
1407 summary_buf[len] = 0;
1412 * To allow LF and other nonportable characters in pathnames,
1413 * they are c-style quoted as needed.
1415 static void write_filename_info(const char *path)
1417 printf("filename ");
1418 write_name_quoted(path, stdout, '\n');
1422 * The blame_entry is found to be guilty for the range. Mark it
1423 * as such, and show it in incremental output.
1425 static void found_guilty_entry(struct blame_entry *ent)
1431 struct origin *suspect = ent->suspect;
1433 printf("%s %d %d %d\n",
1434 sha1_to_hex(suspect->commit->object.sha1),
1435 ent->s_lno + 1, ent->lno + 1, ent->num_lines);
1436 if (!(suspect->commit->object.flags & METAINFO_SHOWN)) {
1437 struct commit_info ci;
1438 suspect->commit->object.flags |= METAINFO_SHOWN;
1439 get_commit_info(suspect->commit, &ci, 1);
1440 printf("author %s\n", ci.author);
1441 printf("author-mail %s\n", ci.author_mail);
1442 printf("author-time %lu\n", ci.author_time);
1443 printf("author-tz %s\n", ci.author_tz);
1444 printf("committer %s\n", ci.committer);
1445 printf("committer-mail %s\n", ci.committer_mail);
1446 printf("committer-time %lu\n", ci.committer_time);
1447 printf("committer-tz %s\n", ci.committer_tz);
1448 printf("summary %s\n", ci.summary);
1449 if (suspect->commit->object.flags & UNINTERESTING)
1450 printf("boundary\n");
1452 write_filename_info(suspect->path);
1453 maybe_flush_or_die(stdout, "stdout");
1458 * The main loop -- while the scoreboard has lines whose true origin
1459 * is still unknown, pick one blame_entry, and allow its current
1460 * suspect to pass blames to its parents.
1462 static void assign_blame(struct scoreboard *sb, int opt)
1464 struct rev_info *revs = sb->revs;
1467 struct blame_entry *ent;
1468 struct commit *commit;
1469 struct origin *suspect = NULL;
1471 /* find one suspect to break down */
1472 for (ent = sb->ent; !suspect && ent; ent = ent->next)
1474 suspect = ent->suspect;
1476 return; /* all done */
1479 * We will use this suspect later in the loop,
1480 * so hold onto it in the meantime.
1482 origin_incref(suspect);
1483 commit = suspect->commit;
1484 if (!commit->object.parsed)
1485 parse_commit(commit);
1487 (!(commit->object.flags & UNINTERESTING) &&
1488 !(revs->max_age != -1 && commit->date < revs->max_age)))
1489 pass_blame(sb, suspect, opt);
1491 commit->object.flags |= UNINTERESTING;
1492 if (commit->object.parsed)
1493 mark_parents_uninteresting(commit);
1495 /* treat root commit as boundary */
1496 if (!commit->parents && !show_root)
1497 commit->object.flags |= UNINTERESTING;
1499 /* Take responsibility for the remaining entries */
1500 for (ent = sb->ent; ent; ent = ent->next)
1501 if (same_suspect(ent->suspect, suspect))
1502 found_guilty_entry(ent);
1503 origin_decref(suspect);
1505 if (DEBUG) /* sanity */
1506 sanity_check_refcnt(sb);
1510 static const char *format_time(unsigned long time, const char *tz_str,
1513 static char time_buf[128];
1514 const char *time_str;
1518 if (show_raw_time) {
1519 sprintf(time_buf, "%lu %s", time, tz_str);
1523 time_str = show_date(time, tz, blame_date_mode);
1524 time_len = strlen(time_str);
1525 memcpy(time_buf, time_str, time_len);
1526 memset(time_buf + time_len, ' ', blame_date_width - time_len);
1531 #define OUTPUT_ANNOTATE_COMPAT 001
1532 #define OUTPUT_LONG_OBJECT_NAME 002
1533 #define OUTPUT_RAW_TIMESTAMP 004
1534 #define OUTPUT_PORCELAIN 010
1535 #define OUTPUT_SHOW_NAME 020
1536 #define OUTPUT_SHOW_NUMBER 040
1537 #define OUTPUT_SHOW_SCORE 0100
1538 #define OUTPUT_NO_AUTHOR 0200
1540 static void emit_porcelain(struct scoreboard *sb, struct blame_entry *ent)
1544 struct origin *suspect = ent->suspect;
1547 strcpy(hex, sha1_to_hex(suspect->commit->object.sha1));
1548 printf("%s%c%d %d %d\n",
1550 ent->guilty ? ' ' : '*', // purely for debugging
1554 if (!(suspect->commit->object.flags & METAINFO_SHOWN)) {
1555 struct commit_info ci;
1556 suspect->commit->object.flags |= METAINFO_SHOWN;
1557 get_commit_info(suspect->commit, &ci, 1);
1558 printf("author %s\n", ci.author);
1559 printf("author-mail %s\n", ci.author_mail);
1560 printf("author-time %lu\n", ci.author_time);
1561 printf("author-tz %s\n", ci.author_tz);
1562 printf("committer %s\n", ci.committer);
1563 printf("committer-mail %s\n", ci.committer_mail);
1564 printf("committer-time %lu\n", ci.committer_time);
1565 printf("committer-tz %s\n", ci.committer_tz);
1566 write_filename_info(suspect->path);
1567 printf("summary %s\n", ci.summary);
1568 if (suspect->commit->object.flags & UNINTERESTING)
1569 printf("boundary\n");
1571 else if (suspect->commit->object.flags & MORE_THAN_ONE_PATH)
1572 write_filename_info(suspect->path);
1574 cp = nth_line(sb, ent->lno);
1575 for (cnt = 0; cnt < ent->num_lines; cnt++) {
1578 printf("%s %d %d\n", hex,
1579 ent->s_lno + 1 + cnt,
1580 ent->lno + 1 + cnt);
1585 } while (ch != '\n' &&
1586 cp < sb->final_buf + sb->final_buf_size);
1590 static void emit_other(struct scoreboard *sb, struct blame_entry *ent, int opt)
1594 struct origin *suspect = ent->suspect;
1595 struct commit_info ci;
1597 int show_raw_time = !!(opt & OUTPUT_RAW_TIMESTAMP);
1599 get_commit_info(suspect->commit, &ci, 1);
1600 strcpy(hex, sha1_to_hex(suspect->commit->object.sha1));
1602 cp = nth_line(sb, ent->lno);
1603 for (cnt = 0; cnt < ent->num_lines; cnt++) {
1605 int length = (opt & OUTPUT_LONG_OBJECT_NAME) ? 40 : 8;
1607 if (suspect->commit->object.flags & UNINTERESTING) {
1609 memset(hex, ' ', length);
1610 else if (!(opt & OUTPUT_ANNOTATE_COMPAT)) {
1616 printf("%.*s", length, hex);
1617 if (opt & OUTPUT_ANNOTATE_COMPAT)
1618 printf("\t(%10s\t%10s\t%d)", ci.author,
1619 format_time(ci.author_time, ci.author_tz,
1621 ent->lno + 1 + cnt);
1623 if (opt & OUTPUT_SHOW_SCORE)
1625 max_score_digits, ent->score,
1626 ent->suspect->refcnt);
1627 if (opt & OUTPUT_SHOW_NAME)
1628 printf(" %-*.*s", longest_file, longest_file,
1630 if (opt & OUTPUT_SHOW_NUMBER)
1631 printf(" %*d", max_orig_digits,
1632 ent->s_lno + 1 + cnt);
1634 if (!(opt & OUTPUT_NO_AUTHOR)) {
1635 int pad = longest_author - utf8_strwidth(ci.author);
1636 printf(" (%s%*s %10s",
1638 format_time(ci.author_time,
1643 max_digits, ent->lno + 1 + cnt);
1648 } while (ch != '\n' &&
1649 cp < sb->final_buf + sb->final_buf_size);
1653 static void output(struct scoreboard *sb, int option)
1655 struct blame_entry *ent;
1657 if (option & OUTPUT_PORCELAIN) {
1658 for (ent = sb->ent; ent; ent = ent->next) {
1659 struct blame_entry *oth;
1660 struct origin *suspect = ent->suspect;
1661 struct commit *commit = suspect->commit;
1662 if (commit->object.flags & MORE_THAN_ONE_PATH)
1664 for (oth = ent->next; oth; oth = oth->next) {
1665 if ((oth->suspect->commit != commit) ||
1666 !strcmp(oth->suspect->path, suspect->path))
1668 commit->object.flags |= MORE_THAN_ONE_PATH;
1674 for (ent = sb->ent; ent; ent = ent->next) {
1675 if (option & OUTPUT_PORCELAIN)
1676 emit_porcelain(sb, ent);
1678 emit_other(sb, ent, option);
1684 * To allow quick access to the contents of nth line in the
1685 * final image, prepare an index in the scoreboard.
1687 static int prepare_lines(struct scoreboard *sb)
1689 const char *buf = sb->final_buf;
1690 unsigned long len = sb->final_buf_size;
1691 int num = 0, incomplete = 0, bol = 1;
1693 if (len && buf[len-1] != '\n')
1694 incomplete++; /* incomplete line at the end */
1697 sb->lineno = xrealloc(sb->lineno,
1698 sizeof(int* ) * (num + 1));
1699 sb->lineno[num] = buf - sb->final_buf;
1702 if (*buf++ == '\n') {
1707 sb->lineno = xrealloc(sb->lineno,
1708 sizeof(int* ) * (num + incomplete + 1));
1709 sb->lineno[num + incomplete] = buf - sb->final_buf;
1710 sb->num_lines = num + incomplete;
1711 return sb->num_lines;
1715 * Add phony grafts for use with -S; this is primarily to
1716 * support git's cvsserver that wants to give a linear history
1719 static int read_ancestry(const char *graft_file)
1721 FILE *fp = fopen(graft_file, "r");
1725 while (fgets(buf, sizeof(buf), fp)) {
1726 /* The format is just "Commit Parent1 Parent2 ...\n" */
1727 int len = strlen(buf);
1728 struct commit_graft *graft = read_graft_line(buf, len);
1730 register_commit_graft(graft, 0);
1737 * How many columns do we need to show line numbers in decimal?
1739 static int lineno_width(int lines)
1743 for (width = 1, i = 10; i <= lines + 1; width++)
1749 * How many columns do we need to show line numbers, authors,
1752 static void find_alignment(struct scoreboard *sb, int *option)
1754 int longest_src_lines = 0;
1755 int longest_dst_lines = 0;
1756 unsigned largest_score = 0;
1757 struct blame_entry *e;
1759 for (e = sb->ent; e; e = e->next) {
1760 struct origin *suspect = e->suspect;
1761 struct commit_info ci;
1764 if (strcmp(suspect->path, sb->path))
1765 *option |= OUTPUT_SHOW_NAME;
1766 num = strlen(suspect->path);
1767 if (longest_file < num)
1769 if (!(suspect->commit->object.flags & METAINFO_SHOWN)) {
1770 suspect->commit->object.flags |= METAINFO_SHOWN;
1771 get_commit_info(suspect->commit, &ci, 1);
1772 num = utf8_strwidth(ci.author);
1773 if (longest_author < num)
1774 longest_author = num;
1776 num = e->s_lno + e->num_lines;
1777 if (longest_src_lines < num)
1778 longest_src_lines = num;
1779 num = e->lno + e->num_lines;
1780 if (longest_dst_lines < num)
1781 longest_dst_lines = num;
1782 if (largest_score < ent_score(sb, e))
1783 largest_score = ent_score(sb, e);
1785 max_orig_digits = lineno_width(longest_src_lines);
1786 max_digits = lineno_width(longest_dst_lines);
1787 max_score_digits = lineno_width(largest_score);
1791 * For debugging -- origin is refcounted, and this asserts that
1792 * we do not underflow.
1794 static void sanity_check_refcnt(struct scoreboard *sb)
1797 struct blame_entry *ent;
1799 for (ent = sb->ent; ent; ent = ent->next) {
1800 /* Nobody should have zero or negative refcnt */
1801 if (ent->suspect->refcnt <= 0) {
1802 fprintf(stderr, "%s in %s has negative refcnt %d\n",
1804 sha1_to_hex(ent->suspect->commit->object.sha1),
1805 ent->suspect->refcnt);
1809 for (ent = sb->ent; ent; ent = ent->next) {
1810 /* Mark the ones that haven't been checked */
1811 if (0 < ent->suspect->refcnt)
1812 ent->suspect->refcnt = -ent->suspect->refcnt;
1814 for (ent = sb->ent; ent; ent = ent->next) {
1816 * ... then pick each and see if they have the the
1820 struct blame_entry *e;
1821 struct origin *suspect = ent->suspect;
1823 if (0 < suspect->refcnt)
1825 suspect->refcnt = -suspect->refcnt; /* Unmark */
1826 for (found = 0, e = sb->ent; e; e = e->next) {
1827 if (e->suspect != suspect)
1831 if (suspect->refcnt != found) {
1832 fprintf(stderr, "%s in %s has refcnt %d, not %d\n",
1834 sha1_to_hex(ent->suspect->commit->object.sha1),
1835 ent->suspect->refcnt, found);
1841 find_alignment(sb, &opt);
1843 die("Baa %d!", baa);
1848 * Used for the command line parsing; check if the path exists
1849 * in the working tree.
1851 static int has_string_in_work_tree(const char *path)
1854 return !lstat(path, &st);
1857 static unsigned parse_score(const char *arg)
1860 unsigned long score = strtoul(arg, &end, 10);
1866 static const char *add_prefix(const char *prefix, const char *path)
1868 return prefix_path(prefix, prefix ? strlen(prefix) : 0, path);
1872 * Parsing of (comma separated) one item in the -L option
1874 static const char *parse_loc(const char *spec,
1875 struct scoreboard *sb, long lno,
1876 long begin, long *ret)
1883 regmatch_t match[1];
1885 /* Allow "-L <something>,+20" to mean starting at <something>
1886 * for 20 lines, or "-L <something>,-5" for 5 lines ending at
1889 if (1 < begin && (spec[0] == '+' || spec[0] == '-')) {
1890 num = strtol(spec + 1, &term, 10);
1891 if (term != spec + 1) {
1895 *ret = begin + num - 2;
1904 num = strtol(spec, &term, 10);
1912 /* it could be a regexp of form /.../ */
1913 for (term = (char*) spec + 1; *term && *term != '/'; term++) {
1920 /* try [spec+1 .. term-1] as regexp */
1922 begin--; /* input is in human terms */
1923 line = nth_line(sb, begin);
1925 if (!(reg_error = regcomp(®exp, spec + 1, REG_NEWLINE)) &&
1926 !(reg_error = regexec(®exp, line, 1, match, 0))) {
1927 const char *cp = line + match[0].rm_so;
1930 while (begin++ < lno) {
1931 nline = nth_line(sb, begin);
1932 if (line <= cp && cp < nline)
1943 regerror(reg_error, ®exp, errbuf, 1024);
1944 die("-L parameter '%s': %s", spec + 1, errbuf);
1949 * Parsing of -L option
1951 static void prepare_blame_range(struct scoreboard *sb,
1952 const char *bottomtop,
1954 long *bottom, long *top)
1958 term = parse_loc(bottomtop, sb, lno, 1, bottom);
1960 term = parse_loc(term + 1, sb, lno, *bottom + 1, top);
1968 static int git_blame_config(const char *var, const char *value, void *cb)
1970 if (!strcmp(var, "blame.showroot")) {
1971 show_root = git_config_bool(var, value);
1974 if (!strcmp(var, "blame.blankboundary")) {
1975 blank_boundary = git_config_bool(var, value);
1978 if (!strcmp(var, "blame.date")) {
1980 return config_error_nonbool(var);
1981 blame_date_mode = parse_date_format(value);
1984 return git_default_config(var, value, cb);
1988 * Prepare a dummy commit that represents the work tree (or staged) item.
1989 * Note that annotating work tree item never works in the reverse.
1991 static struct commit *fake_working_tree_commit(const char *path, const char *contents_from)
1993 struct commit *commit;
1994 struct origin *origin;
1995 unsigned char head_sha1[20];
1996 struct strbuf buf = STRBUF_INIT;
2000 struct cache_entry *ce;
2003 if (get_sha1("HEAD", head_sha1))
2004 die("No such ref: HEAD");
2007 commit = xcalloc(1, sizeof(*commit));
2008 commit->parents = xcalloc(1, sizeof(*commit->parents));
2009 commit->parents->item = lookup_commit_reference(head_sha1);
2010 commit->object.parsed = 1;
2012 commit->object.type = OBJ_COMMIT;
2014 origin = make_origin(commit, path);
2016 if (!contents_from || strcmp("-", contents_from)) {
2018 const char *read_from;
2020 if (contents_from) {
2021 if (stat(contents_from, &st) < 0)
2022 die("Cannot stat %s", contents_from);
2023 read_from = contents_from;
2026 if (lstat(path, &st) < 0)
2027 die("Cannot lstat %s", path);
2030 mode = canon_mode(st.st_mode);
2031 switch (st.st_mode & S_IFMT) {
2033 if (strbuf_read_file(&buf, read_from, st.st_size) != st.st_size)
2034 die("cannot open or read %s", read_from);
2037 if (strbuf_readlink(&buf, read_from, st.st_size) < 0)
2038 die("cannot readlink %s", read_from);
2041 die("unsupported file type %s", read_from);
2045 /* Reading from stdin */
2046 contents_from = "standard input";
2048 if (strbuf_read(&buf, 0, 0) < 0)
2049 die("read error %s from stdin", strerror(errno));
2051 convert_to_git(path, buf.buf, buf.len, &buf, 0);
2052 origin->file.ptr = buf.buf;
2053 origin->file.size = buf.len;
2054 pretend_sha1_file(buf.buf, buf.len, OBJ_BLOB, origin->blob_sha1);
2055 commit->util = origin;
2058 * Read the current index, replace the path entry with
2059 * origin->blob_sha1 without mucking with its mode or type
2060 * bits; we are not going to write this index out -- we just
2061 * want to run "diff-index --cached".
2068 int pos = cache_name_pos(path, len);
2070 mode = active_cache[pos]->ce_mode;
2072 /* Let's not bother reading from HEAD tree */
2073 mode = S_IFREG | 0644;
2075 size = cache_entry_size(len);
2076 ce = xcalloc(1, size);
2077 hashcpy(ce->sha1, origin->blob_sha1);
2078 memcpy(ce->name, path, len);
2079 ce->ce_flags = create_ce_flags(len, 0);
2080 ce->ce_mode = create_ce_mode(mode);
2081 add_cache_entry(ce, ADD_CACHE_OK_TO_ADD|ADD_CACHE_OK_TO_REPLACE);
2084 * We are not going to write this out, so this does not matter
2085 * right now, but someday we might optimize diff-index --cached
2086 * with cache-tree information.
2088 cache_tree_invalidate_path(active_cache_tree, path);
2090 commit->buffer = xmalloc(400);
2091 ident = fmt_ident("Not Committed Yet", "not.committed.yet", NULL, 0);
2092 snprintf(commit->buffer, 400,
2093 "tree 0000000000000000000000000000000000000000\n"
2097 "Version of %s from %s\n",
2098 sha1_to_hex(head_sha1),
2099 ident, ident, path, contents_from ? contents_from : path);
2103 static const char *prepare_final(struct scoreboard *sb)
2106 const char *final_commit_name = NULL;
2107 struct rev_info *revs = sb->revs;
2110 * There must be one and only one positive commit in the
2111 * revs->pending array.
2113 for (i = 0; i < revs->pending.nr; i++) {
2114 struct object *obj = revs->pending.objects[i].item;
2115 if (obj->flags & UNINTERESTING)
2117 while (obj->type == OBJ_TAG)
2118 obj = deref_tag(obj, NULL, 0);
2119 if (obj->type != OBJ_COMMIT)
2120 die("Non commit %s?", revs->pending.objects[i].name);
2122 die("More than one commit to dig from %s and %s?",
2123 revs->pending.objects[i].name,
2125 sb->final = (struct commit *) obj;
2126 final_commit_name = revs->pending.objects[i].name;
2128 return final_commit_name;
2131 static const char *prepare_initial(struct scoreboard *sb)
2134 const char *final_commit_name = NULL;
2135 struct rev_info *revs = sb->revs;
2138 * There must be one and only one negative commit, and it must be
2141 for (i = 0; i < revs->pending.nr; i++) {
2142 struct object *obj = revs->pending.objects[i].item;
2143 if (!(obj->flags & UNINTERESTING))
2145 while (obj->type == OBJ_TAG)
2146 obj = deref_tag(obj, NULL, 0);
2147 if (obj->type != OBJ_COMMIT)
2148 die("Non commit %s?", revs->pending.objects[i].name);
2150 die("More than one commit to dig down to %s and %s?",
2151 revs->pending.objects[i].name,
2153 sb->final = (struct commit *) obj;
2154 final_commit_name = revs->pending.objects[i].name;
2156 if (!final_commit_name)
2157 die("No commit to dig down to?");
2158 return final_commit_name;
2161 static int blame_copy_callback(const struct option *option, const char *arg, int unset)
2163 int *opt = option->value;
2166 * -C enables copy from removed files;
2167 * -C -C enables copy from existing files, but only
2168 * when blaming a new file;
2169 * -C -C -C enables copy from existing files for
2172 if (*opt & PICKAXE_BLAME_COPY_HARDER)
2173 *opt |= PICKAXE_BLAME_COPY_HARDEST;
2174 if (*opt & PICKAXE_BLAME_COPY)
2175 *opt |= PICKAXE_BLAME_COPY_HARDER;
2176 *opt |= PICKAXE_BLAME_COPY | PICKAXE_BLAME_MOVE;
2179 blame_copy_score = parse_score(arg);
2183 static int blame_move_callback(const struct option *option, const char *arg, int unset)
2185 int *opt = option->value;
2187 *opt |= PICKAXE_BLAME_MOVE;
2190 blame_move_score = parse_score(arg);
2194 static int blame_bottomtop_callback(const struct option *option, const char *arg, int unset)
2196 const char **bottomtop = option->value;
2200 die("More than one '-L n,m' option given");
2205 int cmd_blame(int argc, const char **argv, const char *prefix)
2207 struct rev_info revs;
2209 struct scoreboard sb;
2211 struct blame_entry *ent;
2212 long dashdash_pos, bottom, top, lno;
2213 const char *final_commit_name = NULL;
2214 enum object_type type;
2216 static const char *bottomtop = NULL;
2217 static int output_option = 0, opt = 0;
2218 static int show_stats = 0;
2219 static const char *revs_file = NULL;
2220 static const char *contents_from = NULL;
2221 static const struct option options[] = {
2222 OPT_BOOLEAN(0, "incremental", &incremental, "Show blame entries as we find them, incrementally"),
2223 OPT_BOOLEAN('b', NULL, &blank_boundary, "Show blank SHA-1 for boundary commits (Default: off)"),
2224 OPT_BOOLEAN(0, "root", &show_root, "Do not treat root commits as boundaries (Default: off)"),
2225 OPT_BOOLEAN(0, "show-stats", &show_stats, "Show work cost statistics"),
2226 OPT_BIT(0, "score-debug", &output_option, "Show output score for blame entries", OUTPUT_SHOW_SCORE),
2227 OPT_BIT('f', "show-name", &output_option, "Show original filename (Default: auto)", OUTPUT_SHOW_NAME),
2228 OPT_BIT('n', "show-number", &output_option, "Show original linenumber (Default: off)", OUTPUT_SHOW_NUMBER),
2229 OPT_BIT('p', "porcelain", &output_option, "Show in a format designed for machine consumption", OUTPUT_PORCELAIN),
2230 OPT_BIT('c', NULL, &output_option, "Use the same output mode as git-annotate (Default: off)", OUTPUT_ANNOTATE_COMPAT),
2231 OPT_BIT('t', NULL, &output_option, "Show raw timestamp (Default: off)", OUTPUT_RAW_TIMESTAMP),
2232 OPT_BIT('l', NULL, &output_option, "Show long commit SHA1 (Default: off)", OUTPUT_LONG_OBJECT_NAME),
2233 OPT_BIT('s', NULL, &output_option, "Suppress author name and timestamp (Default: off)", OUTPUT_NO_AUTHOR),
2234 OPT_BIT('w', NULL, &xdl_opts, "Ignore whitespace differences", XDF_IGNORE_WHITESPACE),
2235 OPT_STRING('S', NULL, &revs_file, "file", "Use revisions from <file> instead of calling git-rev-list"),
2236 OPT_STRING(0, "contents", &contents_from, "file", "Use <file>'s contents as the final image"),
2237 { OPTION_CALLBACK, 'C', NULL, &opt, "score", "Find line copies within and across files", PARSE_OPT_OPTARG, blame_copy_callback },
2238 { OPTION_CALLBACK, 'M', NULL, &opt, "score", "Find line movements within and across files", PARSE_OPT_OPTARG, blame_move_callback },
2239 OPT_CALLBACK('L', NULL, &bottomtop, "n,m", "Process only line range n,m, counting from 1", blame_bottomtop_callback),
2243 struct parse_opt_ctx_t ctx;
2244 int cmd_is_annotate = !strcmp(argv[0], "annotate");
2246 git_config(git_blame_config, NULL);
2247 init_revisions(&revs, NULL);
2248 revs.date_mode = blame_date_mode;
2250 save_commit_buffer = 0;
2253 parse_options_start(&ctx, argc, argv, PARSE_OPT_KEEP_DASHDASH |
2254 PARSE_OPT_KEEP_ARGV0);
2256 switch (parse_options_step(&ctx, options, blame_opt_usage)) {
2257 case PARSE_OPT_HELP:
2259 case PARSE_OPT_DONE:
2261 dashdash_pos = ctx.cpidx;
2265 if (!strcmp(ctx.argv[0], "--reverse")) {
2266 ctx.argv[0] = "--children";
2269 parse_revision_opt(&revs, &ctx, options, blame_opt_usage);
2272 argc = parse_options_end(&ctx);
2274 if (cmd_is_annotate) {
2275 output_option |= OUTPUT_ANNOTATE_COMPAT;
2276 blame_date_mode = DATE_ISO8601;
2278 blame_date_mode = revs.date_mode;
2281 /* The maximum width used to show the dates */
2282 switch (blame_date_mode) {
2284 blame_date_width = sizeof("Thu, 19 Oct 2006 16:00:04 -0700");
2287 blame_date_width = sizeof("2006-10-19 16:00:04 -0700");
2290 blame_date_width = sizeof("1161298804 -0700");
2293 blame_date_width = sizeof("2006-10-19");
2296 /* "normal" is used as the fallback for "relative" */
2299 blame_date_width = sizeof("Thu Oct 19 16:00:04 2006 -0700");
2302 blame_date_width -= 1; /* strip the null */
2304 if (DIFF_OPT_TST(&revs.diffopt, FIND_COPIES_HARDER))
2305 opt |= (PICKAXE_BLAME_COPY | PICKAXE_BLAME_MOVE |
2306 PICKAXE_BLAME_COPY_HARDER);
2308 if (!blame_move_score)
2309 blame_move_score = BLAME_DEFAULT_MOVE_SCORE;
2310 if (!blame_copy_score)
2311 blame_copy_score = BLAME_DEFAULT_COPY_SCORE;
2314 * We have collected options unknown to us in argv[1..unk]
2315 * which are to be passed to revision machinery if we are
2316 * going to do the "bottom" processing.
2318 * The remaining are:
2320 * (1) if dashdash_pos != 0, its either
2321 * "blame [revisions] -- <path>" or
2322 * "blame -- <path> <rev>"
2324 * (2) otherwise, its one of the two:
2325 * "blame [revisions] <path>"
2326 * "blame <path> <rev>"
2328 * Note that we must strip out <path> from the arguments: we do not
2329 * want the path pruning but we may want "bottom" processing.
2332 switch (argc - dashdash_pos - 1) {
2335 usage_with_options(blame_opt_usage, options);
2336 /* reorder for the new way: <rev> -- <path> */
2342 path = add_prefix(prefix, argv[--argc]);
2346 usage_with_options(blame_opt_usage, options);
2350 usage_with_options(blame_opt_usage, options);
2351 path = add_prefix(prefix, argv[argc - 1]);
2352 if (argc == 3 && !has_string_in_work_tree(path)) { /* (2b) */
2353 path = add_prefix(prefix, argv[1]);
2356 argv[argc - 1] = "--";
2359 if (!has_string_in_work_tree(path))
2360 die("cannot stat path %s: %s", path, strerror(errno));
2363 setup_revisions(argc, argv, &revs, NULL);
2364 memset(&sb, 0, sizeof(sb));
2368 final_commit_name = prepare_final(&sb);
2369 else if (contents_from)
2370 die("--contents and --children do not blend well.");
2372 final_commit_name = prepare_initial(&sb);
2376 * "--not A B -- path" without anything positive;
2377 * do not default to HEAD, but use the working tree
2381 sb.final = fake_working_tree_commit(path, contents_from);
2382 add_pending_object(&revs, &(sb.final->object), ":");
2384 else if (contents_from)
2385 die("Cannot use --contents with final commit object name");
2388 * If we have bottom, this will mark the ancestors of the
2389 * bottom commits we would reach while traversing as
2392 if (prepare_revision_walk(&revs))
2393 die("revision walk setup failed");
2395 if (is_null_sha1(sb.final->object.sha1)) {
2398 buf = xmalloc(o->file.size + 1);
2399 memcpy(buf, o->file.ptr, o->file.size + 1);
2401 sb.final_buf_size = o->file.size;
2404 o = get_origin(&sb, sb.final, path);
2405 if (fill_blob_sha1(o))
2406 die("no such path %s in %s", path, final_commit_name);
2408 sb.final_buf = read_sha1_file(o->blob_sha1, &type,
2409 &sb.final_buf_size);
2411 die("Cannot read blob %s for path %s",
2412 sha1_to_hex(o->blob_sha1),
2416 lno = prepare_lines(&sb);
2420 prepare_blame_range(&sb, bottomtop, lno, &bottom, &top);
2421 if (bottom && top && top < bottom) {
2423 tmp = top; top = bottom; bottom = tmp;
2431 die("file %s has only %lu lines", path, lno);
2433 ent = xcalloc(1, sizeof(*ent));
2435 ent->num_lines = top - bottom;
2437 ent->s_lno = bottom;
2442 if (revs_file && read_ancestry(revs_file))
2443 die("reading graft file %s failed: %s",
2444 revs_file, strerror(errno));
2446 read_mailmap(&mailmap, NULL);
2451 assign_blame(&sb, opt);
2458 if (!(output_option & OUTPUT_PORCELAIN))
2459 find_alignment(&sb, &output_option);
2461 output(&sb, output_option);
2462 free((void *)sb.final_buf);
2463 for (ent = sb.ent; ent; ) {
2464 struct blame_entry *e = ent->next;
2470 printf("num read blob: %d\n", num_read_blob);
2471 printf("num get patch: %d\n", num_get_patch);
2472 printf("num commits: %d\n", num_commits);