diff: do not use null sha1 as a sentinel value
[git/jnareb-git.git] / builtin / blame.c
blobfac0e93e67eeee8bef709670da1cbfe77055137d
1 /*
2 * Blame
4 * Copyright (c) 2006, Junio C Hamano
5 */
7 #include "cache.h"
8 #include "builtin.h"
9 #include "blob.h"
10 #include "commit.h"
11 #include "tag.h"
12 #include "tree-walk.h"
13 #include "diff.h"
14 #include "diffcore.h"
15 #include "revision.h"
16 #include "quote.h"
17 #include "xdiff-interface.h"
18 #include "cache-tree.h"
19 #include "string-list.h"
20 #include "mailmap.h"
21 #include "parse-options.h"
22 #include "utf8.h"
23 #include "userdiff.h"
25 static char blame_usage[] = "git blame [options] [rev-opts] [rev] [--] file";
27 static const char *blame_opt_usage[] = {
28 blame_usage,
29 "",
30 "[rev-opts] are documented in git-rev-list(1)",
31 NULL
34 static int longest_file;
35 static int longest_author;
36 static int max_orig_digits;
37 static int max_digits;
38 static int max_score_digits;
39 static int show_root;
40 static int reverse;
41 static int blank_boundary;
42 static int incremental;
43 static int xdl_opts;
44 static int abbrev = -1;
46 static enum date_mode blame_date_mode = DATE_ISO8601;
47 static size_t blame_date_width;
49 static struct string_list mailmap;
51 #ifndef DEBUG
52 #define DEBUG 0
53 #endif
55 /* stats */
56 static int num_read_blob;
57 static int num_get_patch;
58 static int num_commits;
60 #define PICKAXE_BLAME_MOVE 01
61 #define PICKAXE_BLAME_COPY 02
62 #define PICKAXE_BLAME_COPY_HARDER 04
63 #define PICKAXE_BLAME_COPY_HARDEST 010
66 * blame for a blame_entry with score lower than these thresholds
67 * is not passed to the parent using move/copy logic.
69 static unsigned blame_move_score;
70 static unsigned blame_copy_score;
71 #define BLAME_DEFAULT_MOVE_SCORE 20
72 #define BLAME_DEFAULT_COPY_SCORE 40
74 /* bits #0..7 in revision.h, #8..11 used for merge_bases() in commit.c */
75 #define METAINFO_SHOWN (1u<<12)
76 #define MORE_THAN_ONE_PATH (1u<<13)
79 * One blob in a commit that is being suspected
81 struct origin {
82 int refcnt;
83 struct origin *previous;
84 struct commit *commit;
85 mmfile_t file;
86 unsigned char blob_sha1[20];
87 unsigned mode;
88 char path[FLEX_ARRAY];
92 * Prepare diff_filespec and convert it using diff textconv API
93 * if the textconv driver exists.
94 * Return 1 if the conversion succeeds, 0 otherwise.
96 int textconv_object(const char *path,
97 unsigned mode,
98 const unsigned char *sha1,
99 int sha1_valid,
100 char **buf,
101 unsigned long *buf_size)
103 struct diff_filespec *df;
104 struct userdiff_driver *textconv;
106 df = alloc_filespec(path);
107 fill_filespec(df, sha1, sha1_valid, mode);
108 textconv = get_textconv(df);
109 if (!textconv) {
110 free_filespec(df);
111 return 0;
114 *buf_size = fill_textconv(textconv, df, buf);
115 free_filespec(df);
116 return 1;
120 * Given an origin, prepare mmfile_t structure to be used by the
121 * diff machinery
123 static void fill_origin_blob(struct diff_options *opt,
124 struct origin *o, mmfile_t *file)
126 if (!o->file.ptr) {
127 enum object_type type;
128 unsigned long file_size;
130 num_read_blob++;
131 if (DIFF_OPT_TST(opt, ALLOW_TEXTCONV) &&
132 textconv_object(o->path, o->mode, o->blob_sha1, 1, &file->ptr, &file_size))
134 else
135 file->ptr = read_sha1_file(o->blob_sha1, &type, &file_size);
136 file->size = file_size;
138 if (!file->ptr)
139 die("Cannot read blob %s for path %s",
140 sha1_to_hex(o->blob_sha1),
141 o->path);
142 o->file = *file;
144 else
145 *file = o->file;
149 * Origin is refcounted and usually we keep the blob contents to be
150 * reused.
152 static inline struct origin *origin_incref(struct origin *o)
154 if (o)
155 o->refcnt++;
156 return o;
159 static void origin_decref(struct origin *o)
161 if (o && --o->refcnt <= 0) {
162 if (o->previous)
163 origin_decref(o->previous);
164 free(o->file.ptr);
165 free(o);
169 static void drop_origin_blob(struct origin *o)
171 if (o->file.ptr) {
172 free(o->file.ptr);
173 o->file.ptr = NULL;
178 * Each group of lines is described by a blame_entry; it can be split
179 * as we pass blame to the parents. They form a linked list in the
180 * scoreboard structure, sorted by the target line number.
182 struct blame_entry {
183 struct blame_entry *prev;
184 struct blame_entry *next;
186 /* the first line of this group in the final image;
187 * internally all line numbers are 0 based.
189 int lno;
191 /* how many lines this group has */
192 int num_lines;
194 /* the commit that introduced this group into the final image */
195 struct origin *suspect;
197 /* true if the suspect is truly guilty; false while we have not
198 * checked if the group came from one of its parents.
200 char guilty;
202 /* true if the entry has been scanned for copies in the current parent
204 char scanned;
206 /* the line number of the first line of this group in the
207 * suspect's file; internally all line numbers are 0 based.
209 int s_lno;
211 /* how significant this entry is -- cached to avoid
212 * scanning the lines over and over.
214 unsigned score;
218 * The current state of the blame assignment.
220 struct scoreboard {
221 /* the final commit (i.e. where we started digging from) */
222 struct commit *final;
223 struct rev_info *revs;
224 const char *path;
227 * The contents in the final image.
228 * Used by many functions to obtain contents of the nth line,
229 * indexed with scoreboard.lineno[blame_entry.lno].
231 const char *final_buf;
232 unsigned long final_buf_size;
234 /* linked list of blames */
235 struct blame_entry *ent;
237 /* look-up a line in the final buffer */
238 int num_lines;
239 int *lineno;
242 static inline int same_suspect(struct origin *a, struct origin *b)
244 if (a == b)
245 return 1;
246 if (a->commit != b->commit)
247 return 0;
248 return !strcmp(a->path, b->path);
251 static void sanity_check_refcnt(struct scoreboard *);
254 * If two blame entries that are next to each other came from
255 * contiguous lines in the same origin (i.e. <commit, path> pair),
256 * merge them together.
258 static void coalesce(struct scoreboard *sb)
260 struct blame_entry *ent, *next;
262 for (ent = sb->ent; ent && (next = ent->next); ent = next) {
263 if (same_suspect(ent->suspect, next->suspect) &&
264 ent->guilty == next->guilty &&
265 ent->s_lno + ent->num_lines == next->s_lno) {
266 ent->num_lines += next->num_lines;
267 ent->next = next->next;
268 if (ent->next)
269 ent->next->prev = ent;
270 origin_decref(next->suspect);
271 free(next);
272 ent->score = 0;
273 next = ent; /* again */
277 if (DEBUG) /* sanity */
278 sanity_check_refcnt(sb);
282 * Given a commit and a path in it, create a new origin structure.
283 * The callers that add blame to the scoreboard should use
284 * get_origin() to obtain shared, refcounted copy instead of calling
285 * this function directly.
287 static struct origin *make_origin(struct commit *commit, const char *path)
289 struct origin *o;
290 o = xcalloc(1, sizeof(*o) + strlen(path) + 1);
291 o->commit = commit;
292 o->refcnt = 1;
293 strcpy(o->path, path);
294 return o;
298 * Locate an existing origin or create a new one.
300 static struct origin *get_origin(struct scoreboard *sb,
301 struct commit *commit,
302 const char *path)
304 struct blame_entry *e;
306 for (e = sb->ent; e; e = e->next) {
307 if (e->suspect->commit == commit &&
308 !strcmp(e->suspect->path, path))
309 return origin_incref(e->suspect);
311 return make_origin(commit, path);
315 * Fill the blob_sha1 field of an origin if it hasn't, so that later
316 * call to fill_origin_blob() can use it to locate the data. blob_sha1
317 * for an origin is also used to pass the blame for the entire file to
318 * the parent to detect the case where a child's blob is identical to
319 * that of its parent's.
321 * This also fills origin->mode for corresponding tree path.
323 static int fill_blob_sha1_and_mode(struct origin *origin)
325 if (!is_null_sha1(origin->blob_sha1))
326 return 0;
327 if (get_tree_entry(origin->commit->object.sha1,
328 origin->path,
329 origin->blob_sha1, &origin->mode))
330 goto error_out;
331 if (sha1_object_info(origin->blob_sha1, NULL) != OBJ_BLOB)
332 goto error_out;
333 return 0;
334 error_out:
335 hashclr(origin->blob_sha1);
336 origin->mode = S_IFINVALID;
337 return -1;
341 * We have an origin -- check if the same path exists in the
342 * parent and return an origin structure to represent it.
344 static struct origin *find_origin(struct scoreboard *sb,
345 struct commit *parent,
346 struct origin *origin)
348 struct origin *porigin = NULL;
349 struct diff_options diff_opts;
350 const char *paths[2];
352 if (parent->util) {
354 * Each commit object can cache one origin in that
355 * commit. This is a freestanding copy of origin and
356 * not refcounted.
358 struct origin *cached = parent->util;
359 if (!strcmp(cached->path, origin->path)) {
361 * The same path between origin and its parent
362 * without renaming -- the most common case.
364 porigin = get_origin(sb, parent, cached->path);
367 * If the origin was newly created (i.e. get_origin
368 * would call make_origin if none is found in the
369 * scoreboard), it does not know the blob_sha1/mode,
370 * so copy it. Otherwise porigin was in the
371 * scoreboard and already knows blob_sha1/mode.
373 if (porigin->refcnt == 1) {
374 hashcpy(porigin->blob_sha1, cached->blob_sha1);
375 porigin->mode = cached->mode;
377 return porigin;
379 /* otherwise it was not very useful; free it */
380 free(parent->util);
381 parent->util = NULL;
384 /* See if the origin->path is different between parent
385 * and origin first. Most of the time they are the
386 * same and diff-tree is fairly efficient about this.
388 diff_setup(&diff_opts);
389 DIFF_OPT_SET(&diff_opts, RECURSIVE);
390 diff_opts.detect_rename = 0;
391 diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;
392 paths[0] = origin->path;
393 paths[1] = NULL;
395 diff_tree_setup_paths(paths, &diff_opts);
396 if (diff_setup_done(&diff_opts) < 0)
397 die("diff-setup");
399 if (is_null_sha1(origin->commit->object.sha1))
400 do_diff_cache(parent->tree->object.sha1, &diff_opts);
401 else
402 diff_tree_sha1(parent->tree->object.sha1,
403 origin->commit->tree->object.sha1,
404 "", &diff_opts);
405 diffcore_std(&diff_opts);
407 if (!diff_queued_diff.nr) {
408 /* The path is the same as parent */
409 porigin = get_origin(sb, parent, origin->path);
410 hashcpy(porigin->blob_sha1, origin->blob_sha1);
411 porigin->mode = origin->mode;
412 } else {
414 * Since origin->path is a pathspec, if the parent
415 * commit had it as a directory, we will see a whole
416 * bunch of deletion of files in the directory that we
417 * do not care about.
419 int i;
420 struct diff_filepair *p = NULL;
421 for (i = 0; i < diff_queued_diff.nr; i++) {
422 const char *name;
423 p = diff_queued_diff.queue[i];
424 name = p->one->path ? p->one->path : p->two->path;
425 if (!strcmp(name, origin->path))
426 break;
428 if (!p)
429 die("internal error in blame::find_origin");
430 switch (p->status) {
431 default:
432 die("internal error in blame::find_origin (%c)",
433 p->status);
434 case 'M':
435 porigin = get_origin(sb, parent, origin->path);
436 hashcpy(porigin->blob_sha1, p->one->sha1);
437 porigin->mode = p->one->mode;
438 break;
439 case 'A':
440 case 'T':
441 /* Did not exist in parent, or type changed */
442 break;
445 diff_flush(&diff_opts);
446 diff_tree_release_paths(&diff_opts);
447 if (porigin) {
449 * Create a freestanding copy that is not part of
450 * the refcounted origin found in the scoreboard, and
451 * cache it in the commit.
453 struct origin *cached;
455 cached = make_origin(porigin->commit, porigin->path);
456 hashcpy(cached->blob_sha1, porigin->blob_sha1);
457 cached->mode = porigin->mode;
458 parent->util = cached;
460 return porigin;
464 * We have an origin -- find the path that corresponds to it in its
465 * parent and return an origin structure to represent it.
467 static struct origin *find_rename(struct scoreboard *sb,
468 struct commit *parent,
469 struct origin *origin)
471 struct origin *porigin = NULL;
472 struct diff_options diff_opts;
473 int i;
474 const char *paths[2];
476 diff_setup(&diff_opts);
477 DIFF_OPT_SET(&diff_opts, RECURSIVE);
478 diff_opts.detect_rename = DIFF_DETECT_RENAME;
479 diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;
480 diff_opts.single_follow = origin->path;
481 paths[0] = NULL;
482 diff_tree_setup_paths(paths, &diff_opts);
483 if (diff_setup_done(&diff_opts) < 0)
484 die("diff-setup");
486 if (is_null_sha1(origin->commit->object.sha1))
487 do_diff_cache(parent->tree->object.sha1, &diff_opts);
488 else
489 diff_tree_sha1(parent->tree->object.sha1,
490 origin->commit->tree->object.sha1,
491 "", &diff_opts);
492 diffcore_std(&diff_opts);
494 for (i = 0; i < diff_queued_diff.nr; i++) {
495 struct diff_filepair *p = diff_queued_diff.queue[i];
496 if ((p->status == 'R' || p->status == 'C') &&
497 !strcmp(p->two->path, origin->path)) {
498 porigin = get_origin(sb, parent, p->one->path);
499 hashcpy(porigin->blob_sha1, p->one->sha1);
500 porigin->mode = p->one->mode;
501 break;
504 diff_flush(&diff_opts);
505 diff_tree_release_paths(&diff_opts);
506 return porigin;
510 * Link in a new blame entry to the scoreboard. Entries that cover the
511 * same line range have been removed from the scoreboard previously.
513 static void add_blame_entry(struct scoreboard *sb, struct blame_entry *e)
515 struct blame_entry *ent, *prev = NULL;
517 origin_incref(e->suspect);
519 for (ent = sb->ent; ent && ent->lno < e->lno; ent = ent->next)
520 prev = ent;
522 /* prev, if not NULL, is the last one that is below e */
523 e->prev = prev;
524 if (prev) {
525 e->next = prev->next;
526 prev->next = e;
528 else {
529 e->next = sb->ent;
530 sb->ent = e;
532 if (e->next)
533 e->next->prev = e;
537 * src typically is on-stack; we want to copy the information in it to
538 * a malloced blame_entry that is already on the linked list of the
539 * scoreboard. The origin of dst loses a refcnt while the origin of src
540 * gains one.
542 static void dup_entry(struct blame_entry *dst, struct blame_entry *src)
544 struct blame_entry *p, *n;
546 p = dst->prev;
547 n = dst->next;
548 origin_incref(src->suspect);
549 origin_decref(dst->suspect);
550 memcpy(dst, src, sizeof(*src));
551 dst->prev = p;
552 dst->next = n;
553 dst->score = 0;
556 static const char *nth_line(struct scoreboard *sb, int lno)
558 return sb->final_buf + sb->lineno[lno];
562 * It is known that lines between tlno to same came from parent, and e
563 * has an overlap with that range. it also is known that parent's
564 * line plno corresponds to e's line tlno.
566 * <---- e ----->
567 * <------>
568 * <------------>
569 * <------------>
570 * <------------------>
572 * Split e into potentially three parts; before this chunk, the chunk
573 * to be blamed for the parent, and after that portion.
575 static void split_overlap(struct blame_entry *split,
576 struct blame_entry *e,
577 int tlno, int plno, int same,
578 struct origin *parent)
580 int chunk_end_lno;
581 memset(split, 0, sizeof(struct blame_entry [3]));
583 if (e->s_lno < tlno) {
584 /* there is a pre-chunk part not blamed on parent */
585 split[0].suspect = origin_incref(e->suspect);
586 split[0].lno = e->lno;
587 split[0].s_lno = e->s_lno;
588 split[0].num_lines = tlno - e->s_lno;
589 split[1].lno = e->lno + tlno - e->s_lno;
590 split[1].s_lno = plno;
592 else {
593 split[1].lno = e->lno;
594 split[1].s_lno = plno + (e->s_lno - tlno);
597 if (same < e->s_lno + e->num_lines) {
598 /* there is a post-chunk part not blamed on parent */
599 split[2].suspect = origin_incref(e->suspect);
600 split[2].lno = e->lno + (same - e->s_lno);
601 split[2].s_lno = e->s_lno + (same - e->s_lno);
602 split[2].num_lines = e->s_lno + e->num_lines - same;
603 chunk_end_lno = split[2].lno;
605 else
606 chunk_end_lno = e->lno + e->num_lines;
607 split[1].num_lines = chunk_end_lno - split[1].lno;
610 * if it turns out there is nothing to blame the parent for,
611 * forget about the splitting. !split[1].suspect signals this.
613 if (split[1].num_lines < 1)
614 return;
615 split[1].suspect = origin_incref(parent);
619 * split_overlap() divided an existing blame e into up to three parts
620 * in split. Adjust the linked list of blames in the scoreboard to
621 * reflect the split.
623 static void split_blame(struct scoreboard *sb,
624 struct blame_entry *split,
625 struct blame_entry *e)
627 struct blame_entry *new_entry;
629 if (split[0].suspect && split[2].suspect) {
630 /* The first part (reuse storage for the existing entry e) */
631 dup_entry(e, &split[0]);
633 /* The last part -- me */
634 new_entry = xmalloc(sizeof(*new_entry));
635 memcpy(new_entry, &(split[2]), sizeof(struct blame_entry));
636 add_blame_entry(sb, new_entry);
638 /* ... and the middle part -- parent */
639 new_entry = xmalloc(sizeof(*new_entry));
640 memcpy(new_entry, &(split[1]), sizeof(struct blame_entry));
641 add_blame_entry(sb, new_entry);
643 else if (!split[0].suspect && !split[2].suspect)
645 * The parent covers the entire area; reuse storage for
646 * e and replace it with the parent.
648 dup_entry(e, &split[1]);
649 else if (split[0].suspect) {
650 /* me and then parent */
651 dup_entry(e, &split[0]);
653 new_entry = xmalloc(sizeof(*new_entry));
654 memcpy(new_entry, &(split[1]), sizeof(struct blame_entry));
655 add_blame_entry(sb, new_entry);
657 else {
658 /* parent and then me */
659 dup_entry(e, &split[1]);
661 new_entry = xmalloc(sizeof(*new_entry));
662 memcpy(new_entry, &(split[2]), sizeof(struct blame_entry));
663 add_blame_entry(sb, new_entry);
666 if (DEBUG) { /* sanity */
667 struct blame_entry *ent;
668 int lno = sb->ent->lno, corrupt = 0;
670 for (ent = sb->ent; ent; ent = ent->next) {
671 if (lno != ent->lno)
672 corrupt = 1;
673 if (ent->s_lno < 0)
674 corrupt = 1;
675 lno += ent->num_lines;
677 if (corrupt) {
678 lno = sb->ent->lno;
679 for (ent = sb->ent; ent; ent = ent->next) {
680 printf("L %8d l %8d n %8d\n",
681 lno, ent->lno, ent->num_lines);
682 lno = ent->lno + ent->num_lines;
684 die("oops");
690 * After splitting the blame, the origins used by the
691 * on-stack blame_entry should lose one refcnt each.
693 static void decref_split(struct blame_entry *split)
695 int i;
697 for (i = 0; i < 3; i++)
698 origin_decref(split[i].suspect);
702 * Helper for blame_chunk(). blame_entry e is known to overlap with
703 * the patch hunk; split it and pass blame to the parent.
705 static void blame_overlap(struct scoreboard *sb, struct blame_entry *e,
706 int tlno, int plno, int same,
707 struct origin *parent)
709 struct blame_entry split[3];
711 split_overlap(split, e, tlno, plno, same, parent);
712 if (split[1].suspect)
713 split_blame(sb, split, e);
714 decref_split(split);
718 * Find the line number of the last line the target is suspected for.
720 static int find_last_in_target(struct scoreboard *sb, struct origin *target)
722 struct blame_entry *e;
723 int last_in_target = -1;
725 for (e = sb->ent; e; e = e->next) {
726 if (e->guilty || !same_suspect(e->suspect, target))
727 continue;
728 if (last_in_target < e->s_lno + e->num_lines)
729 last_in_target = e->s_lno + e->num_lines;
731 return last_in_target;
735 * Process one hunk from the patch between the current suspect for
736 * blame_entry e and its parent. Find and split the overlap, and
737 * pass blame to the overlapping part to the parent.
739 static void blame_chunk(struct scoreboard *sb,
740 int tlno, int plno, int same,
741 struct origin *target, struct origin *parent)
743 struct blame_entry *e;
745 for (e = sb->ent; e; e = e->next) {
746 if (e->guilty || !same_suspect(e->suspect, target))
747 continue;
748 if (same <= e->s_lno)
749 continue;
750 if (tlno < e->s_lno + e->num_lines)
751 blame_overlap(sb, e, tlno, plno, same, parent);
755 struct blame_chunk_cb_data {
756 struct scoreboard *sb;
757 struct origin *target;
758 struct origin *parent;
759 long plno;
760 long tlno;
763 static void blame_chunk_cb(void *data, long same, long p_next, long t_next)
765 struct blame_chunk_cb_data *d = data;
766 blame_chunk(d->sb, d->tlno, d->plno, same, d->target, d->parent);
767 d->plno = p_next;
768 d->tlno = t_next;
772 * We are looking at the origin 'target' and aiming to pass blame
773 * for the lines it is suspected to its parent. Run diff to find
774 * which lines came from parent and pass blame for them.
776 static int pass_blame_to_parent(struct scoreboard *sb,
777 struct origin *target,
778 struct origin *parent)
780 int last_in_target;
781 mmfile_t file_p, file_o;
782 struct blame_chunk_cb_data d;
783 xpparam_t xpp;
784 xdemitconf_t xecfg;
785 memset(&d, 0, sizeof(d));
786 d.sb = sb; d.target = target; d.parent = parent;
787 last_in_target = find_last_in_target(sb, target);
788 if (last_in_target < 0)
789 return 1; /* nothing remains for this target */
791 fill_origin_blob(&sb->revs->diffopt, parent, &file_p);
792 fill_origin_blob(&sb->revs->diffopt, target, &file_o);
793 num_get_patch++;
795 memset(&xpp, 0, sizeof(xpp));
796 xpp.flags = xdl_opts;
797 memset(&xecfg, 0, sizeof(xecfg));
798 xecfg.ctxlen = 0;
799 xdi_diff_hunks(&file_p, &file_o, blame_chunk_cb, &d, &xpp, &xecfg);
800 /* The rest (i.e. anything after tlno) are the same as the parent */
801 blame_chunk(sb, d.tlno, d.plno, last_in_target, target, parent);
803 return 0;
807 * The lines in blame_entry after splitting blames many times can become
808 * very small and trivial, and at some point it becomes pointless to
809 * blame the parents. E.g. "\t\t}\n\t}\n\n" appears everywhere in any
810 * ordinary C program, and it is not worth to say it was copied from
811 * totally unrelated file in the parent.
813 * Compute how trivial the lines in the blame_entry are.
815 static unsigned ent_score(struct scoreboard *sb, struct blame_entry *e)
817 unsigned score;
818 const char *cp, *ep;
820 if (e->score)
821 return e->score;
823 score = 1;
824 cp = nth_line(sb, e->lno);
825 ep = nth_line(sb, e->lno + e->num_lines);
826 while (cp < ep) {
827 unsigned ch = *((unsigned char *)cp);
828 if (isalnum(ch))
829 score++;
830 cp++;
832 e->score = score;
833 return score;
837 * best_so_far[] and this[] are both a split of an existing blame_entry
838 * that passes blame to the parent. Maintain best_so_far the best split
839 * so far, by comparing this and best_so_far and copying this into
840 * bst_so_far as needed.
842 static void copy_split_if_better(struct scoreboard *sb,
843 struct blame_entry *best_so_far,
844 struct blame_entry *this)
846 int i;
848 if (!this[1].suspect)
849 return;
850 if (best_so_far[1].suspect) {
851 if (ent_score(sb, &this[1]) < ent_score(sb, &best_so_far[1]))
852 return;
855 for (i = 0; i < 3; i++)
856 origin_incref(this[i].suspect);
857 decref_split(best_so_far);
858 memcpy(best_so_far, this, sizeof(struct blame_entry [3]));
862 * We are looking at a part of the final image represented by
863 * ent (tlno and same are offset by ent->s_lno).
864 * tlno is where we are looking at in the final image.
865 * up to (but not including) same match preimage.
866 * plno is where we are looking at in the preimage.
868 * <-------------- final image ---------------------->
869 * <------ent------>
870 * ^tlno ^same
871 * <---------preimage----->
872 * ^plno
874 * All line numbers are 0-based.
876 static void handle_split(struct scoreboard *sb,
877 struct blame_entry *ent,
878 int tlno, int plno, int same,
879 struct origin *parent,
880 struct blame_entry *split)
882 if (ent->num_lines <= tlno)
883 return;
884 if (tlno < same) {
885 struct blame_entry this[3];
886 tlno += ent->s_lno;
887 same += ent->s_lno;
888 split_overlap(this, ent, tlno, plno, same, parent);
889 copy_split_if_better(sb, split, this);
890 decref_split(this);
894 struct handle_split_cb_data {
895 struct scoreboard *sb;
896 struct blame_entry *ent;
897 struct origin *parent;
898 struct blame_entry *split;
899 long plno;
900 long tlno;
903 static void handle_split_cb(void *data, long same, long p_next, long t_next)
905 struct handle_split_cb_data *d = data;
906 handle_split(d->sb, d->ent, d->tlno, d->plno, same, d->parent, d->split);
907 d->plno = p_next;
908 d->tlno = t_next;
912 * Find the lines from parent that are the same as ent so that
913 * we can pass blames to it. file_p has the blob contents for
914 * the parent.
916 static void find_copy_in_blob(struct scoreboard *sb,
917 struct blame_entry *ent,
918 struct origin *parent,
919 struct blame_entry *split,
920 mmfile_t *file_p)
922 const char *cp;
923 int cnt;
924 mmfile_t file_o;
925 struct handle_split_cb_data d;
926 xpparam_t xpp;
927 xdemitconf_t xecfg;
928 memset(&d, 0, sizeof(d));
929 d.sb = sb; d.ent = ent; d.parent = parent; d.split = split;
931 * Prepare mmfile that contains only the lines in ent.
933 cp = nth_line(sb, ent->lno);
934 file_o.ptr = (char *) cp;
935 cnt = ent->num_lines;
937 while (cnt && cp < sb->final_buf + sb->final_buf_size) {
938 if (*cp++ == '\n')
939 cnt--;
941 file_o.size = cp - file_o.ptr;
944 * file_o is a part of final image we are annotating.
945 * file_p partially may match that image.
947 memset(&xpp, 0, sizeof(xpp));
948 xpp.flags = xdl_opts;
949 memset(&xecfg, 0, sizeof(xecfg));
950 xecfg.ctxlen = 1;
951 memset(split, 0, sizeof(struct blame_entry [3]));
952 xdi_diff_hunks(file_p, &file_o, handle_split_cb, &d, &xpp, &xecfg);
953 /* remainder, if any, all match the preimage */
954 handle_split(sb, ent, d.tlno, d.plno, ent->num_lines, parent, split);
958 * See if lines currently target is suspected for can be attributed to
959 * parent.
961 static int find_move_in_parent(struct scoreboard *sb,
962 struct origin *target,
963 struct origin *parent)
965 int last_in_target, made_progress;
966 struct blame_entry *e, split[3];
967 mmfile_t file_p;
969 last_in_target = find_last_in_target(sb, target);
970 if (last_in_target < 0)
971 return 1; /* nothing remains for this target */
973 fill_origin_blob(&sb->revs->diffopt, parent, &file_p);
974 if (!file_p.ptr)
975 return 0;
977 made_progress = 1;
978 while (made_progress) {
979 made_progress = 0;
980 for (e = sb->ent; e; e = e->next) {
981 if (e->guilty || !same_suspect(e->suspect, target) ||
982 ent_score(sb, e) < blame_move_score)
983 continue;
984 find_copy_in_blob(sb, e, parent, split, &file_p);
985 if (split[1].suspect &&
986 blame_move_score < ent_score(sb, &split[1])) {
987 split_blame(sb, split, e);
988 made_progress = 1;
990 decref_split(split);
993 return 0;
996 struct blame_list {
997 struct blame_entry *ent;
998 struct blame_entry split[3];
1002 * Count the number of entries the target is suspected for,
1003 * and prepare a list of entry and the best split.
1005 static struct blame_list *setup_blame_list(struct scoreboard *sb,
1006 struct origin *target,
1007 int min_score,
1008 int *num_ents_p)
1010 struct blame_entry *e;
1011 int num_ents, i;
1012 struct blame_list *blame_list = NULL;
1014 for (e = sb->ent, num_ents = 0; e; e = e->next)
1015 if (!e->scanned && !e->guilty &&
1016 same_suspect(e->suspect, target) &&
1017 min_score < ent_score(sb, e))
1018 num_ents++;
1019 if (num_ents) {
1020 blame_list = xcalloc(num_ents, sizeof(struct blame_list));
1021 for (e = sb->ent, i = 0; e; e = e->next)
1022 if (!e->scanned && !e->guilty &&
1023 same_suspect(e->suspect, target) &&
1024 min_score < ent_score(sb, e))
1025 blame_list[i++].ent = e;
1027 *num_ents_p = num_ents;
1028 return blame_list;
1032 * Reset the scanned status on all entries.
1034 static void reset_scanned_flag(struct scoreboard *sb)
1036 struct blame_entry *e;
1037 for (e = sb->ent; e; e = e->next)
1038 e->scanned = 0;
1042 * For lines target is suspected for, see if we can find code movement
1043 * across file boundary from the parent commit. porigin is the path
1044 * in the parent we already tried.
1046 static int find_copy_in_parent(struct scoreboard *sb,
1047 struct origin *target,
1048 struct commit *parent,
1049 struct origin *porigin,
1050 int opt)
1052 struct diff_options diff_opts;
1053 const char *paths[1];
1054 int i, j;
1055 int retval;
1056 struct blame_list *blame_list;
1057 int num_ents;
1059 blame_list = setup_blame_list(sb, target, blame_copy_score, &num_ents);
1060 if (!blame_list)
1061 return 1; /* nothing remains for this target */
1063 diff_setup(&diff_opts);
1064 DIFF_OPT_SET(&diff_opts, RECURSIVE);
1065 diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;
1067 paths[0] = NULL;
1068 diff_tree_setup_paths(paths, &diff_opts);
1069 if (diff_setup_done(&diff_opts) < 0)
1070 die("diff-setup");
1072 /* Try "find copies harder" on new path if requested;
1073 * we do not want to use diffcore_rename() actually to
1074 * match things up; find_copies_harder is set only to
1075 * force diff_tree_sha1() to feed all filepairs to diff_queue,
1076 * and this code needs to be after diff_setup_done(), which
1077 * usually makes find-copies-harder imply copy detection.
1079 if ((opt & PICKAXE_BLAME_COPY_HARDEST)
1080 || ((opt & PICKAXE_BLAME_COPY_HARDER)
1081 && (!porigin || strcmp(target->path, porigin->path))))
1082 DIFF_OPT_SET(&diff_opts, FIND_COPIES_HARDER);
1084 if (is_null_sha1(target->commit->object.sha1))
1085 do_diff_cache(parent->tree->object.sha1, &diff_opts);
1086 else
1087 diff_tree_sha1(parent->tree->object.sha1,
1088 target->commit->tree->object.sha1,
1089 "", &diff_opts);
1091 if (!DIFF_OPT_TST(&diff_opts, FIND_COPIES_HARDER))
1092 diffcore_std(&diff_opts);
1094 retval = 0;
1095 while (1) {
1096 int made_progress = 0;
1098 for (i = 0; i < diff_queued_diff.nr; i++) {
1099 struct diff_filepair *p = diff_queued_diff.queue[i];
1100 struct origin *norigin;
1101 mmfile_t file_p;
1102 struct blame_entry this[3];
1104 if (!DIFF_FILE_VALID(p->one))
1105 continue; /* does not exist in parent */
1106 if (S_ISGITLINK(p->one->mode))
1107 continue; /* ignore git links */
1108 if (porigin && !strcmp(p->one->path, porigin->path))
1109 /* find_move already dealt with this path */
1110 continue;
1112 norigin = get_origin(sb, parent, p->one->path);
1113 hashcpy(norigin->blob_sha1, p->one->sha1);
1114 norigin->mode = p->one->mode;
1115 fill_origin_blob(&sb->revs->diffopt, norigin, &file_p);
1116 if (!file_p.ptr)
1117 continue;
1119 for (j = 0; j < num_ents; j++) {
1120 find_copy_in_blob(sb, blame_list[j].ent,
1121 norigin, this, &file_p);
1122 copy_split_if_better(sb, blame_list[j].split,
1123 this);
1124 decref_split(this);
1126 origin_decref(norigin);
1129 for (j = 0; j < num_ents; j++) {
1130 struct blame_entry *split = blame_list[j].split;
1131 if (split[1].suspect &&
1132 blame_copy_score < ent_score(sb, &split[1])) {
1133 split_blame(sb, split, blame_list[j].ent);
1134 made_progress = 1;
1136 else
1137 blame_list[j].ent->scanned = 1;
1138 decref_split(split);
1140 free(blame_list);
1142 if (!made_progress)
1143 break;
1144 blame_list = setup_blame_list(sb, target, blame_copy_score, &num_ents);
1145 if (!blame_list) {
1146 retval = 1;
1147 break;
1150 reset_scanned_flag(sb);
1151 diff_flush(&diff_opts);
1152 diff_tree_release_paths(&diff_opts);
1153 return retval;
1157 * The blobs of origin and porigin exactly match, so everything
1158 * origin is suspected for can be blamed on the parent.
1160 static void pass_whole_blame(struct scoreboard *sb,
1161 struct origin *origin, struct origin *porigin)
1163 struct blame_entry *e;
1165 if (!porigin->file.ptr && origin->file.ptr) {
1166 /* Steal its file */
1167 porigin->file = origin->file;
1168 origin->file.ptr = NULL;
1170 for (e = sb->ent; e; e = e->next) {
1171 if (!same_suspect(e->suspect, origin))
1172 continue;
1173 origin_incref(porigin);
1174 origin_decref(e->suspect);
1175 e->suspect = porigin;
1180 * We pass blame from the current commit to its parents. We keep saying
1181 * "parent" (and "porigin"), but what we mean is to find scapegoat to
1182 * exonerate ourselves.
1184 static struct commit_list *first_scapegoat(struct rev_info *revs, struct commit *commit)
1186 if (!reverse)
1187 return commit->parents;
1188 return lookup_decoration(&revs->children, &commit->object);
1191 static int num_scapegoats(struct rev_info *revs, struct commit *commit)
1193 int cnt;
1194 struct commit_list *l = first_scapegoat(revs, commit);
1195 for (cnt = 0; l; l = l->next)
1196 cnt++;
1197 return cnt;
1200 #define MAXSG 16
1202 static void pass_blame(struct scoreboard *sb, struct origin *origin, int opt)
1204 struct rev_info *revs = sb->revs;
1205 int i, pass, num_sg;
1206 struct commit *commit = origin->commit;
1207 struct commit_list *sg;
1208 struct origin *sg_buf[MAXSG];
1209 struct origin *porigin, **sg_origin = sg_buf;
1211 num_sg = num_scapegoats(revs, commit);
1212 if (!num_sg)
1213 goto finish;
1214 else if (num_sg < ARRAY_SIZE(sg_buf))
1215 memset(sg_buf, 0, sizeof(sg_buf));
1216 else
1217 sg_origin = xcalloc(num_sg, sizeof(*sg_origin));
1220 * The first pass looks for unrenamed path to optimize for
1221 * common cases, then we look for renames in the second pass.
1223 for (pass = 0; pass < 2; pass++) {
1224 struct origin *(*find)(struct scoreboard *,
1225 struct commit *, struct origin *);
1226 find = pass ? find_rename : find_origin;
1228 for (i = 0, sg = first_scapegoat(revs, commit);
1229 i < num_sg && sg;
1230 sg = sg->next, i++) {
1231 struct commit *p = sg->item;
1232 int j, same;
1234 if (sg_origin[i])
1235 continue;
1236 if (parse_commit(p))
1237 continue;
1238 porigin = find(sb, p, origin);
1239 if (!porigin)
1240 continue;
1241 if (!hashcmp(porigin->blob_sha1, origin->blob_sha1)) {
1242 pass_whole_blame(sb, origin, porigin);
1243 origin_decref(porigin);
1244 goto finish;
1246 for (j = same = 0; j < i; j++)
1247 if (sg_origin[j] &&
1248 !hashcmp(sg_origin[j]->blob_sha1,
1249 porigin->blob_sha1)) {
1250 same = 1;
1251 break;
1253 if (!same)
1254 sg_origin[i] = porigin;
1255 else
1256 origin_decref(porigin);
1260 num_commits++;
1261 for (i = 0, sg = first_scapegoat(revs, commit);
1262 i < num_sg && sg;
1263 sg = sg->next, i++) {
1264 struct origin *porigin = sg_origin[i];
1265 if (!porigin)
1266 continue;
1267 if (!origin->previous) {
1268 origin_incref(porigin);
1269 origin->previous = porigin;
1271 if (pass_blame_to_parent(sb, origin, porigin))
1272 goto finish;
1276 * Optionally find moves in parents' files.
1278 if (opt & PICKAXE_BLAME_MOVE)
1279 for (i = 0, sg = first_scapegoat(revs, commit);
1280 i < num_sg && sg;
1281 sg = sg->next, i++) {
1282 struct origin *porigin = sg_origin[i];
1283 if (!porigin)
1284 continue;
1285 if (find_move_in_parent(sb, origin, porigin))
1286 goto finish;
1290 * Optionally find copies from parents' files.
1292 if (opt & PICKAXE_BLAME_COPY)
1293 for (i = 0, sg = first_scapegoat(revs, commit);
1294 i < num_sg && sg;
1295 sg = sg->next, i++) {
1296 struct origin *porigin = sg_origin[i];
1297 if (find_copy_in_parent(sb, origin, sg->item,
1298 porigin, opt))
1299 goto finish;
1302 finish:
1303 for (i = 0; i < num_sg; i++) {
1304 if (sg_origin[i]) {
1305 drop_origin_blob(sg_origin[i]);
1306 origin_decref(sg_origin[i]);
1309 drop_origin_blob(origin);
1310 if (sg_buf != sg_origin)
1311 free(sg_origin);
1315 * Information on commits, used for output.
1317 struct commit_info {
1318 const char *author;
1319 const char *author_mail;
1320 unsigned long author_time;
1321 const char *author_tz;
1323 /* filled only when asked for details */
1324 const char *committer;
1325 const char *committer_mail;
1326 unsigned long committer_time;
1327 const char *committer_tz;
1329 const char *summary;
1333 * Parse author/committer line in the commit object buffer
1335 static void get_ac_line(const char *inbuf, const char *what,
1336 int person_len, char *person,
1337 int mail_len, char *mail,
1338 unsigned long *time, const char **tz)
1340 int len, tzlen, maillen;
1341 char *tmp, *endp, *timepos, *mailpos;
1343 tmp = strstr(inbuf, what);
1344 if (!tmp)
1345 goto error_out;
1346 tmp += strlen(what);
1347 endp = strchr(tmp, '\n');
1348 if (!endp)
1349 len = strlen(tmp);
1350 else
1351 len = endp - tmp;
1352 if (person_len <= len) {
1353 error_out:
1354 /* Ugh */
1355 *tz = "(unknown)";
1356 strcpy(person, *tz);
1357 strcpy(mail, *tz);
1358 *time = 0;
1359 return;
1361 memcpy(person, tmp, len);
1363 tmp = person;
1364 tmp += len;
1365 *tmp = 0;
1366 while (person < tmp && *tmp != ' ')
1367 tmp--;
1368 if (tmp <= person)
1369 goto error_out;
1370 *tz = tmp+1;
1371 tzlen = (person+len)-(tmp+1);
1373 *tmp = 0;
1374 while (person < tmp && *tmp != ' ')
1375 tmp--;
1376 if (tmp <= person)
1377 goto error_out;
1378 *time = strtoul(tmp, NULL, 10);
1379 timepos = tmp;
1381 *tmp = 0;
1382 while (person < tmp && !(*tmp == ' ' && tmp[1] == '<'))
1383 tmp--;
1384 if (tmp <= person)
1385 return;
1386 mailpos = tmp + 1;
1387 *tmp = 0;
1388 maillen = timepos - tmp;
1389 memcpy(mail, mailpos, maillen);
1391 if (!mailmap.nr)
1392 return;
1395 * mailmap expansion may make the name longer.
1396 * make room by pushing stuff down.
1398 tmp = person + person_len - (tzlen + 1);
1399 memmove(tmp, *tz, tzlen);
1400 tmp[tzlen] = 0;
1401 *tz = tmp;
1404 * Now, convert both name and e-mail using mailmap
1406 if (map_user(&mailmap, mail+1, mail_len-1, person, tmp-person-1)) {
1407 /* Add a trailing '>' to email, since map_user returns plain emails
1408 Note: It already has '<', since we replace from mail+1 */
1409 mailpos = memchr(mail, '\0', mail_len);
1410 if (mailpos && mailpos-mail < mail_len - 1) {
1411 *mailpos = '>';
1412 *(mailpos+1) = '\0';
1417 static void get_commit_info(struct commit *commit,
1418 struct commit_info *ret,
1419 int detailed)
1421 int len;
1422 const char *subject;
1423 char *reencoded, *message;
1424 static char author_name[1024];
1425 static char author_mail[1024];
1426 static char committer_name[1024];
1427 static char committer_mail[1024];
1428 static char summary_buf[1024];
1431 * We've operated without save_commit_buffer, so
1432 * we now need to populate them for output.
1434 if (!commit->buffer) {
1435 enum object_type type;
1436 unsigned long size;
1437 commit->buffer =
1438 read_sha1_file(commit->object.sha1, &type, &size);
1439 if (!commit->buffer)
1440 die("Cannot read commit %s",
1441 sha1_to_hex(commit->object.sha1));
1443 reencoded = reencode_commit_message(commit, NULL);
1444 message = reencoded ? reencoded : commit->buffer;
1445 ret->author = author_name;
1446 ret->author_mail = author_mail;
1447 get_ac_line(message, "\nauthor ",
1448 sizeof(author_name), author_name,
1449 sizeof(author_mail), author_mail,
1450 &ret->author_time, &ret->author_tz);
1452 if (!detailed) {
1453 free(reencoded);
1454 return;
1457 ret->committer = committer_name;
1458 ret->committer_mail = committer_mail;
1459 get_ac_line(message, "\ncommitter ",
1460 sizeof(committer_name), committer_name,
1461 sizeof(committer_mail), committer_mail,
1462 &ret->committer_time, &ret->committer_tz);
1464 ret->summary = summary_buf;
1465 len = find_commit_subject(message, &subject);
1466 if (len && len < sizeof(summary_buf)) {
1467 memcpy(summary_buf, subject, len);
1468 summary_buf[len] = 0;
1469 } else {
1470 sprintf(summary_buf, "(%s)", sha1_to_hex(commit->object.sha1));
1472 free(reencoded);
1476 * To allow LF and other nonportable characters in pathnames,
1477 * they are c-style quoted as needed.
1479 static void write_filename_info(const char *path)
1481 printf("filename ");
1482 write_name_quoted(path, stdout, '\n');
1486 * Porcelain/Incremental format wants to show a lot of details per
1487 * commit. Instead of repeating this every line, emit it only once,
1488 * the first time each commit appears in the output (unless the
1489 * user has specifically asked for us to repeat).
1491 static int emit_one_suspect_detail(struct origin *suspect, int repeat)
1493 struct commit_info ci;
1495 if (!repeat && (suspect->commit->object.flags & METAINFO_SHOWN))
1496 return 0;
1498 suspect->commit->object.flags |= METAINFO_SHOWN;
1499 get_commit_info(suspect->commit, &ci, 1);
1500 printf("author %s\n", ci.author);
1501 printf("author-mail %s\n", ci.author_mail);
1502 printf("author-time %lu\n", ci.author_time);
1503 printf("author-tz %s\n", ci.author_tz);
1504 printf("committer %s\n", ci.committer);
1505 printf("committer-mail %s\n", ci.committer_mail);
1506 printf("committer-time %lu\n", ci.committer_time);
1507 printf("committer-tz %s\n", ci.committer_tz);
1508 printf("summary %s\n", ci.summary);
1509 if (suspect->commit->object.flags & UNINTERESTING)
1510 printf("boundary\n");
1511 if (suspect->previous) {
1512 struct origin *prev = suspect->previous;
1513 printf("previous %s ", sha1_to_hex(prev->commit->object.sha1));
1514 write_name_quoted(prev->path, stdout, '\n');
1516 return 1;
1520 * The blame_entry is found to be guilty for the range. Mark it
1521 * as such, and show it in incremental output.
1523 static void found_guilty_entry(struct blame_entry *ent)
1525 if (ent->guilty)
1526 return;
1527 ent->guilty = 1;
1528 if (incremental) {
1529 struct origin *suspect = ent->suspect;
1531 printf("%s %d %d %d\n",
1532 sha1_to_hex(suspect->commit->object.sha1),
1533 ent->s_lno + 1, ent->lno + 1, ent->num_lines);
1534 emit_one_suspect_detail(suspect, 0);
1535 write_filename_info(suspect->path);
1536 maybe_flush_or_die(stdout, "stdout");
1541 * The main loop -- while the scoreboard has lines whose true origin
1542 * is still unknown, pick one blame_entry, and allow its current
1543 * suspect to pass blames to its parents.
1545 static void assign_blame(struct scoreboard *sb, int opt)
1547 struct rev_info *revs = sb->revs;
1549 while (1) {
1550 struct blame_entry *ent;
1551 struct commit *commit;
1552 struct origin *suspect = NULL;
1554 /* find one suspect to break down */
1555 for (ent = sb->ent; !suspect && ent; ent = ent->next)
1556 if (!ent->guilty)
1557 suspect = ent->suspect;
1558 if (!suspect)
1559 return; /* all done */
1562 * We will use this suspect later in the loop,
1563 * so hold onto it in the meantime.
1565 origin_incref(suspect);
1566 commit = suspect->commit;
1567 if (!commit->object.parsed)
1568 parse_commit(commit);
1569 if (reverse ||
1570 (!(commit->object.flags & UNINTERESTING) &&
1571 !(revs->max_age != -1 && commit->date < revs->max_age)))
1572 pass_blame(sb, suspect, opt);
1573 else {
1574 commit->object.flags |= UNINTERESTING;
1575 if (commit->object.parsed)
1576 mark_parents_uninteresting(commit);
1578 /* treat root commit as boundary */
1579 if (!commit->parents && !show_root)
1580 commit->object.flags |= UNINTERESTING;
1582 /* Take responsibility for the remaining entries */
1583 for (ent = sb->ent; ent; ent = ent->next)
1584 if (same_suspect(ent->suspect, suspect))
1585 found_guilty_entry(ent);
1586 origin_decref(suspect);
1588 if (DEBUG) /* sanity */
1589 sanity_check_refcnt(sb);
1593 static const char *format_time(unsigned long time, const char *tz_str,
1594 int show_raw_time)
1596 static char time_buf[128];
1597 const char *time_str;
1598 int time_len;
1599 int tz;
1601 if (show_raw_time) {
1602 snprintf(time_buf, sizeof(time_buf), "%lu %s", time, tz_str);
1604 else {
1605 tz = atoi(tz_str);
1606 time_str = show_date(time, tz, blame_date_mode);
1607 time_len = strlen(time_str);
1608 memcpy(time_buf, time_str, time_len);
1609 memset(time_buf + time_len, ' ', blame_date_width - time_len);
1611 return time_buf;
1614 #define OUTPUT_ANNOTATE_COMPAT 001
1615 #define OUTPUT_LONG_OBJECT_NAME 002
1616 #define OUTPUT_RAW_TIMESTAMP 004
1617 #define OUTPUT_PORCELAIN 010
1618 #define OUTPUT_SHOW_NAME 020
1619 #define OUTPUT_SHOW_NUMBER 040
1620 #define OUTPUT_SHOW_SCORE 0100
1621 #define OUTPUT_NO_AUTHOR 0200
1622 #define OUTPUT_SHOW_EMAIL 0400
1623 #define OUTPUT_LINE_PORCELAIN 01000
1625 static void emit_porcelain_details(struct origin *suspect, int repeat)
1627 if (emit_one_suspect_detail(suspect, repeat) ||
1628 (suspect->commit->object.flags & MORE_THAN_ONE_PATH))
1629 write_filename_info(suspect->path);
1632 static void emit_porcelain(struct scoreboard *sb, struct blame_entry *ent,
1633 int opt)
1635 int repeat = opt & OUTPUT_LINE_PORCELAIN;
1636 int cnt;
1637 const char *cp;
1638 struct origin *suspect = ent->suspect;
1639 char hex[41];
1641 strcpy(hex, sha1_to_hex(suspect->commit->object.sha1));
1642 printf("%s%c%d %d %d\n",
1643 hex,
1644 ent->guilty ? ' ' : '*', /* purely for debugging */
1645 ent->s_lno + 1,
1646 ent->lno + 1,
1647 ent->num_lines);
1648 emit_porcelain_details(suspect, repeat);
1650 cp = nth_line(sb, ent->lno);
1651 for (cnt = 0; cnt < ent->num_lines; cnt++) {
1652 char ch;
1653 if (cnt) {
1654 printf("%s %d %d\n", hex,
1655 ent->s_lno + 1 + cnt,
1656 ent->lno + 1 + cnt);
1657 if (repeat)
1658 emit_porcelain_details(suspect, 1);
1660 putchar('\t');
1661 do {
1662 ch = *cp++;
1663 putchar(ch);
1664 } while (ch != '\n' &&
1665 cp < sb->final_buf + sb->final_buf_size);
1668 if (sb->final_buf_size && cp[-1] != '\n')
1669 putchar('\n');
1672 static void emit_other(struct scoreboard *sb, struct blame_entry *ent, int opt)
1674 int cnt;
1675 const char *cp;
1676 struct origin *suspect = ent->suspect;
1677 struct commit_info ci;
1678 char hex[41];
1679 int show_raw_time = !!(opt & OUTPUT_RAW_TIMESTAMP);
1681 get_commit_info(suspect->commit, &ci, 1);
1682 strcpy(hex, sha1_to_hex(suspect->commit->object.sha1));
1684 cp = nth_line(sb, ent->lno);
1685 for (cnt = 0; cnt < ent->num_lines; cnt++) {
1686 char ch;
1687 int length = (opt & OUTPUT_LONG_OBJECT_NAME) ? 40 : abbrev;
1689 if (suspect->commit->object.flags & UNINTERESTING) {
1690 if (blank_boundary)
1691 memset(hex, ' ', length);
1692 else if (!(opt & OUTPUT_ANNOTATE_COMPAT)) {
1693 length--;
1694 putchar('^');
1698 printf("%.*s", length, hex);
1699 if (opt & OUTPUT_ANNOTATE_COMPAT) {
1700 const char *name;
1701 if (opt & OUTPUT_SHOW_EMAIL)
1702 name = ci.author_mail;
1703 else
1704 name = ci.author;
1705 printf("\t(%10s\t%10s\t%d)", name,
1706 format_time(ci.author_time, ci.author_tz,
1707 show_raw_time),
1708 ent->lno + 1 + cnt);
1709 } else {
1710 if (opt & OUTPUT_SHOW_SCORE)
1711 printf(" %*d %02d",
1712 max_score_digits, ent->score,
1713 ent->suspect->refcnt);
1714 if (opt & OUTPUT_SHOW_NAME)
1715 printf(" %-*.*s", longest_file, longest_file,
1716 suspect->path);
1717 if (opt & OUTPUT_SHOW_NUMBER)
1718 printf(" %*d", max_orig_digits,
1719 ent->s_lno + 1 + cnt);
1721 if (!(opt & OUTPUT_NO_AUTHOR)) {
1722 const char *name;
1723 int pad;
1724 if (opt & OUTPUT_SHOW_EMAIL)
1725 name = ci.author_mail;
1726 else
1727 name = ci.author;
1728 pad = longest_author - utf8_strwidth(name);
1729 printf(" (%s%*s %10s",
1730 name, pad, "",
1731 format_time(ci.author_time,
1732 ci.author_tz,
1733 show_raw_time));
1735 printf(" %*d) ",
1736 max_digits, ent->lno + 1 + cnt);
1738 do {
1739 ch = *cp++;
1740 putchar(ch);
1741 } while (ch != '\n' &&
1742 cp < sb->final_buf + sb->final_buf_size);
1745 if (sb->final_buf_size && cp[-1] != '\n')
1746 putchar('\n');
1749 static void output(struct scoreboard *sb, int option)
1751 struct blame_entry *ent;
1753 if (option & OUTPUT_PORCELAIN) {
1754 for (ent = sb->ent; ent; ent = ent->next) {
1755 struct blame_entry *oth;
1756 struct origin *suspect = ent->suspect;
1757 struct commit *commit = suspect->commit;
1758 if (commit->object.flags & MORE_THAN_ONE_PATH)
1759 continue;
1760 for (oth = ent->next; oth; oth = oth->next) {
1761 if ((oth->suspect->commit != commit) ||
1762 !strcmp(oth->suspect->path, suspect->path))
1763 continue;
1764 commit->object.flags |= MORE_THAN_ONE_PATH;
1765 break;
1770 for (ent = sb->ent; ent; ent = ent->next) {
1771 if (option & OUTPUT_PORCELAIN)
1772 emit_porcelain(sb, ent, option);
1773 else {
1774 emit_other(sb, ent, option);
1780 * To allow quick access to the contents of nth line in the
1781 * final image, prepare an index in the scoreboard.
1783 static int prepare_lines(struct scoreboard *sb)
1785 const char *buf = sb->final_buf;
1786 unsigned long len = sb->final_buf_size;
1787 int num = 0, incomplete = 0, bol = 1;
1789 if (len && buf[len-1] != '\n')
1790 incomplete++; /* incomplete line at the end */
1791 while (len--) {
1792 if (bol) {
1793 sb->lineno = xrealloc(sb->lineno,
1794 sizeof(int *) * (num + 1));
1795 sb->lineno[num] = buf - sb->final_buf;
1796 bol = 0;
1798 if (*buf++ == '\n') {
1799 num++;
1800 bol = 1;
1803 sb->lineno = xrealloc(sb->lineno,
1804 sizeof(int *) * (num + incomplete + 1));
1805 sb->lineno[num + incomplete] = buf - sb->final_buf;
1806 sb->num_lines = num + incomplete;
1807 return sb->num_lines;
1811 * Add phony grafts for use with -S; this is primarily to
1812 * support git's cvsserver that wants to give a linear history
1813 * to its clients.
1815 static int read_ancestry(const char *graft_file)
1817 FILE *fp = fopen(graft_file, "r");
1818 char buf[1024];
1819 if (!fp)
1820 return -1;
1821 while (fgets(buf, sizeof(buf), fp)) {
1822 /* The format is just "Commit Parent1 Parent2 ...\n" */
1823 int len = strlen(buf);
1824 struct commit_graft *graft = read_graft_line(buf, len);
1825 if (graft)
1826 register_commit_graft(graft, 0);
1828 fclose(fp);
1829 return 0;
1833 * How many columns do we need to show line numbers in decimal?
1835 static int lineno_width(int lines)
1837 int i, width;
1839 for (width = 1, i = 10; i <= lines; width++)
1840 i *= 10;
1841 return width;
1845 * How many columns do we need to show line numbers, authors,
1846 * and filenames?
1848 static void find_alignment(struct scoreboard *sb, int *option)
1850 int longest_src_lines = 0;
1851 int longest_dst_lines = 0;
1852 unsigned largest_score = 0;
1853 struct blame_entry *e;
1855 for (e = sb->ent; e; e = e->next) {
1856 struct origin *suspect = e->suspect;
1857 struct commit_info ci;
1858 int num;
1860 if (strcmp(suspect->path, sb->path))
1861 *option |= OUTPUT_SHOW_NAME;
1862 num = strlen(suspect->path);
1863 if (longest_file < num)
1864 longest_file = num;
1865 if (!(suspect->commit->object.flags & METAINFO_SHOWN)) {
1866 suspect->commit->object.flags |= METAINFO_SHOWN;
1867 get_commit_info(suspect->commit, &ci, 1);
1868 if (*option & OUTPUT_SHOW_EMAIL)
1869 num = utf8_strwidth(ci.author_mail);
1870 else
1871 num = utf8_strwidth(ci.author);
1872 if (longest_author < num)
1873 longest_author = num;
1875 num = e->s_lno + e->num_lines;
1876 if (longest_src_lines < num)
1877 longest_src_lines = num;
1878 num = e->lno + e->num_lines;
1879 if (longest_dst_lines < num)
1880 longest_dst_lines = num;
1881 if (largest_score < ent_score(sb, e))
1882 largest_score = ent_score(sb, e);
1884 max_orig_digits = lineno_width(longest_src_lines);
1885 max_digits = lineno_width(longest_dst_lines);
1886 max_score_digits = lineno_width(largest_score);
1890 * For debugging -- origin is refcounted, and this asserts that
1891 * we do not underflow.
1893 static void sanity_check_refcnt(struct scoreboard *sb)
1895 int baa = 0;
1896 struct blame_entry *ent;
1898 for (ent = sb->ent; ent; ent = ent->next) {
1899 /* Nobody should have zero or negative refcnt */
1900 if (ent->suspect->refcnt <= 0) {
1901 fprintf(stderr, "%s in %s has negative refcnt %d\n",
1902 ent->suspect->path,
1903 sha1_to_hex(ent->suspect->commit->object.sha1),
1904 ent->suspect->refcnt);
1905 baa = 1;
1908 if (baa) {
1909 int opt = 0160;
1910 find_alignment(sb, &opt);
1911 output(sb, opt);
1912 die("Baa %d!", baa);
1917 * Used for the command line parsing; check if the path exists
1918 * in the working tree.
1920 static int has_string_in_work_tree(const char *path)
1922 struct stat st;
1923 return !lstat(path, &st);
1926 static unsigned parse_score(const char *arg)
1928 char *end;
1929 unsigned long score = strtoul(arg, &end, 10);
1930 if (*end)
1931 return 0;
1932 return score;
1935 static const char *add_prefix(const char *prefix, const char *path)
1937 return prefix_path(prefix, prefix ? strlen(prefix) : 0, path);
1941 * Parsing of (comma separated) one item in the -L option
1943 static const char *parse_loc(const char *spec,
1944 struct scoreboard *sb, long lno,
1945 long begin, long *ret)
1947 char *term;
1948 const char *line;
1949 long num;
1950 int reg_error;
1951 regex_t regexp;
1952 regmatch_t match[1];
1954 /* Allow "-L <something>,+20" to mean starting at <something>
1955 * for 20 lines, or "-L <something>,-5" for 5 lines ending at
1956 * <something>.
1958 if (1 < begin && (spec[0] == '+' || spec[0] == '-')) {
1959 num = strtol(spec + 1, &term, 10);
1960 if (term != spec + 1) {
1961 if (spec[0] == '-')
1962 num = 0 - num;
1963 if (0 < num)
1964 *ret = begin + num - 2;
1965 else if (!num)
1966 *ret = begin;
1967 else
1968 *ret = begin + num;
1969 return term;
1971 return spec;
1973 num = strtol(spec, &term, 10);
1974 if (term != spec) {
1975 *ret = num;
1976 return term;
1978 if (spec[0] != '/')
1979 return spec;
1981 /* it could be a regexp of form /.../ */
1982 for (term = (char *) spec + 1; *term && *term != '/'; term++) {
1983 if (*term == '\\')
1984 term++;
1986 if (*term != '/')
1987 return spec;
1989 /* try [spec+1 .. term-1] as regexp */
1990 *term = 0;
1991 begin--; /* input is in human terms */
1992 line = nth_line(sb, begin);
1994 if (!(reg_error = regcomp(&regexp, spec + 1, REG_NEWLINE)) &&
1995 !(reg_error = regexec(&regexp, line, 1, match, 0))) {
1996 const char *cp = line + match[0].rm_so;
1997 const char *nline;
1999 while (begin++ < lno) {
2000 nline = nth_line(sb, begin);
2001 if (line <= cp && cp < nline)
2002 break;
2003 line = nline;
2005 *ret = begin;
2006 regfree(&regexp);
2007 *term++ = '/';
2008 return term;
2010 else {
2011 char errbuf[1024];
2012 regerror(reg_error, &regexp, errbuf, 1024);
2013 die("-L parameter '%s': %s", spec + 1, errbuf);
2018 * Parsing of -L option
2020 static void prepare_blame_range(struct scoreboard *sb,
2021 const char *bottomtop,
2022 long lno,
2023 long *bottom, long *top)
2025 const char *term;
2027 term = parse_loc(bottomtop, sb, lno, 1, bottom);
2028 if (*term == ',') {
2029 term = parse_loc(term + 1, sb, lno, *bottom + 1, top);
2030 if (*term)
2031 usage(blame_usage);
2033 if (*term)
2034 usage(blame_usage);
2037 static int git_blame_config(const char *var, const char *value, void *cb)
2039 if (!strcmp(var, "blame.showroot")) {
2040 show_root = git_config_bool(var, value);
2041 return 0;
2043 if (!strcmp(var, "blame.blankboundary")) {
2044 blank_boundary = git_config_bool(var, value);
2045 return 0;
2047 if (!strcmp(var, "blame.date")) {
2048 if (!value)
2049 return config_error_nonbool(var);
2050 blame_date_mode = parse_date_format(value);
2051 return 0;
2054 switch (userdiff_config(var, value)) {
2055 case 0:
2056 break;
2057 case -1:
2058 return -1;
2059 default:
2060 return 0;
2063 return git_default_config(var, value, cb);
2067 * Prepare a dummy commit that represents the work tree (or staged) item.
2068 * Note that annotating work tree item never works in the reverse.
2070 static struct commit *fake_working_tree_commit(struct diff_options *opt,
2071 const char *path,
2072 const char *contents_from)
2074 struct commit *commit;
2075 struct origin *origin;
2076 unsigned char head_sha1[20];
2077 struct strbuf buf = STRBUF_INIT;
2078 const char *ident;
2079 time_t now;
2080 int size, len;
2081 struct cache_entry *ce;
2082 unsigned mode;
2084 if (get_sha1("HEAD", head_sha1))
2085 die("No such ref: HEAD");
2087 time(&now);
2088 commit = xcalloc(1, sizeof(*commit));
2089 commit->parents = xcalloc(1, sizeof(*commit->parents));
2090 commit->parents->item = lookup_commit_reference(head_sha1);
2091 commit->object.parsed = 1;
2092 commit->date = now;
2093 commit->object.type = OBJ_COMMIT;
2095 origin = make_origin(commit, path);
2097 if (!contents_from || strcmp("-", contents_from)) {
2098 struct stat st;
2099 const char *read_from;
2100 char *buf_ptr;
2101 unsigned long buf_len;
2103 if (contents_from) {
2104 if (stat(contents_from, &st) < 0)
2105 die_errno("Cannot stat '%s'", contents_from);
2106 read_from = contents_from;
2108 else {
2109 if (lstat(path, &st) < 0)
2110 die_errno("Cannot lstat '%s'", path);
2111 read_from = path;
2113 mode = canon_mode(st.st_mode);
2115 switch (st.st_mode & S_IFMT) {
2116 case S_IFREG:
2117 if (DIFF_OPT_TST(opt, ALLOW_TEXTCONV) &&
2118 textconv_object(read_from, mode, null_sha1, 0, &buf_ptr, &buf_len))
2119 strbuf_attach(&buf, buf_ptr, buf_len, buf_len + 1);
2120 else if (strbuf_read_file(&buf, read_from, st.st_size) != st.st_size)
2121 die_errno("cannot open or read '%s'", read_from);
2122 break;
2123 case S_IFLNK:
2124 if (strbuf_readlink(&buf, read_from, st.st_size) < 0)
2125 die_errno("cannot readlink '%s'", read_from);
2126 break;
2127 default:
2128 die("unsupported file type %s", read_from);
2131 else {
2132 /* Reading from stdin */
2133 contents_from = "standard input";
2134 mode = 0;
2135 if (strbuf_read(&buf, 0, 0) < 0)
2136 die_errno("failed to read from stdin");
2138 convert_to_git(path, buf.buf, buf.len, &buf, 0);
2139 origin->file.ptr = buf.buf;
2140 origin->file.size = buf.len;
2141 pretend_sha1_file(buf.buf, buf.len, OBJ_BLOB, origin->blob_sha1);
2142 commit->util = origin;
2145 * Read the current index, replace the path entry with
2146 * origin->blob_sha1 without mucking with its mode or type
2147 * bits; we are not going to write this index out -- we just
2148 * want to run "diff-index --cached".
2150 discard_cache();
2151 read_cache();
2153 len = strlen(path);
2154 if (!mode) {
2155 int pos = cache_name_pos(path, len);
2156 if (0 <= pos)
2157 mode = active_cache[pos]->ce_mode;
2158 else
2159 /* Let's not bother reading from HEAD tree */
2160 mode = S_IFREG | 0644;
2162 size = cache_entry_size(len);
2163 ce = xcalloc(1, size);
2164 hashcpy(ce->sha1, origin->blob_sha1);
2165 memcpy(ce->name, path, len);
2166 ce->ce_flags = create_ce_flags(len, 0);
2167 ce->ce_mode = create_ce_mode(mode);
2168 add_cache_entry(ce, ADD_CACHE_OK_TO_ADD|ADD_CACHE_OK_TO_REPLACE);
2171 * We are not going to write this out, so this does not matter
2172 * right now, but someday we might optimize diff-index --cached
2173 * with cache-tree information.
2175 cache_tree_invalidate_path(active_cache_tree, path);
2177 commit->buffer = xmalloc(400);
2178 ident = fmt_ident("Not Committed Yet", "not.committed.yet", NULL, 0);
2179 snprintf(commit->buffer, 400,
2180 "tree 0000000000000000000000000000000000000000\n"
2181 "parent %s\n"
2182 "author %s\n"
2183 "committer %s\n\n"
2184 "Version of %s from %s\n",
2185 sha1_to_hex(head_sha1),
2186 ident, ident, path, contents_from ? contents_from : path);
2187 return commit;
2190 static const char *prepare_final(struct scoreboard *sb)
2192 int i;
2193 const char *final_commit_name = NULL;
2194 struct rev_info *revs = sb->revs;
2197 * There must be one and only one positive commit in the
2198 * revs->pending array.
2200 for (i = 0; i < revs->pending.nr; i++) {
2201 struct object *obj = revs->pending.objects[i].item;
2202 if (obj->flags & UNINTERESTING)
2203 continue;
2204 while (obj->type == OBJ_TAG)
2205 obj = deref_tag(obj, NULL, 0);
2206 if (obj->type != OBJ_COMMIT)
2207 die("Non commit %s?", revs->pending.objects[i].name);
2208 if (sb->final)
2209 die("More than one commit to dig from %s and %s?",
2210 revs->pending.objects[i].name,
2211 final_commit_name);
2212 sb->final = (struct commit *) obj;
2213 final_commit_name = revs->pending.objects[i].name;
2215 return final_commit_name;
2218 static const char *prepare_initial(struct scoreboard *sb)
2220 int i;
2221 const char *final_commit_name = NULL;
2222 struct rev_info *revs = sb->revs;
2225 * There must be one and only one negative commit, and it must be
2226 * the boundary.
2228 for (i = 0; i < revs->pending.nr; i++) {
2229 struct object *obj = revs->pending.objects[i].item;
2230 if (!(obj->flags & UNINTERESTING))
2231 continue;
2232 while (obj->type == OBJ_TAG)
2233 obj = deref_tag(obj, NULL, 0);
2234 if (obj->type != OBJ_COMMIT)
2235 die("Non commit %s?", revs->pending.objects[i].name);
2236 if (sb->final)
2237 die("More than one commit to dig down to %s and %s?",
2238 revs->pending.objects[i].name,
2239 final_commit_name);
2240 sb->final = (struct commit *) obj;
2241 final_commit_name = revs->pending.objects[i].name;
2243 if (!final_commit_name)
2244 die("No commit to dig down to?");
2245 return final_commit_name;
2248 static int blame_copy_callback(const struct option *option, const char *arg, int unset)
2250 int *opt = option->value;
2253 * -C enables copy from removed files;
2254 * -C -C enables copy from existing files, but only
2255 * when blaming a new file;
2256 * -C -C -C enables copy from existing files for
2257 * everybody
2259 if (*opt & PICKAXE_BLAME_COPY_HARDER)
2260 *opt |= PICKAXE_BLAME_COPY_HARDEST;
2261 if (*opt & PICKAXE_BLAME_COPY)
2262 *opt |= PICKAXE_BLAME_COPY_HARDER;
2263 *opt |= PICKAXE_BLAME_COPY | PICKAXE_BLAME_MOVE;
2265 if (arg)
2266 blame_copy_score = parse_score(arg);
2267 return 0;
2270 static int blame_move_callback(const struct option *option, const char *arg, int unset)
2272 int *opt = option->value;
2274 *opt |= PICKAXE_BLAME_MOVE;
2276 if (arg)
2277 blame_move_score = parse_score(arg);
2278 return 0;
2281 static int blame_bottomtop_callback(const struct option *option, const char *arg, int unset)
2283 const char **bottomtop = option->value;
2284 if (!arg)
2285 return -1;
2286 if (*bottomtop)
2287 die("More than one '-L n,m' option given");
2288 *bottomtop = arg;
2289 return 0;
2292 int cmd_blame(int argc, const char **argv, const char *prefix)
2294 struct rev_info revs;
2295 const char *path;
2296 struct scoreboard sb;
2297 struct origin *o;
2298 struct blame_entry *ent;
2299 long dashdash_pos, bottom, top, lno;
2300 const char *final_commit_name = NULL;
2301 enum object_type type;
2303 static const char *bottomtop = NULL;
2304 static int output_option = 0, opt = 0;
2305 static int show_stats = 0;
2306 static const char *revs_file = NULL;
2307 static const char *contents_from = NULL;
2308 static const struct option options[] = {
2309 OPT_BOOLEAN(0, "incremental", &incremental, "Show blame entries as we find them, incrementally"),
2310 OPT_BOOLEAN('b', NULL, &blank_boundary, "Show blank SHA-1 for boundary commits (Default: off)"),
2311 OPT_BOOLEAN(0, "root", &show_root, "Do not treat root commits as boundaries (Default: off)"),
2312 OPT_BOOLEAN(0, "show-stats", &show_stats, "Show work cost statistics"),
2313 OPT_BIT(0, "score-debug", &output_option, "Show output score for blame entries", OUTPUT_SHOW_SCORE),
2314 OPT_BIT('f', "show-name", &output_option, "Show original filename (Default: auto)", OUTPUT_SHOW_NAME),
2315 OPT_BIT('n', "show-number", &output_option, "Show original linenumber (Default: off)", OUTPUT_SHOW_NUMBER),
2316 OPT_BIT('p', "porcelain", &output_option, "Show in a format designed for machine consumption", OUTPUT_PORCELAIN),
2317 OPT_BIT(0, "line-porcelain", &output_option, "Show porcelain format with per-line commit information", OUTPUT_PORCELAIN|OUTPUT_LINE_PORCELAIN),
2318 OPT_BIT('c', NULL, &output_option, "Use the same output mode as git-annotate (Default: off)", OUTPUT_ANNOTATE_COMPAT),
2319 OPT_BIT('t', NULL, &output_option, "Show raw timestamp (Default: off)", OUTPUT_RAW_TIMESTAMP),
2320 OPT_BIT('l', NULL, &output_option, "Show long commit SHA1 (Default: off)", OUTPUT_LONG_OBJECT_NAME),
2321 OPT_BIT('s', NULL, &output_option, "Suppress author name and timestamp (Default: off)", OUTPUT_NO_AUTHOR),
2322 OPT_BIT('e', "show-email", &output_option, "Show author email instead of name (Default: off)", OUTPUT_SHOW_EMAIL),
2323 OPT_BIT('w', NULL, &xdl_opts, "Ignore whitespace differences", XDF_IGNORE_WHITESPACE),
2324 OPT_STRING('S', NULL, &revs_file, "file", "Use revisions from <file> instead of calling git-rev-list"),
2325 OPT_STRING(0, "contents", &contents_from, "file", "Use <file>'s contents as the final image"),
2326 { OPTION_CALLBACK, 'C', NULL, &opt, "score", "Find line copies within and across files", PARSE_OPT_OPTARG, blame_copy_callback },
2327 { OPTION_CALLBACK, 'M', NULL, &opt, "score", "Find line movements within and across files", PARSE_OPT_OPTARG, blame_move_callback },
2328 OPT_CALLBACK('L', NULL, &bottomtop, "n,m", "Process only line range n,m, counting from 1", blame_bottomtop_callback),
2329 OPT__ABBREV(&abbrev),
2330 OPT_END()
2333 struct parse_opt_ctx_t ctx;
2334 int cmd_is_annotate = !strcmp(argv[0], "annotate");
2336 git_config(git_blame_config, NULL);
2337 init_revisions(&revs, NULL);
2338 revs.date_mode = blame_date_mode;
2339 DIFF_OPT_SET(&revs.diffopt, ALLOW_TEXTCONV);
2341 save_commit_buffer = 0;
2342 dashdash_pos = 0;
2344 parse_options_start(&ctx, argc, argv, prefix, options,
2345 PARSE_OPT_KEEP_DASHDASH | PARSE_OPT_KEEP_ARGV0);
2346 for (;;) {
2347 switch (parse_options_step(&ctx, options, blame_opt_usage)) {
2348 case PARSE_OPT_HELP:
2349 exit(129);
2350 case PARSE_OPT_DONE:
2351 if (ctx.argv[0])
2352 dashdash_pos = ctx.cpidx;
2353 goto parse_done;
2356 if (!strcmp(ctx.argv[0], "--reverse")) {
2357 ctx.argv[0] = "--children";
2358 reverse = 1;
2360 parse_revision_opt(&revs, &ctx, options, blame_opt_usage);
2362 parse_done:
2363 argc = parse_options_end(&ctx);
2365 if (abbrev == -1)
2366 abbrev = default_abbrev;
2367 /* one more abbrev length is needed for the boundary commit */
2368 abbrev++;
2370 if (revs_file && read_ancestry(revs_file))
2371 die_errno("reading graft file '%s' failed", revs_file);
2373 if (cmd_is_annotate) {
2374 output_option |= OUTPUT_ANNOTATE_COMPAT;
2375 blame_date_mode = DATE_ISO8601;
2376 } else {
2377 blame_date_mode = revs.date_mode;
2380 /* The maximum width used to show the dates */
2381 switch (blame_date_mode) {
2382 case DATE_RFC2822:
2383 blame_date_width = sizeof("Thu, 19 Oct 2006 16:00:04 -0700");
2384 break;
2385 case DATE_ISO8601:
2386 blame_date_width = sizeof("2006-10-19 16:00:04 -0700");
2387 break;
2388 case DATE_RAW:
2389 blame_date_width = sizeof("1161298804 -0700");
2390 break;
2391 case DATE_SHORT:
2392 blame_date_width = sizeof("2006-10-19");
2393 break;
2394 case DATE_RELATIVE:
2395 /* "normal" is used as the fallback for "relative" */
2396 case DATE_LOCAL:
2397 case DATE_NORMAL:
2398 blame_date_width = sizeof("Thu Oct 19 16:00:04 2006 -0700");
2399 break;
2401 blame_date_width -= 1; /* strip the null */
2403 if (DIFF_OPT_TST(&revs.diffopt, FIND_COPIES_HARDER))
2404 opt |= (PICKAXE_BLAME_COPY | PICKAXE_BLAME_MOVE |
2405 PICKAXE_BLAME_COPY_HARDER);
2407 if (!blame_move_score)
2408 blame_move_score = BLAME_DEFAULT_MOVE_SCORE;
2409 if (!blame_copy_score)
2410 blame_copy_score = BLAME_DEFAULT_COPY_SCORE;
2413 * We have collected options unknown to us in argv[1..unk]
2414 * which are to be passed to revision machinery if we are
2415 * going to do the "bottom" processing.
2417 * The remaining are:
2419 * (1) if dashdash_pos != 0, it is either
2420 * "blame [revisions] -- <path>" or
2421 * "blame -- <path> <rev>"
2423 * (2) otherwise, it is one of the two:
2424 * "blame [revisions] <path>"
2425 * "blame <path> <rev>"
2427 * Note that we must strip out <path> from the arguments: we do not
2428 * want the path pruning but we may want "bottom" processing.
2430 if (dashdash_pos) {
2431 switch (argc - dashdash_pos - 1) {
2432 case 2: /* (1b) */
2433 if (argc != 4)
2434 usage_with_options(blame_opt_usage, options);
2435 /* reorder for the new way: <rev> -- <path> */
2436 argv[1] = argv[3];
2437 argv[3] = argv[2];
2438 argv[2] = "--";
2439 /* FALLTHROUGH */
2440 case 1: /* (1a) */
2441 path = add_prefix(prefix, argv[--argc]);
2442 argv[argc] = NULL;
2443 break;
2444 default:
2445 usage_with_options(blame_opt_usage, options);
2447 } else {
2448 if (argc < 2)
2449 usage_with_options(blame_opt_usage, options);
2450 path = add_prefix(prefix, argv[argc - 1]);
2451 if (argc == 3 && !has_string_in_work_tree(path)) { /* (2b) */
2452 path = add_prefix(prefix, argv[1]);
2453 argv[1] = argv[2];
2455 argv[argc - 1] = "--";
2457 setup_work_tree();
2458 if (!has_string_in_work_tree(path))
2459 die_errno("cannot stat path '%s'", path);
2462 revs.disable_stdin = 1;
2463 setup_revisions(argc, argv, &revs, NULL);
2464 memset(&sb, 0, sizeof(sb));
2466 sb.revs = &revs;
2467 if (!reverse)
2468 final_commit_name = prepare_final(&sb);
2469 else if (contents_from)
2470 die("--contents and --children do not blend well.");
2471 else
2472 final_commit_name = prepare_initial(&sb);
2474 if (!sb.final) {
2476 * "--not A B -- path" without anything positive;
2477 * do not default to HEAD, but use the working tree
2478 * or "--contents".
2480 setup_work_tree();
2481 sb.final = fake_working_tree_commit(&sb.revs->diffopt,
2482 path, contents_from);
2483 add_pending_object(&revs, &(sb.final->object), ":");
2485 else if (contents_from)
2486 die("Cannot use --contents with final commit object name");
2489 * If we have bottom, this will mark the ancestors of the
2490 * bottom commits we would reach while traversing as
2491 * uninteresting.
2493 if (prepare_revision_walk(&revs))
2494 die("revision walk setup failed");
2496 if (is_null_sha1(sb.final->object.sha1)) {
2497 char *buf;
2498 o = sb.final->util;
2499 buf = xmalloc(o->file.size + 1);
2500 memcpy(buf, o->file.ptr, o->file.size + 1);
2501 sb.final_buf = buf;
2502 sb.final_buf_size = o->file.size;
2504 else {
2505 o = get_origin(&sb, sb.final, path);
2506 if (fill_blob_sha1_and_mode(o))
2507 die("no such path %s in %s", path, final_commit_name);
2509 if (DIFF_OPT_TST(&sb.revs->diffopt, ALLOW_TEXTCONV) &&
2510 textconv_object(path, o->mode, o->blob_sha1, 1, (char **) &sb.final_buf,
2511 &sb.final_buf_size))
2513 else
2514 sb.final_buf = read_sha1_file(o->blob_sha1, &type,
2515 &sb.final_buf_size);
2517 if (!sb.final_buf)
2518 die("Cannot read blob %s for path %s",
2519 sha1_to_hex(o->blob_sha1),
2520 path);
2522 num_read_blob++;
2523 lno = prepare_lines(&sb);
2525 bottom = top = 0;
2526 if (bottomtop)
2527 prepare_blame_range(&sb, bottomtop, lno, &bottom, &top);
2528 if (bottom && top && top < bottom) {
2529 long tmp;
2530 tmp = top; top = bottom; bottom = tmp;
2532 if (bottom < 1)
2533 bottom = 1;
2534 if (top < 1)
2535 top = lno;
2536 bottom--;
2537 if (lno < top || lno < bottom)
2538 die("file %s has only %lu lines", path, lno);
2540 ent = xcalloc(1, sizeof(*ent));
2541 ent->lno = bottom;
2542 ent->num_lines = top - bottom;
2543 ent->suspect = o;
2544 ent->s_lno = bottom;
2546 sb.ent = ent;
2547 sb.path = path;
2549 read_mailmap(&mailmap, NULL);
2551 if (!incremental)
2552 setup_pager();
2554 assign_blame(&sb, opt);
2556 if (incremental)
2557 return 0;
2559 coalesce(&sb);
2561 if (!(output_option & OUTPUT_PORCELAIN))
2562 find_alignment(&sb, &output_option);
2564 output(&sb, output_option);
2565 free((void *)sb.final_buf);
2566 for (ent = sb.ent; ent; ) {
2567 struct blame_entry *e = ent->next;
2568 free(ent);
2569 ent = e;
2572 if (show_stats) {
2573 printf("num read blob: %d\n", num_read_blob);
2574 printf("num get patch: %d\n", num_get_patch);
2575 printf("num commits: %d\n", num_commits);
2577 return 0;