merge-octopus: Work around environment issue on Windows
[git/dscho.git] / builtin / blame.c
blob85427bce8fe82e9142c5e828cb6e5eb86bcfdc44
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"
24 #include "line.h"
26 static char blame_usage[] = "git blame [options] [rev-opts] [rev] [--] file";
28 static const char *blame_opt_usage[] = {
29 blame_usage,
30 "",
31 "[rev-opts] are documented in git-rev-list(1)",
32 NULL
35 static int longest_file;
36 static int longest_author;
37 static int max_orig_digits;
38 static int max_digits;
39 static int max_score_digits;
40 static int show_root;
41 static int reverse;
42 static int blank_boundary;
43 static int incremental;
44 static int xdl_opts;
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 char path[FLEX_ARRAY];
91 * Prepare diff_filespec and convert it using diff textconv API
92 * if the textconv driver exists.
93 * Return 1 if the conversion succeeds, 0 otherwise.
95 int textconv_object(const char *path,
96 const unsigned char *sha1,
97 char **buf,
98 unsigned long *buf_size)
100 struct diff_filespec *df;
101 struct userdiff_driver *textconv;
103 df = alloc_filespec(path);
104 fill_filespec(df, sha1, S_IFREG | 0664);
105 textconv = get_textconv(df);
106 if (!textconv) {
107 free_filespec(df);
108 return 0;
111 *buf_size = fill_textconv(textconv, df, buf);
112 free_filespec(df);
113 return 1;
117 * Given an origin, prepare mmfile_t structure to be used by the
118 * diff machinery
120 static void fill_origin_blob(struct diff_options *opt,
121 struct origin *o, mmfile_t *file)
123 if (!o->file.ptr) {
124 enum object_type type;
125 unsigned long file_size;
127 num_read_blob++;
128 if (DIFF_OPT_TST(opt, ALLOW_TEXTCONV) &&
129 textconv_object(o->path, o->blob_sha1, &file->ptr, &file_size))
131 else
132 file->ptr = read_sha1_file(o->blob_sha1, &type, &file_size);
133 file->size = file_size;
135 if (!file->ptr)
136 die("Cannot read blob %s for path %s",
137 sha1_to_hex(o->blob_sha1),
138 o->path);
139 o->file = *file;
141 else
142 *file = o->file;
146 * Origin is refcounted and usually we keep the blob contents to be
147 * reused.
149 static inline struct origin *origin_incref(struct origin *o)
151 if (o)
152 o->refcnt++;
153 return o;
156 static void origin_decref(struct origin *o)
158 if (o && --o->refcnt <= 0) {
159 if (o->previous)
160 origin_decref(o->previous);
161 free(o->file.ptr);
162 free(o);
166 static void drop_origin_blob(struct origin *o)
168 if (o->file.ptr) {
169 free(o->file.ptr);
170 o->file.ptr = NULL;
175 * Each group of lines is described by a blame_entry; it can be split
176 * as we pass blame to the parents. They form a linked list in the
177 * scoreboard structure, sorted by the target line number.
179 struct blame_entry {
180 struct blame_entry *prev;
181 struct blame_entry *next;
183 /* the first line of this group in the final image;
184 * internally all line numbers are 0 based.
186 int lno;
188 /* how many lines this group has */
189 int num_lines;
191 /* the commit that introduced this group into the final image */
192 struct origin *suspect;
194 /* true if the suspect is truly guilty; false while we have not
195 * checked if the group came from one of its parents.
197 char guilty;
199 /* true if the entry has been scanned for copies in the current parent
201 char scanned;
203 /* the line number of the first line of this group in the
204 * suspect's file; internally all line numbers are 0 based.
206 int s_lno;
208 /* how significant this entry is -- cached to avoid
209 * scanning the lines over and over.
211 unsigned score;
215 * The current state of the blame assignment.
217 struct scoreboard {
218 /* the final commit (i.e. where we started digging from) */
219 struct commit *final;
220 struct rev_info *revs;
221 const char *path;
224 * The contents in the final image.
225 * Used by many functions to obtain contents of the nth line,
226 * indexed with scoreboard.lineno[blame_entry.lno].
228 const char *final_buf;
229 unsigned long final_buf_size;
231 /* linked list of blames */
232 struct blame_entry *ent;
234 /* look-up a line in the final buffer */
235 int num_lines;
236 int *lineno;
239 static inline int same_suspect(struct origin *a, struct origin *b)
241 if (a == b)
242 return 1;
243 if (a->commit != b->commit)
244 return 0;
245 return !strcmp(a->path, b->path);
248 static void sanity_check_refcnt(struct scoreboard *);
251 * If two blame entries that are next to each other came from
252 * contiguous lines in the same origin (i.e. <commit, path> pair),
253 * merge them together.
255 static void coalesce(struct scoreboard *sb)
257 struct blame_entry *ent, *next;
259 for (ent = sb->ent; ent && (next = ent->next); ent = next) {
260 if (same_suspect(ent->suspect, next->suspect) &&
261 ent->guilty == next->guilty &&
262 ent->s_lno + ent->num_lines == next->s_lno) {
263 ent->num_lines += next->num_lines;
264 ent->next = next->next;
265 if (ent->next)
266 ent->next->prev = ent;
267 origin_decref(next->suspect);
268 free(next);
269 ent->score = 0;
270 next = ent; /* again */
274 if (DEBUG) /* sanity */
275 sanity_check_refcnt(sb);
279 * Given a commit and a path in it, create a new origin structure.
280 * The callers that add blame to the scoreboard should use
281 * get_origin() to obtain shared, refcounted copy instead of calling
282 * this function directly.
284 static struct origin *make_origin(struct commit *commit, const char *path)
286 struct origin *o;
287 o = xcalloc(1, sizeof(*o) + strlen(path) + 1);
288 o->commit = commit;
289 o->refcnt = 1;
290 strcpy(o->path, path);
291 return o;
295 * Locate an existing origin or create a new one.
297 static struct origin *get_origin(struct scoreboard *sb,
298 struct commit *commit,
299 const char *path)
301 struct blame_entry *e;
303 for (e = sb->ent; e; e = e->next) {
304 if (e->suspect->commit == commit &&
305 !strcmp(e->suspect->path, path))
306 return origin_incref(e->suspect);
308 return make_origin(commit, path);
312 * Fill the blob_sha1 field of an origin if it hasn't, so that later
313 * call to fill_origin_blob() can use it to locate the data. blob_sha1
314 * for an origin is also used to pass the blame for the entire file to
315 * the parent to detect the case where a child's blob is identical to
316 * that of its parent's.
318 static int fill_blob_sha1(struct origin *origin)
320 unsigned mode;
321 if (!is_null_sha1(origin->blob_sha1))
322 return 0;
323 if (get_tree_entry(origin->commit->object.sha1,
324 origin->path,
325 origin->blob_sha1, &mode))
326 goto error_out;
327 if (sha1_object_info(origin->blob_sha1, NULL) != OBJ_BLOB)
328 goto error_out;
329 return 0;
330 error_out:
331 hashclr(origin->blob_sha1);
332 return -1;
336 * We have an origin -- check if the same path exists in the
337 * parent and return an origin structure to represent it.
339 static struct origin *find_origin(struct scoreboard *sb,
340 struct commit *parent,
341 struct origin *origin)
343 struct origin *porigin = NULL;
344 struct diff_options diff_opts;
345 const char *paths[2];
347 if (parent->util) {
349 * Each commit object can cache one origin in that
350 * commit. This is a freestanding copy of origin and
351 * not refcounted.
353 struct origin *cached = parent->util;
354 if (!strcmp(cached->path, origin->path)) {
356 * The same path between origin and its parent
357 * without renaming -- the most common case.
359 porigin = get_origin(sb, parent, cached->path);
362 * If the origin was newly created (i.e. get_origin
363 * would call make_origin if none is found in the
364 * scoreboard), it does not know the blob_sha1,
365 * so copy it. Otherwise porigin was in the
366 * scoreboard and already knows blob_sha1.
368 if (porigin->refcnt == 1)
369 hashcpy(porigin->blob_sha1, cached->blob_sha1);
370 return porigin;
372 /* otherwise it was not very useful; free it */
373 free(parent->util);
374 parent->util = NULL;
377 /* See if the origin->path is different between parent
378 * and origin first. Most of the time they are the
379 * same and diff-tree is fairly efficient about this.
381 diff_setup(&diff_opts);
382 DIFF_OPT_SET(&diff_opts, RECURSIVE);
383 diff_opts.detect_rename = 0;
384 diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;
385 paths[0] = origin->path;
386 paths[1] = NULL;
388 diff_tree_setup_paths(paths, &diff_opts);
389 if (diff_setup_done(&diff_opts) < 0)
390 die("diff-setup");
392 if (is_null_sha1(origin->commit->object.sha1))
393 do_diff_cache(parent->tree->object.sha1, &diff_opts);
394 else
395 diff_tree_sha1(parent->tree->object.sha1,
396 origin->commit->tree->object.sha1,
397 "", &diff_opts);
398 diffcore_std(&diff_opts);
400 if (!diff_queued_diff.nr) {
401 /* The path is the same as parent */
402 porigin = get_origin(sb, parent, origin->path);
403 hashcpy(porigin->blob_sha1, origin->blob_sha1);
404 } else {
406 * Since origin->path is a pathspec, if the parent
407 * commit had it as a directory, we will see a whole
408 * bunch of deletion of files in the directory that we
409 * do not care about.
411 int i;
412 struct diff_filepair *p = NULL;
413 for (i = 0; i < diff_queued_diff.nr; i++) {
414 const char *name;
415 p = diff_queued_diff.queue[i];
416 name = p->one->path ? p->one->path : p->two->path;
417 if (!strcmp(name, origin->path))
418 break;
420 if (!p)
421 die("internal error in blame::find_origin");
422 switch (p->status) {
423 default:
424 die("internal error in blame::find_origin (%c)",
425 p->status);
426 case 'M':
427 porigin = get_origin(sb, parent, origin->path);
428 hashcpy(porigin->blob_sha1, p->one->sha1);
429 break;
430 case 'A':
431 case 'T':
432 /* Did not exist in parent, or type changed */
433 break;
436 diff_flush(&diff_opts);
437 diff_tree_release_paths(&diff_opts);
438 if (porigin) {
440 * Create a freestanding copy that is not part of
441 * the refcounted origin found in the scoreboard, and
442 * cache it in the commit.
444 struct origin *cached;
446 cached = make_origin(porigin->commit, porigin->path);
447 hashcpy(cached->blob_sha1, porigin->blob_sha1);
448 parent->util = cached;
450 return porigin;
454 * We have an origin -- find the path that corresponds to it in its
455 * parent and return an origin structure to represent it.
457 static struct origin *find_rename(struct scoreboard *sb,
458 struct commit *parent,
459 struct origin *origin)
461 struct origin *porigin = NULL;
462 struct diff_options diff_opts;
463 int i;
464 const char *paths[2];
466 diff_setup(&diff_opts);
467 DIFF_OPT_SET(&diff_opts, RECURSIVE);
468 diff_opts.detect_rename = DIFF_DETECT_RENAME;
469 diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;
470 diff_opts.single_follow = origin->path;
471 paths[0] = NULL;
472 diff_tree_setup_paths(paths, &diff_opts);
473 if (diff_setup_done(&diff_opts) < 0)
474 die("diff-setup");
476 if (is_null_sha1(origin->commit->object.sha1))
477 do_diff_cache(parent->tree->object.sha1, &diff_opts);
478 else
479 diff_tree_sha1(parent->tree->object.sha1,
480 origin->commit->tree->object.sha1,
481 "", &diff_opts);
482 diffcore_std(&diff_opts);
484 for (i = 0; i < diff_queued_diff.nr; i++) {
485 struct diff_filepair *p = diff_queued_diff.queue[i];
486 if ((p->status == 'R' || p->status == 'C') &&
487 !strcmp(p->two->path, origin->path)) {
488 porigin = get_origin(sb, parent, p->one->path);
489 hashcpy(porigin->blob_sha1, p->one->sha1);
490 break;
493 diff_flush(&diff_opts);
494 diff_tree_release_paths(&diff_opts);
495 return porigin;
499 * Link in a new blame entry to the scoreboard. Entries that cover the
500 * same line range have been removed from the scoreboard previously.
502 static void add_blame_entry(struct scoreboard *sb, struct blame_entry *e)
504 struct blame_entry *ent, *prev = NULL;
506 origin_incref(e->suspect);
508 for (ent = sb->ent; ent && ent->lno < e->lno; ent = ent->next)
509 prev = ent;
511 /* prev, if not NULL, is the last one that is below e */
512 e->prev = prev;
513 if (prev) {
514 e->next = prev->next;
515 prev->next = e;
517 else {
518 e->next = sb->ent;
519 sb->ent = e;
521 if (e->next)
522 e->next->prev = e;
526 * src typically is on-stack; we want to copy the information in it to
527 * a malloced blame_entry that is already on the linked list of the
528 * scoreboard. The origin of dst loses a refcnt while the origin of src
529 * gains one.
531 static void dup_entry(struct blame_entry *dst, struct blame_entry *src)
533 struct blame_entry *p, *n;
535 p = dst->prev;
536 n = dst->next;
537 origin_incref(src->suspect);
538 origin_decref(dst->suspect);
539 memcpy(dst, src, sizeof(*src));
540 dst->prev = p;
541 dst->next = n;
542 dst->score = 0;
545 static const char *nth_line(struct scoreboard *sb, long lno)
547 return sb->final_buf + sb->lineno[lno];
550 static const char *nth_line_cb(void *data, long lno)
552 return nth_line((struct scoreboard *)data, lno);
556 * It is known that lines between tlno to same came from parent, and e
557 * has an overlap with that range. it also is known that parent's
558 * line plno corresponds to e's line tlno.
560 * <---- e ----->
561 * <------>
562 * <------------>
563 * <------------>
564 * <------------------>
566 * Split e into potentially three parts; before this chunk, the chunk
567 * to be blamed for the parent, and after that portion.
569 static void split_overlap(struct blame_entry *split,
570 struct blame_entry *e,
571 int tlno, int plno, int same,
572 struct origin *parent)
574 int chunk_end_lno;
575 memset(split, 0, sizeof(struct blame_entry [3]));
577 if (e->s_lno < tlno) {
578 /* there is a pre-chunk part not blamed on parent */
579 split[0].suspect = origin_incref(e->suspect);
580 split[0].lno = e->lno;
581 split[0].s_lno = e->s_lno;
582 split[0].num_lines = tlno - e->s_lno;
583 split[1].lno = e->lno + tlno - e->s_lno;
584 split[1].s_lno = plno;
586 else {
587 split[1].lno = e->lno;
588 split[1].s_lno = plno + (e->s_lno - tlno);
591 if (same < e->s_lno + e->num_lines) {
592 /* there is a post-chunk part not blamed on parent */
593 split[2].suspect = origin_incref(e->suspect);
594 split[2].lno = e->lno + (same - e->s_lno);
595 split[2].s_lno = e->s_lno + (same - e->s_lno);
596 split[2].num_lines = e->s_lno + e->num_lines - same;
597 chunk_end_lno = split[2].lno;
599 else
600 chunk_end_lno = e->lno + e->num_lines;
601 split[1].num_lines = chunk_end_lno - split[1].lno;
604 * if it turns out there is nothing to blame the parent for,
605 * forget about the splitting. !split[1].suspect signals this.
607 if (split[1].num_lines < 1)
608 return;
609 split[1].suspect = origin_incref(parent);
613 * split_overlap() divided an existing blame e into up to three parts
614 * in split. Adjust the linked list of blames in the scoreboard to
615 * reflect the split.
617 static void split_blame(struct scoreboard *sb,
618 struct blame_entry *split,
619 struct blame_entry *e)
621 struct blame_entry *new_entry;
623 if (split[0].suspect && split[2].suspect) {
624 /* The first part (reuse storage for the existing entry e) */
625 dup_entry(e, &split[0]);
627 /* The last part -- me */
628 new_entry = xmalloc(sizeof(*new_entry));
629 memcpy(new_entry, &(split[2]), sizeof(struct blame_entry));
630 add_blame_entry(sb, new_entry);
632 /* ... and the middle part -- parent */
633 new_entry = xmalloc(sizeof(*new_entry));
634 memcpy(new_entry, &(split[1]), sizeof(struct blame_entry));
635 add_blame_entry(sb, new_entry);
637 else if (!split[0].suspect && !split[2].suspect)
639 * The parent covers the entire area; reuse storage for
640 * e and replace it with the parent.
642 dup_entry(e, &split[1]);
643 else if (split[0].suspect) {
644 /* me and then parent */
645 dup_entry(e, &split[0]);
647 new_entry = xmalloc(sizeof(*new_entry));
648 memcpy(new_entry, &(split[1]), sizeof(struct blame_entry));
649 add_blame_entry(sb, new_entry);
651 else {
652 /* parent and then me */
653 dup_entry(e, &split[1]);
655 new_entry = xmalloc(sizeof(*new_entry));
656 memcpy(new_entry, &(split[2]), sizeof(struct blame_entry));
657 add_blame_entry(sb, new_entry);
660 if (DEBUG) { /* sanity */
661 struct blame_entry *ent;
662 int lno = sb->ent->lno, corrupt = 0;
664 for (ent = sb->ent; ent; ent = ent->next) {
665 if (lno != ent->lno)
666 corrupt = 1;
667 if (ent->s_lno < 0)
668 corrupt = 1;
669 lno += ent->num_lines;
671 if (corrupt) {
672 lno = sb->ent->lno;
673 for (ent = sb->ent; ent; ent = ent->next) {
674 printf("L %8d l %8d n %8d\n",
675 lno, ent->lno, ent->num_lines);
676 lno = ent->lno + ent->num_lines;
678 die("oops");
684 * After splitting the blame, the origins used by the
685 * on-stack blame_entry should lose one refcnt each.
687 static void decref_split(struct blame_entry *split)
689 int i;
691 for (i = 0; i < 3; i++)
692 origin_decref(split[i].suspect);
696 * Helper for blame_chunk(). blame_entry e is known to overlap with
697 * the patch hunk; split it and pass blame to the parent.
699 static void blame_overlap(struct scoreboard *sb, struct blame_entry *e,
700 int tlno, int plno, int same,
701 struct origin *parent)
703 struct blame_entry split[3];
705 split_overlap(split, e, tlno, plno, same, parent);
706 if (split[1].suspect)
707 split_blame(sb, split, e);
708 decref_split(split);
712 * Find the line number of the last line the target is suspected for.
714 static int find_last_in_target(struct scoreboard *sb, struct origin *target)
716 struct blame_entry *e;
717 int last_in_target = -1;
719 for (e = sb->ent; e; e = e->next) {
720 if (e->guilty || !same_suspect(e->suspect, target))
721 continue;
722 if (last_in_target < e->s_lno + e->num_lines)
723 last_in_target = e->s_lno + e->num_lines;
725 return last_in_target;
729 * Process one hunk from the patch between the current suspect for
730 * blame_entry e and its parent. Find and split the overlap, and
731 * pass blame to the overlapping part to the parent.
733 static void blame_chunk(struct scoreboard *sb,
734 int tlno, int plno, int same,
735 struct origin *target, struct origin *parent)
737 struct blame_entry *e;
739 for (e = sb->ent; e; e = e->next) {
740 if (e->guilty || !same_suspect(e->suspect, target))
741 continue;
742 if (same <= e->s_lno)
743 continue;
744 if (tlno < e->s_lno + e->num_lines)
745 blame_overlap(sb, e, tlno, plno, same, parent);
749 struct blame_chunk_cb_data {
750 struct scoreboard *sb;
751 struct origin *target;
752 struct origin *parent;
753 long plno;
754 long tlno;
757 static void blame_chunk_cb(void *data, long same, long p_next, long t_next)
759 struct blame_chunk_cb_data *d = data;
760 blame_chunk(d->sb, d->tlno, d->plno, same, d->target, d->parent);
761 d->plno = p_next;
762 d->tlno = t_next;
766 * We are looking at the origin 'target' and aiming to pass blame
767 * for the lines it is suspected to its parent. Run diff to find
768 * which lines came from parent and pass blame for them.
770 static int pass_blame_to_parent(struct scoreboard *sb,
771 struct origin *target,
772 struct origin *parent)
774 int last_in_target;
775 mmfile_t file_p, file_o;
776 struct blame_chunk_cb_data d;
777 xpparam_t xpp;
778 xdemitconf_t xecfg;
779 memset(&d, 0, sizeof(d));
780 d.sb = sb; d.target = target; d.parent = parent;
781 last_in_target = find_last_in_target(sb, target);
782 if (last_in_target < 0)
783 return 1; /* nothing remains for this target */
785 fill_origin_blob(&sb->revs->diffopt, parent, &file_p);
786 fill_origin_blob(&sb->revs->diffopt, target, &file_o);
787 num_get_patch++;
789 memset(&xpp, 0, sizeof(xpp));
790 xpp.flags = xdl_opts;
791 memset(&xecfg, 0, sizeof(xecfg));
792 xecfg.ctxlen = 0;
793 xdi_diff_hunks(&file_p, &file_o, blame_chunk_cb, &d, &xpp, &xecfg);
794 /* The rest (i.e. anything after tlno) are the same as the parent */
795 blame_chunk(sb, d.tlno, d.plno, last_in_target, target, parent);
797 return 0;
801 * The lines in blame_entry after splitting blames many times can become
802 * very small and trivial, and at some point it becomes pointless to
803 * blame the parents. E.g. "\t\t}\n\t}\n\n" appears everywhere in any
804 * ordinary C program, and it is not worth to say it was copied from
805 * totally unrelated file in the parent.
807 * Compute how trivial the lines in the blame_entry are.
809 static unsigned ent_score(struct scoreboard *sb, struct blame_entry *e)
811 unsigned score;
812 const char *cp, *ep;
814 if (e->score)
815 return e->score;
817 score = 1;
818 cp = nth_line(sb, e->lno);
819 ep = nth_line(sb, e->lno + e->num_lines);
820 while (cp < ep) {
821 unsigned ch = *((unsigned char *)cp);
822 if (isalnum(ch))
823 score++;
824 cp++;
826 e->score = score;
827 return score;
831 * best_so_far[] and this[] are both a split of an existing blame_entry
832 * that passes blame to the parent. Maintain best_so_far the best split
833 * so far, by comparing this and best_so_far and copying this into
834 * bst_so_far as needed.
836 static void copy_split_if_better(struct scoreboard *sb,
837 struct blame_entry *best_so_far,
838 struct blame_entry *this)
840 int i;
842 if (!this[1].suspect)
843 return;
844 if (best_so_far[1].suspect) {
845 if (ent_score(sb, &this[1]) < ent_score(sb, &best_so_far[1]))
846 return;
849 for (i = 0; i < 3; i++)
850 origin_incref(this[i].suspect);
851 decref_split(best_so_far);
852 memcpy(best_so_far, this, sizeof(struct blame_entry [3]));
856 * We are looking at a part of the final image represented by
857 * ent (tlno and same are offset by ent->s_lno).
858 * tlno is where we are looking at in the final image.
859 * up to (but not including) same match preimage.
860 * plno is where we are looking at in the preimage.
862 * <-------------- final image ---------------------->
863 * <------ent------>
864 * ^tlno ^same
865 * <---------preimage----->
866 * ^plno
868 * All line numbers are 0-based.
870 static void handle_split(struct scoreboard *sb,
871 struct blame_entry *ent,
872 int tlno, int plno, int same,
873 struct origin *parent,
874 struct blame_entry *split)
876 if (ent->num_lines <= tlno)
877 return;
878 if (tlno < same) {
879 struct blame_entry this[3];
880 tlno += ent->s_lno;
881 same += ent->s_lno;
882 split_overlap(this, ent, tlno, plno, same, parent);
883 copy_split_if_better(sb, split, this);
884 decref_split(this);
888 struct handle_split_cb_data {
889 struct scoreboard *sb;
890 struct blame_entry *ent;
891 struct origin *parent;
892 struct blame_entry *split;
893 long plno;
894 long tlno;
897 static void handle_split_cb(void *data, long same, long p_next, long t_next)
899 struct handle_split_cb_data *d = data;
900 handle_split(d->sb, d->ent, d->tlno, d->plno, same, d->parent, d->split);
901 d->plno = p_next;
902 d->tlno = t_next;
906 * Find the lines from parent that are the same as ent so that
907 * we can pass blames to it. file_p has the blob contents for
908 * the parent.
910 static void find_copy_in_blob(struct scoreboard *sb,
911 struct blame_entry *ent,
912 struct origin *parent,
913 struct blame_entry *split,
914 mmfile_t *file_p)
916 const char *cp;
917 int cnt;
918 mmfile_t file_o;
919 struct handle_split_cb_data d;
920 xpparam_t xpp;
921 xdemitconf_t xecfg;
922 memset(&d, 0, sizeof(d));
923 d.sb = sb; d.ent = ent; d.parent = parent; d.split = split;
925 * Prepare mmfile that contains only the lines in ent.
927 cp = nth_line(sb, ent->lno);
928 file_o.ptr = (char *) cp;
929 cnt = ent->num_lines;
931 while (cnt && cp < sb->final_buf + sb->final_buf_size) {
932 if (*cp++ == '\n')
933 cnt--;
935 file_o.size = cp - file_o.ptr;
938 * file_o is a part of final image we are annotating.
939 * file_p partially may match that image.
941 memset(&xpp, 0, sizeof(xpp));
942 xpp.flags = xdl_opts;
943 memset(&xecfg, 0, sizeof(xecfg));
944 xecfg.ctxlen = 1;
945 memset(split, 0, sizeof(struct blame_entry [3]));
946 xdi_diff_hunks(file_p, &file_o, handle_split_cb, &d, &xpp, &xecfg);
947 /* remainder, if any, all match the preimage */
948 handle_split(sb, ent, d.tlno, d.plno, ent->num_lines, parent, split);
952 * See if lines currently target is suspected for can be attributed to
953 * parent.
955 static int find_move_in_parent(struct scoreboard *sb,
956 struct origin *target,
957 struct origin *parent)
959 int last_in_target, made_progress;
960 struct blame_entry *e, split[3];
961 mmfile_t file_p;
963 last_in_target = find_last_in_target(sb, target);
964 if (last_in_target < 0)
965 return 1; /* nothing remains for this target */
967 fill_origin_blob(&sb->revs->diffopt, parent, &file_p);
968 if (!file_p.ptr)
969 return 0;
971 made_progress = 1;
972 while (made_progress) {
973 made_progress = 0;
974 for (e = sb->ent; e; e = e->next) {
975 if (e->guilty || !same_suspect(e->suspect, target) ||
976 ent_score(sb, e) < blame_move_score)
977 continue;
978 find_copy_in_blob(sb, e, parent, split, &file_p);
979 if (split[1].suspect &&
980 blame_move_score < ent_score(sb, &split[1])) {
981 split_blame(sb, split, e);
982 made_progress = 1;
984 decref_split(split);
987 return 0;
990 struct blame_list {
991 struct blame_entry *ent;
992 struct blame_entry split[3];
996 * Count the number of entries the target is suspected for,
997 * and prepare a list of entry and the best split.
999 static struct blame_list *setup_blame_list(struct scoreboard *sb,
1000 struct origin *target,
1001 int min_score,
1002 int *num_ents_p)
1004 struct blame_entry *e;
1005 int num_ents, i;
1006 struct blame_list *blame_list = NULL;
1008 for (e = sb->ent, num_ents = 0; e; e = e->next)
1009 if (!e->scanned && !e->guilty &&
1010 same_suspect(e->suspect, target) &&
1011 min_score < ent_score(sb, e))
1012 num_ents++;
1013 if (num_ents) {
1014 blame_list = xcalloc(num_ents, sizeof(struct blame_list));
1015 for (e = sb->ent, i = 0; e; e = e->next)
1016 if (!e->scanned && !e->guilty &&
1017 same_suspect(e->suspect, target) &&
1018 min_score < ent_score(sb, e))
1019 blame_list[i++].ent = e;
1021 *num_ents_p = num_ents;
1022 return blame_list;
1026 * Reset the scanned status on all entries.
1028 static void reset_scanned_flag(struct scoreboard *sb)
1030 struct blame_entry *e;
1031 for (e = sb->ent; e; e = e->next)
1032 e->scanned = 0;
1036 * For lines target is suspected for, see if we can find code movement
1037 * across file boundary from the parent commit. porigin is the path
1038 * in the parent we already tried.
1040 static int find_copy_in_parent(struct scoreboard *sb,
1041 struct origin *target,
1042 struct commit *parent,
1043 struct origin *porigin,
1044 int opt)
1046 struct diff_options diff_opts;
1047 const char *paths[1];
1048 int i, j;
1049 int retval;
1050 struct blame_list *blame_list;
1051 int num_ents;
1053 blame_list = setup_blame_list(sb, target, blame_copy_score, &num_ents);
1054 if (!blame_list)
1055 return 1; /* nothing remains for this target */
1057 diff_setup(&diff_opts);
1058 DIFF_OPT_SET(&diff_opts, RECURSIVE);
1059 diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;
1061 paths[0] = NULL;
1062 diff_tree_setup_paths(paths, &diff_opts);
1063 if (diff_setup_done(&diff_opts) < 0)
1064 die("diff-setup");
1066 /* Try "find copies harder" on new path if requested;
1067 * we do not want to use diffcore_rename() actually to
1068 * match things up; find_copies_harder is set only to
1069 * force diff_tree_sha1() to feed all filepairs to diff_queue,
1070 * and this code needs to be after diff_setup_done(), which
1071 * usually makes find-copies-harder imply copy detection.
1073 if ((opt & PICKAXE_BLAME_COPY_HARDEST)
1074 || ((opt & PICKAXE_BLAME_COPY_HARDER)
1075 && (!porigin || strcmp(target->path, porigin->path))))
1076 DIFF_OPT_SET(&diff_opts, FIND_COPIES_HARDER);
1078 if (is_null_sha1(target->commit->object.sha1))
1079 do_diff_cache(parent->tree->object.sha1, &diff_opts);
1080 else
1081 diff_tree_sha1(parent->tree->object.sha1,
1082 target->commit->tree->object.sha1,
1083 "", &diff_opts);
1085 if (!DIFF_OPT_TST(&diff_opts, FIND_COPIES_HARDER))
1086 diffcore_std(&diff_opts);
1088 retval = 0;
1089 while (1) {
1090 int made_progress = 0;
1092 for (i = 0; i < diff_queued_diff.nr; i++) {
1093 struct diff_filepair *p = diff_queued_diff.queue[i];
1094 struct origin *norigin;
1095 mmfile_t file_p;
1096 struct blame_entry this[3];
1098 if (!DIFF_FILE_VALID(p->one))
1099 continue; /* does not exist in parent */
1100 if (S_ISGITLINK(p->one->mode))
1101 continue; /* ignore git links */
1102 if (porigin && !strcmp(p->one->path, porigin->path))
1103 /* find_move already dealt with this path */
1104 continue;
1106 norigin = get_origin(sb, parent, p->one->path);
1107 hashcpy(norigin->blob_sha1, p->one->sha1);
1108 fill_origin_blob(&sb->revs->diffopt, norigin, &file_p);
1109 if (!file_p.ptr)
1110 continue;
1112 for (j = 0; j < num_ents; j++) {
1113 find_copy_in_blob(sb, blame_list[j].ent,
1114 norigin, this, &file_p);
1115 copy_split_if_better(sb, blame_list[j].split,
1116 this);
1117 decref_split(this);
1119 origin_decref(norigin);
1122 for (j = 0; j < num_ents; j++) {
1123 struct blame_entry *split = blame_list[j].split;
1124 if (split[1].suspect &&
1125 blame_copy_score < ent_score(sb, &split[1])) {
1126 split_blame(sb, split, blame_list[j].ent);
1127 made_progress = 1;
1129 else
1130 blame_list[j].ent->scanned = 1;
1131 decref_split(split);
1133 free(blame_list);
1135 if (!made_progress)
1136 break;
1137 blame_list = setup_blame_list(sb, target, blame_copy_score, &num_ents);
1138 if (!blame_list) {
1139 retval = 1;
1140 break;
1143 reset_scanned_flag(sb);
1144 diff_flush(&diff_opts);
1145 diff_tree_release_paths(&diff_opts);
1146 return retval;
1150 * The blobs of origin and porigin exactly match, so everything
1151 * origin is suspected for can be blamed on the parent.
1153 static void pass_whole_blame(struct scoreboard *sb,
1154 struct origin *origin, struct origin *porigin)
1156 struct blame_entry *e;
1158 if (!porigin->file.ptr && origin->file.ptr) {
1159 /* Steal its file */
1160 porigin->file = origin->file;
1161 origin->file.ptr = NULL;
1163 for (e = sb->ent; e; e = e->next) {
1164 if (!same_suspect(e->suspect, origin))
1165 continue;
1166 origin_incref(porigin);
1167 origin_decref(e->suspect);
1168 e->suspect = porigin;
1173 * We pass blame from the current commit to its parents. We keep saying
1174 * "parent" (and "porigin"), but what we mean is to find scapegoat to
1175 * exonerate ourselves.
1177 static struct commit_list *first_scapegoat(struct rev_info *revs, struct commit *commit)
1179 if (!reverse)
1180 return commit->parents;
1181 return lookup_decoration(&revs->children, &commit->object);
1184 static int num_scapegoats(struct rev_info *revs, struct commit *commit)
1186 int cnt;
1187 struct commit_list *l = first_scapegoat(revs, commit);
1188 for (cnt = 0; l; l = l->next)
1189 cnt++;
1190 return cnt;
1193 #define MAXSG 16
1195 static void pass_blame(struct scoreboard *sb, struct origin *origin, int opt)
1197 struct rev_info *revs = sb->revs;
1198 int i, pass, num_sg;
1199 struct commit *commit = origin->commit;
1200 struct commit_list *sg;
1201 struct origin *sg_buf[MAXSG];
1202 struct origin *porigin, **sg_origin = sg_buf;
1204 num_sg = num_scapegoats(revs, commit);
1205 if (!num_sg)
1206 goto finish;
1207 else if (num_sg < ARRAY_SIZE(sg_buf))
1208 memset(sg_buf, 0, sizeof(sg_buf));
1209 else
1210 sg_origin = xcalloc(num_sg, sizeof(*sg_origin));
1213 * The first pass looks for unrenamed path to optimize for
1214 * common cases, then we look for renames in the second pass.
1216 for (pass = 0; pass < 2; pass++) {
1217 struct origin *(*find)(struct scoreboard *,
1218 struct commit *, struct origin *);
1219 find = pass ? find_rename : find_origin;
1221 for (i = 0, sg = first_scapegoat(revs, commit);
1222 i < num_sg && sg;
1223 sg = sg->next, i++) {
1224 struct commit *p = sg->item;
1225 int j, same;
1227 if (sg_origin[i])
1228 continue;
1229 if (parse_commit(p))
1230 continue;
1231 porigin = find(sb, p, origin);
1232 if (!porigin)
1233 continue;
1234 if (!hashcmp(porigin->blob_sha1, origin->blob_sha1)) {
1235 pass_whole_blame(sb, origin, porigin);
1236 origin_decref(porigin);
1237 goto finish;
1239 for (j = same = 0; j < i; j++)
1240 if (sg_origin[j] &&
1241 !hashcmp(sg_origin[j]->blob_sha1,
1242 porigin->blob_sha1)) {
1243 same = 1;
1244 break;
1246 if (!same)
1247 sg_origin[i] = porigin;
1248 else
1249 origin_decref(porigin);
1253 num_commits++;
1254 for (i = 0, sg = first_scapegoat(revs, commit);
1255 i < num_sg && sg;
1256 sg = sg->next, i++) {
1257 struct origin *porigin = sg_origin[i];
1258 if (!porigin)
1259 continue;
1260 if (!origin->previous) {
1261 origin_incref(porigin);
1262 origin->previous = porigin;
1264 if (pass_blame_to_parent(sb, origin, porigin))
1265 goto finish;
1269 * Optionally find moves in parents' files.
1271 if (opt & PICKAXE_BLAME_MOVE)
1272 for (i = 0, sg = first_scapegoat(revs, commit);
1273 i < num_sg && sg;
1274 sg = sg->next, i++) {
1275 struct origin *porigin = sg_origin[i];
1276 if (!porigin)
1277 continue;
1278 if (find_move_in_parent(sb, origin, porigin))
1279 goto finish;
1283 * Optionally find copies from parents' files.
1285 if (opt & PICKAXE_BLAME_COPY)
1286 for (i = 0, sg = first_scapegoat(revs, commit);
1287 i < num_sg && sg;
1288 sg = sg->next, i++) {
1289 struct origin *porigin = sg_origin[i];
1290 if (find_copy_in_parent(sb, origin, sg->item,
1291 porigin, opt))
1292 goto finish;
1295 finish:
1296 for (i = 0; i < num_sg; i++) {
1297 if (sg_origin[i]) {
1298 drop_origin_blob(sg_origin[i]);
1299 origin_decref(sg_origin[i]);
1302 drop_origin_blob(origin);
1303 if (sg_buf != sg_origin)
1304 free(sg_origin);
1308 * Information on commits, used for output.
1310 struct commit_info
1312 const char *author;
1313 const char *author_mail;
1314 unsigned long author_time;
1315 const char *author_tz;
1317 /* filled only when asked for details */
1318 const char *committer;
1319 const char *committer_mail;
1320 unsigned long committer_time;
1321 const char *committer_tz;
1323 const char *summary;
1327 * Parse author/committer line in the commit object buffer
1329 static void get_ac_line(const char *inbuf, const char *what,
1330 int person_len, char *person,
1331 int mail_len, char *mail,
1332 unsigned long *time, const char **tz)
1334 int len, tzlen, maillen;
1335 char *tmp, *endp, *timepos, *mailpos;
1337 tmp = strstr(inbuf, what);
1338 if (!tmp)
1339 goto error_out;
1340 tmp += strlen(what);
1341 endp = strchr(tmp, '\n');
1342 if (!endp)
1343 len = strlen(tmp);
1344 else
1345 len = endp - tmp;
1346 if (person_len <= len) {
1347 error_out:
1348 /* Ugh */
1349 *tz = "(unknown)";
1350 strcpy(person, *tz);
1351 strcpy(mail, *tz);
1352 *time = 0;
1353 return;
1355 memcpy(person, tmp, len);
1357 tmp = person;
1358 tmp += len;
1359 *tmp = 0;
1360 while (person < tmp && *tmp != ' ')
1361 tmp--;
1362 if (tmp <= person)
1363 goto error_out;
1364 *tz = tmp+1;
1365 tzlen = (person+len)-(tmp+1);
1367 *tmp = 0;
1368 while (person < tmp && *tmp != ' ')
1369 tmp--;
1370 if (tmp <= person)
1371 goto error_out;
1372 *time = strtoul(tmp, NULL, 10);
1373 timepos = tmp;
1375 *tmp = 0;
1376 while (person < tmp && *tmp != ' ')
1377 tmp--;
1378 if (tmp <= person)
1379 return;
1380 mailpos = tmp + 1;
1381 *tmp = 0;
1382 maillen = timepos - tmp;
1383 memcpy(mail, mailpos, maillen);
1385 if (!mailmap.nr)
1386 return;
1389 * mailmap expansion may make the name longer.
1390 * make room by pushing stuff down.
1392 tmp = person + person_len - (tzlen + 1);
1393 memmove(tmp, *tz, tzlen);
1394 tmp[tzlen] = 0;
1395 *tz = tmp;
1398 * Now, convert both name and e-mail using mailmap
1400 if (map_user(&mailmap, mail+1, mail_len-1, person, tmp-person-1)) {
1401 /* Add a trailing '>' to email, since map_user returns plain emails
1402 Note: It already has '<', since we replace from mail+1 */
1403 mailpos = memchr(mail, '\0', mail_len);
1404 if (mailpos && mailpos-mail < mail_len - 1) {
1405 *mailpos = '>';
1406 *(mailpos+1) = '\0';
1411 static void get_commit_info(struct commit *commit,
1412 struct commit_info *ret,
1413 int detailed)
1415 int len;
1416 const char *subject;
1417 char *reencoded, *message;
1418 static char author_name[1024];
1419 static char author_mail[1024];
1420 static char committer_name[1024];
1421 static char committer_mail[1024];
1422 static char summary_buf[1024];
1425 * We've operated without save_commit_buffer, so
1426 * we now need to populate them for output.
1428 if (!commit->buffer) {
1429 enum object_type type;
1430 unsigned long size;
1431 commit->buffer =
1432 read_sha1_file(commit->object.sha1, &type, &size);
1433 if (!commit->buffer)
1434 die("Cannot read commit %s",
1435 sha1_to_hex(commit->object.sha1));
1437 reencoded = reencode_commit_message(commit, NULL);
1438 message = reencoded ? reencoded : commit->buffer;
1439 ret->author = author_name;
1440 ret->author_mail = author_mail;
1441 get_ac_line(message, "\nauthor ",
1442 sizeof(author_name), author_name,
1443 sizeof(author_mail), author_mail,
1444 &ret->author_time, &ret->author_tz);
1446 if (!detailed) {
1447 free(reencoded);
1448 return;
1451 ret->committer = committer_name;
1452 ret->committer_mail = committer_mail;
1453 get_ac_line(message, "\ncommitter ",
1454 sizeof(committer_name), committer_name,
1455 sizeof(committer_mail), committer_mail,
1456 &ret->committer_time, &ret->committer_tz);
1458 ret->summary = summary_buf;
1459 len = find_commit_subject(message, &subject);
1460 if (len && len < sizeof(summary_buf)) {
1461 memcpy(summary_buf, subject, len);
1462 summary_buf[len] = 0;
1463 } else {
1464 sprintf(summary_buf, "(%s)", sha1_to_hex(commit->object.sha1));
1466 free(reencoded);
1470 * To allow LF and other nonportable characters in pathnames,
1471 * they are c-style quoted as needed.
1473 static void write_filename_info(const char *path)
1475 printf("filename ");
1476 write_name_quoted(path, stdout, '\n');
1480 * Porcelain/Incremental format wants to show a lot of details per
1481 * commit. Instead of repeating this every line, emit it only once,
1482 * the first time each commit appears in the output.
1484 static int emit_one_suspect_detail(struct origin *suspect)
1486 struct commit_info ci;
1488 if (suspect->commit->object.flags & METAINFO_SHOWN)
1489 return 0;
1491 suspect->commit->object.flags |= METAINFO_SHOWN;
1492 get_commit_info(suspect->commit, &ci, 1);
1493 printf("author %s\n", ci.author);
1494 printf("author-mail %s\n", ci.author_mail);
1495 printf("author-time %lu\n", ci.author_time);
1496 printf("author-tz %s\n", ci.author_tz);
1497 printf("committer %s\n", ci.committer);
1498 printf("committer-mail %s\n", ci.committer_mail);
1499 printf("committer-time %lu\n", ci.committer_time);
1500 printf("committer-tz %s\n", ci.committer_tz);
1501 printf("summary %s\n", ci.summary);
1502 if (suspect->commit->object.flags & UNINTERESTING)
1503 printf("boundary\n");
1504 if (suspect->previous) {
1505 struct origin *prev = suspect->previous;
1506 printf("previous %s ", sha1_to_hex(prev->commit->object.sha1));
1507 write_name_quoted(prev->path, stdout, '\n');
1509 return 1;
1513 * The blame_entry is found to be guilty for the range. Mark it
1514 * as such, and show it in incremental output.
1516 static void found_guilty_entry(struct blame_entry *ent)
1518 if (ent->guilty)
1519 return;
1520 ent->guilty = 1;
1521 if (incremental) {
1522 struct origin *suspect = ent->suspect;
1524 printf("%s %d %d %d\n",
1525 sha1_to_hex(suspect->commit->object.sha1),
1526 ent->s_lno + 1, ent->lno + 1, ent->num_lines);
1527 emit_one_suspect_detail(suspect);
1528 write_filename_info(suspect->path);
1529 maybe_flush_or_die(stdout, "stdout");
1534 * The main loop -- while the scoreboard has lines whose true origin
1535 * is still unknown, pick one blame_entry, and allow its current
1536 * suspect to pass blames to its parents.
1538 static void assign_blame(struct scoreboard *sb, int opt)
1540 struct rev_info *revs = sb->revs;
1542 while (1) {
1543 struct blame_entry *ent;
1544 struct commit *commit;
1545 struct origin *suspect = NULL;
1547 /* find one suspect to break down */
1548 for (ent = sb->ent; !suspect && ent; ent = ent->next)
1549 if (!ent->guilty)
1550 suspect = ent->suspect;
1551 if (!suspect)
1552 return; /* all done */
1555 * We will use this suspect later in the loop,
1556 * so hold onto it in the meantime.
1558 origin_incref(suspect);
1559 commit = suspect->commit;
1560 if (!commit->object.parsed)
1561 parse_commit(commit);
1562 if (reverse ||
1563 (!(commit->object.flags & UNINTERESTING) &&
1564 !(revs->max_age != -1 && commit->date < revs->max_age)))
1565 pass_blame(sb, suspect, opt);
1566 else {
1567 commit->object.flags |= UNINTERESTING;
1568 if (commit->object.parsed)
1569 mark_parents_uninteresting(commit);
1571 /* treat root commit as boundary */
1572 if (!commit->parents && !show_root)
1573 commit->object.flags |= UNINTERESTING;
1575 /* Take responsibility for the remaining entries */
1576 for (ent = sb->ent; ent; ent = ent->next)
1577 if (same_suspect(ent->suspect, suspect))
1578 found_guilty_entry(ent);
1579 origin_decref(suspect);
1581 if (DEBUG) /* sanity */
1582 sanity_check_refcnt(sb);
1586 static const char *format_time(unsigned long time, const char *tz_str,
1587 int show_raw_time)
1589 static char time_buf[128];
1590 const char *time_str;
1591 int time_len;
1592 int tz;
1594 if (show_raw_time) {
1595 sprintf(time_buf, "%lu %s", time, tz_str);
1597 else {
1598 tz = atoi(tz_str);
1599 time_str = show_date(time, tz, blame_date_mode);
1600 time_len = strlen(time_str);
1601 memcpy(time_buf, time_str, time_len);
1602 memset(time_buf + time_len, ' ', blame_date_width - time_len);
1604 return time_buf;
1607 #define OUTPUT_ANNOTATE_COMPAT 001
1608 #define OUTPUT_LONG_OBJECT_NAME 002
1609 #define OUTPUT_RAW_TIMESTAMP 004
1610 #define OUTPUT_PORCELAIN 010
1611 #define OUTPUT_SHOW_NAME 020
1612 #define OUTPUT_SHOW_NUMBER 040
1613 #define OUTPUT_SHOW_SCORE 0100
1614 #define OUTPUT_NO_AUTHOR 0200
1616 static void emit_porcelain(struct scoreboard *sb, struct blame_entry *ent)
1618 int cnt;
1619 const char *cp;
1620 struct origin *suspect = ent->suspect;
1621 char hex[41];
1623 strcpy(hex, sha1_to_hex(suspect->commit->object.sha1));
1624 printf("%s%c%d %d %d\n",
1625 hex,
1626 ent->guilty ? ' ' : '*', /* purely for debugging */
1627 ent->s_lno + 1,
1628 ent->lno + 1,
1629 ent->num_lines);
1630 if (emit_one_suspect_detail(suspect) ||
1631 (suspect->commit->object.flags & MORE_THAN_ONE_PATH))
1632 write_filename_info(suspect->path);
1634 cp = nth_line(sb, ent->lno);
1635 for (cnt = 0; cnt < ent->num_lines; cnt++) {
1636 char ch;
1637 if (cnt)
1638 printf("%s %d %d\n", hex,
1639 ent->s_lno + 1 + cnt,
1640 ent->lno + 1 + cnt);
1641 putchar('\t');
1642 do {
1643 ch = *cp++;
1644 putchar(ch);
1645 } while (ch != '\n' &&
1646 cp < sb->final_buf + sb->final_buf_size);
1649 if (sb->final_buf_size && cp[-1] != '\n')
1650 putchar('\n');
1653 static void emit_other(struct scoreboard *sb, struct blame_entry *ent, int opt)
1655 int cnt;
1656 const char *cp;
1657 struct origin *suspect = ent->suspect;
1658 struct commit_info ci;
1659 char hex[41];
1660 int show_raw_time = !!(opt & OUTPUT_RAW_TIMESTAMP);
1662 get_commit_info(suspect->commit, &ci, 1);
1663 strcpy(hex, sha1_to_hex(suspect->commit->object.sha1));
1665 cp = nth_line(sb, ent->lno);
1666 for (cnt = 0; cnt < ent->num_lines; cnt++) {
1667 char ch;
1668 int length = (opt & OUTPUT_LONG_OBJECT_NAME) ? 40 : 8;
1670 if (suspect->commit->object.flags & UNINTERESTING) {
1671 if (blank_boundary)
1672 memset(hex, ' ', length);
1673 else if (!(opt & OUTPUT_ANNOTATE_COMPAT)) {
1674 length--;
1675 putchar('^');
1679 printf("%.*s", length, hex);
1680 if (opt & OUTPUT_ANNOTATE_COMPAT)
1681 printf("\t(%10s\t%10s\t%d)", ci.author,
1682 format_time(ci.author_time, ci.author_tz,
1683 show_raw_time),
1684 ent->lno + 1 + cnt);
1685 else {
1686 if (opt & OUTPUT_SHOW_SCORE)
1687 printf(" %*d %02d",
1688 max_score_digits, ent->score,
1689 ent->suspect->refcnt);
1690 if (opt & OUTPUT_SHOW_NAME)
1691 printf(" %-*.*s", longest_file, longest_file,
1692 suspect->path);
1693 if (opt & OUTPUT_SHOW_NUMBER)
1694 printf(" %*d", max_orig_digits,
1695 ent->s_lno + 1 + cnt);
1697 if (!(opt & OUTPUT_NO_AUTHOR)) {
1698 int pad = longest_author - utf8_strwidth(ci.author);
1699 printf(" (%s%*s %10s",
1700 ci.author, pad, "",
1701 format_time(ci.author_time,
1702 ci.author_tz,
1703 show_raw_time));
1705 printf(" %*d) ",
1706 max_digits, ent->lno + 1 + cnt);
1708 do {
1709 ch = *cp++;
1710 putchar(ch);
1711 } while (ch != '\n' &&
1712 cp < sb->final_buf + sb->final_buf_size);
1715 if (sb->final_buf_size && cp[-1] != '\n')
1716 putchar('\n');
1719 static void output(struct scoreboard *sb, int option)
1721 struct blame_entry *ent;
1723 if (option & OUTPUT_PORCELAIN) {
1724 for (ent = sb->ent; ent; ent = ent->next) {
1725 struct blame_entry *oth;
1726 struct origin *suspect = ent->suspect;
1727 struct commit *commit = suspect->commit;
1728 if (commit->object.flags & MORE_THAN_ONE_PATH)
1729 continue;
1730 for (oth = ent->next; oth; oth = oth->next) {
1731 if ((oth->suspect->commit != commit) ||
1732 !strcmp(oth->suspect->path, suspect->path))
1733 continue;
1734 commit->object.flags |= MORE_THAN_ONE_PATH;
1735 break;
1740 for (ent = sb->ent; ent; ent = ent->next) {
1741 if (option & OUTPUT_PORCELAIN)
1742 emit_porcelain(sb, ent);
1743 else {
1744 emit_other(sb, ent, option);
1750 * To allow quick access to the contents of nth line in the
1751 * final image, prepare an index in the scoreboard.
1753 static int prepare_lines(struct scoreboard *sb)
1755 const char *buf = sb->final_buf;
1756 unsigned long len = sb->final_buf_size;
1757 int num = 0, incomplete = 0, bol = 1;
1759 if (len && buf[len-1] != '\n')
1760 incomplete++; /* incomplete line at the end */
1761 while (len--) {
1762 if (bol) {
1763 sb->lineno = xrealloc(sb->lineno,
1764 sizeof(int *) * (num + 1));
1765 sb->lineno[num] = buf - sb->final_buf;
1766 bol = 0;
1768 if (*buf++ == '\n') {
1769 num++;
1770 bol = 1;
1773 sb->lineno = xrealloc(sb->lineno,
1774 sizeof(int *) * (num + incomplete + 1));
1775 sb->lineno[num + incomplete] = buf - sb->final_buf;
1776 sb->num_lines = num + incomplete;
1777 return sb->num_lines;
1781 * Add phony grafts for use with -S; this is primarily to
1782 * support git's cvsserver that wants to give a linear history
1783 * to its clients.
1785 static int read_ancestry(const char *graft_file)
1787 FILE *fp = fopen(graft_file, "r");
1788 char buf[1024];
1789 if (!fp)
1790 return -1;
1791 while (fgets(buf, sizeof(buf), fp)) {
1792 /* The format is just "Commit Parent1 Parent2 ...\n" */
1793 int len = strlen(buf);
1794 struct commit_graft *graft = read_graft_line(buf, len);
1795 if (graft)
1796 register_commit_graft(graft, 0);
1798 fclose(fp);
1799 return 0;
1803 * How many columns do we need to show line numbers in decimal?
1805 static int lineno_width(int lines)
1807 int i, width;
1809 for (width = 1, i = 10; i <= lines; width++)
1810 i *= 10;
1811 return width;
1815 * How many columns do we need to show line numbers, authors,
1816 * and filenames?
1818 static void find_alignment(struct scoreboard *sb, int *option)
1820 int longest_src_lines = 0;
1821 int longest_dst_lines = 0;
1822 unsigned largest_score = 0;
1823 struct blame_entry *e;
1825 for (e = sb->ent; e; e = e->next) {
1826 struct origin *suspect = e->suspect;
1827 struct commit_info ci;
1828 int num;
1830 if (strcmp(suspect->path, sb->path))
1831 *option |= OUTPUT_SHOW_NAME;
1832 num = strlen(suspect->path);
1833 if (longest_file < num)
1834 longest_file = num;
1835 if (!(suspect->commit->object.flags & METAINFO_SHOWN)) {
1836 suspect->commit->object.flags |= METAINFO_SHOWN;
1837 get_commit_info(suspect->commit, &ci, 1);
1838 num = utf8_strwidth(ci.author);
1839 if (longest_author < num)
1840 longest_author = num;
1842 num = e->s_lno + e->num_lines;
1843 if (longest_src_lines < num)
1844 longest_src_lines = num;
1845 num = e->lno + e->num_lines;
1846 if (longest_dst_lines < num)
1847 longest_dst_lines = num;
1848 if (largest_score < ent_score(sb, e))
1849 largest_score = ent_score(sb, e);
1851 max_orig_digits = lineno_width(longest_src_lines);
1852 max_digits = lineno_width(longest_dst_lines);
1853 max_score_digits = lineno_width(largest_score);
1857 * For debugging -- origin is refcounted, and this asserts that
1858 * we do not underflow.
1860 static void sanity_check_refcnt(struct scoreboard *sb)
1862 int baa = 0;
1863 struct blame_entry *ent;
1865 for (ent = sb->ent; ent; ent = ent->next) {
1866 /* Nobody should have zero or negative refcnt */
1867 if (ent->suspect->refcnt <= 0) {
1868 fprintf(stderr, "%s in %s has negative refcnt %d\n",
1869 ent->suspect->path,
1870 sha1_to_hex(ent->suspect->commit->object.sha1),
1871 ent->suspect->refcnt);
1872 baa = 1;
1875 if (baa) {
1876 int opt = 0160;
1877 find_alignment(sb, &opt);
1878 output(sb, opt);
1879 die("Baa %d!", baa);
1884 * Used for the command line parsing; check if the path exists
1885 * in the working tree.
1887 static int has_string_in_work_tree(const char *path)
1889 struct stat st;
1890 return !lstat(path, &st);
1893 static unsigned parse_score(const char *arg)
1895 char *end;
1896 unsigned long score = strtoul(arg, &end, 10);
1897 if (*end)
1898 return 0;
1899 return score;
1902 static const char *add_prefix(const char *prefix, const char *path)
1904 return prefix_path(prefix, prefix ? strlen(prefix) : 0, path);
1908 * Parsing of -L option
1910 static void prepare_blame_range(struct scoreboard *sb,
1911 const char *bottomtop,
1912 long lno,
1913 long *bottom, long *top)
1915 const char *term;
1917 term = parse_loc(bottomtop, nth_line_cb, sb, lno, 1, bottom);
1918 if (*term == ',') {
1919 term = parse_loc(term + 1, nth_line_cb, sb, lno, *bottom + 1, top);
1920 if (*term)
1921 usage(blame_usage);
1923 if (*term)
1924 usage(blame_usage);
1927 static int git_blame_config(const char *var, const char *value, void *cb)
1929 if (!strcmp(var, "blame.showroot")) {
1930 show_root = git_config_bool(var, value);
1931 return 0;
1933 if (!strcmp(var, "blame.blankboundary")) {
1934 blank_boundary = git_config_bool(var, value);
1935 return 0;
1937 if (!strcmp(var, "blame.date")) {
1938 if (!value)
1939 return config_error_nonbool(var);
1940 blame_date_mode = parse_date_format(value);
1941 return 0;
1944 switch (userdiff_config(var, value)) {
1945 case 0:
1946 break;
1947 case -1:
1948 return -1;
1949 default:
1950 return 0;
1953 return git_default_config(var, value, cb);
1957 * Prepare a dummy commit that represents the work tree (or staged) item.
1958 * Note that annotating work tree item never works in the reverse.
1960 static struct commit *fake_working_tree_commit(struct diff_options *opt,
1961 const char *path,
1962 const char *contents_from)
1964 struct commit *commit;
1965 struct origin *origin;
1966 unsigned char head_sha1[20];
1967 struct strbuf buf = STRBUF_INIT;
1968 const char *ident;
1969 time_t now;
1970 int size, len;
1971 struct cache_entry *ce;
1972 unsigned mode;
1974 if (get_sha1("HEAD", head_sha1))
1975 die("No such ref: HEAD");
1977 time(&now);
1978 commit = xcalloc(1, sizeof(*commit));
1979 commit->parents = xcalloc(1, sizeof(*commit->parents));
1980 commit->parents->item = lookup_commit_reference(head_sha1);
1981 commit->object.parsed = 1;
1982 commit->date = now;
1983 commit->object.type = OBJ_COMMIT;
1985 origin = make_origin(commit, path);
1987 if (!contents_from || strcmp("-", contents_from)) {
1988 struct stat st;
1989 const char *read_from;
1990 unsigned long buf_len;
1992 if (contents_from) {
1993 if (stat(contents_from, &st) < 0)
1994 die_errno("Cannot stat '%s'", contents_from);
1995 read_from = contents_from;
1997 else {
1998 if (lstat(path, &st) < 0)
1999 die_errno("Cannot lstat '%s'", path);
2000 read_from = path;
2002 mode = canon_mode(st.st_mode);
2004 switch (st.st_mode & S_IFMT) {
2005 case S_IFREG:
2006 if (DIFF_OPT_TST(opt, ALLOW_TEXTCONV) &&
2007 textconv_object(read_from, null_sha1, &buf.buf, &buf_len))
2008 buf.len = buf_len;
2009 else if (strbuf_read_file(&buf, read_from, st.st_size) != st.st_size)
2010 die_errno("cannot open or read '%s'", read_from);
2011 break;
2012 case S_IFLNK:
2013 if (strbuf_readlink(&buf, read_from, st.st_size) < 0)
2014 die_errno("cannot readlink '%s'", read_from);
2015 break;
2016 default:
2017 die("unsupported file type %s", read_from);
2020 else {
2021 /* Reading from stdin */
2022 contents_from = "standard input";
2023 mode = 0;
2024 if (strbuf_read(&buf, 0, 0) < 0)
2025 die_errno("failed to read from stdin");
2027 convert_to_git(path, buf.buf, buf.len, &buf, 0);
2028 origin->file.ptr = buf.buf;
2029 origin->file.size = buf.len;
2030 pretend_sha1_file(buf.buf, buf.len, OBJ_BLOB, origin->blob_sha1);
2031 commit->util = origin;
2034 * Read the current index, replace the path entry with
2035 * origin->blob_sha1 without mucking with its mode or type
2036 * bits; we are not going to write this index out -- we just
2037 * want to run "diff-index --cached".
2039 discard_cache();
2040 read_cache();
2042 len = strlen(path);
2043 if (!mode) {
2044 int pos = cache_name_pos(path, len);
2045 if (0 <= pos)
2046 mode = active_cache[pos]->ce_mode;
2047 else
2048 /* Let's not bother reading from HEAD tree */
2049 mode = S_IFREG | 0644;
2051 size = cache_entry_size(len);
2052 ce = xcalloc(1, size);
2053 hashcpy(ce->sha1, origin->blob_sha1);
2054 memcpy(ce->name, path, len);
2055 ce->ce_flags = create_ce_flags(len, 0);
2056 ce->ce_mode = create_ce_mode(mode);
2057 add_cache_entry(ce, ADD_CACHE_OK_TO_ADD|ADD_CACHE_OK_TO_REPLACE);
2060 * We are not going to write this out, so this does not matter
2061 * right now, but someday we might optimize diff-index --cached
2062 * with cache-tree information.
2064 cache_tree_invalidate_path(active_cache_tree, path);
2066 commit->buffer = xmalloc(400);
2067 ident = fmt_ident("Not Committed Yet", "not.committed.yet", NULL, 0);
2068 snprintf(commit->buffer, 400,
2069 "tree 0000000000000000000000000000000000000000\n"
2070 "parent %s\n"
2071 "author %s\n"
2072 "committer %s\n\n"
2073 "Version of %s from %s\n",
2074 sha1_to_hex(head_sha1),
2075 ident, ident, path, contents_from ? contents_from : path);
2076 return commit;
2079 static const char *prepare_final(struct scoreboard *sb)
2081 int i;
2082 const char *final_commit_name = NULL;
2083 struct rev_info *revs = sb->revs;
2086 * There must be one and only one positive commit in the
2087 * revs->pending array.
2089 for (i = 0; i < revs->pending.nr; i++) {
2090 struct object *obj = revs->pending.objects[i].item;
2091 if (obj->flags & UNINTERESTING)
2092 continue;
2093 while (obj->type == OBJ_TAG)
2094 obj = deref_tag(obj, NULL, 0);
2095 if (obj->type != OBJ_COMMIT)
2096 die("Non commit %s?", revs->pending.objects[i].name);
2097 if (sb->final)
2098 die("More than one commit to dig from %s and %s?",
2099 revs->pending.objects[i].name,
2100 final_commit_name);
2101 sb->final = (struct commit *) obj;
2102 final_commit_name = revs->pending.objects[i].name;
2104 return final_commit_name;
2107 static const char *prepare_initial(struct scoreboard *sb)
2109 int i;
2110 const char *final_commit_name = NULL;
2111 struct rev_info *revs = sb->revs;
2114 * There must be one and only one negative commit, and it must be
2115 * the boundary.
2117 for (i = 0; i < revs->pending.nr; i++) {
2118 struct object *obj = revs->pending.objects[i].item;
2119 if (!(obj->flags & UNINTERESTING))
2120 continue;
2121 while (obj->type == OBJ_TAG)
2122 obj = deref_tag(obj, NULL, 0);
2123 if (obj->type != OBJ_COMMIT)
2124 die("Non commit %s?", revs->pending.objects[i].name);
2125 if (sb->final)
2126 die("More than one commit to dig down to %s and %s?",
2127 revs->pending.objects[i].name,
2128 final_commit_name);
2129 sb->final = (struct commit *) obj;
2130 final_commit_name = revs->pending.objects[i].name;
2132 if (!final_commit_name)
2133 die("No commit to dig down to?");
2134 return final_commit_name;
2137 static int blame_copy_callback(const struct option *option, const char *arg, int unset)
2139 int *opt = option->value;
2142 * -C enables copy from removed files;
2143 * -C -C enables copy from existing files, but only
2144 * when blaming a new file;
2145 * -C -C -C enables copy from existing files for
2146 * everybody
2148 if (*opt & PICKAXE_BLAME_COPY_HARDER)
2149 *opt |= PICKAXE_BLAME_COPY_HARDEST;
2150 if (*opt & PICKAXE_BLAME_COPY)
2151 *opt |= PICKAXE_BLAME_COPY_HARDER;
2152 *opt |= PICKAXE_BLAME_COPY | PICKAXE_BLAME_MOVE;
2154 if (arg)
2155 blame_copy_score = parse_score(arg);
2156 return 0;
2159 static int blame_move_callback(const struct option *option, const char *arg, int unset)
2161 int *opt = option->value;
2163 *opt |= PICKAXE_BLAME_MOVE;
2165 if (arg)
2166 blame_move_score = parse_score(arg);
2167 return 0;
2170 static int blame_bottomtop_callback(const struct option *option, const char *arg, int unset)
2172 const char **bottomtop = option->value;
2173 if (!arg)
2174 return -1;
2175 if (*bottomtop)
2176 die("More than one '-L n,m' option given");
2177 *bottomtop = arg;
2178 return 0;
2181 int cmd_blame(int argc, const char **argv, const char *prefix)
2183 struct rev_info revs;
2184 const char *path;
2185 struct scoreboard sb;
2186 struct origin *o;
2187 struct blame_entry *ent;
2188 long dashdash_pos, bottom, top, lno;
2189 const char *final_commit_name = NULL;
2190 enum object_type type;
2192 static const char *bottomtop = NULL;
2193 static int output_option = 0, opt = 0;
2194 static int show_stats = 0;
2195 static const char *revs_file = NULL;
2196 static const char *contents_from = NULL;
2197 static const struct option options[] = {
2198 OPT_BOOLEAN(0, "incremental", &incremental, "Show blame entries as we find them, incrementally"),
2199 OPT_BOOLEAN('b', NULL, &blank_boundary, "Show blank SHA-1 for boundary commits (Default: off)"),
2200 OPT_BOOLEAN(0, "root", &show_root, "Do not treat root commits as boundaries (Default: off)"),
2201 OPT_BOOLEAN(0, "show-stats", &show_stats, "Show work cost statistics"),
2202 OPT_BIT(0, "score-debug", &output_option, "Show output score for blame entries", OUTPUT_SHOW_SCORE),
2203 OPT_BIT('f', "show-name", &output_option, "Show original filename (Default: auto)", OUTPUT_SHOW_NAME),
2204 OPT_BIT('n', "show-number", &output_option, "Show original linenumber (Default: off)", OUTPUT_SHOW_NUMBER),
2205 OPT_BIT('p', "porcelain", &output_option, "Show in a format designed for machine consumption", OUTPUT_PORCELAIN),
2206 OPT_BIT('c', NULL, &output_option, "Use the same output mode as git-annotate (Default: off)", OUTPUT_ANNOTATE_COMPAT),
2207 OPT_BIT('t', NULL, &output_option, "Show raw timestamp (Default: off)", OUTPUT_RAW_TIMESTAMP),
2208 OPT_BIT('l', NULL, &output_option, "Show long commit SHA1 (Default: off)", OUTPUT_LONG_OBJECT_NAME),
2209 OPT_BIT('s', NULL, &output_option, "Suppress author name and timestamp (Default: off)", OUTPUT_NO_AUTHOR),
2210 OPT_BIT('w', NULL, &xdl_opts, "Ignore whitespace differences", XDF_IGNORE_WHITESPACE),
2211 OPT_STRING('S', NULL, &revs_file, "file", "Use revisions from <file> instead of calling git-rev-list"),
2212 OPT_STRING(0, "contents", &contents_from, "file", "Use <file>'s contents as the final image"),
2213 { OPTION_CALLBACK, 'C', NULL, &opt, "score", "Find line copies within and across files", PARSE_OPT_OPTARG, blame_copy_callback },
2214 { OPTION_CALLBACK, 'M', NULL, &opt, "score", "Find line movements within and across files", PARSE_OPT_OPTARG, blame_move_callback },
2215 OPT_CALLBACK('L', NULL, &bottomtop, "n,m", "Process only line range n,m, counting from 1", blame_bottomtop_callback),
2216 OPT_END()
2219 struct parse_opt_ctx_t ctx;
2220 int cmd_is_annotate = !strcmp(argv[0], "annotate");
2222 git_config(git_blame_config, NULL);
2223 init_revisions(&revs, NULL);
2224 revs.date_mode = blame_date_mode;
2225 DIFF_OPT_SET(&revs.diffopt, ALLOW_TEXTCONV);
2227 save_commit_buffer = 0;
2228 dashdash_pos = 0;
2230 parse_options_start(&ctx, argc, argv, prefix, PARSE_OPT_KEEP_DASHDASH |
2231 PARSE_OPT_KEEP_ARGV0);
2232 for (;;) {
2233 switch (parse_options_step(&ctx, options, blame_opt_usage)) {
2234 case PARSE_OPT_HELP:
2235 exit(129);
2236 case PARSE_OPT_DONE:
2237 if (ctx.argv[0])
2238 dashdash_pos = ctx.cpidx;
2239 goto parse_done;
2242 if (!strcmp(ctx.argv[0], "--reverse")) {
2243 ctx.argv[0] = "--children";
2244 reverse = 1;
2246 parse_revision_opt(&revs, &ctx, options, blame_opt_usage);
2248 parse_done:
2249 argc = parse_options_end(&ctx);
2251 if (revs_file && read_ancestry(revs_file))
2252 die_errno("reading graft file '%s' failed", revs_file);
2254 if (cmd_is_annotate) {
2255 output_option |= OUTPUT_ANNOTATE_COMPAT;
2256 blame_date_mode = DATE_ISO8601;
2257 } else {
2258 blame_date_mode = revs.date_mode;
2261 /* The maximum width used to show the dates */
2262 switch (blame_date_mode) {
2263 case DATE_RFC2822:
2264 blame_date_width = sizeof("Thu, 19 Oct 2006 16:00:04 -0700");
2265 break;
2266 case DATE_ISO8601:
2267 blame_date_width = sizeof("2006-10-19 16:00:04 -0700");
2268 break;
2269 case DATE_RAW:
2270 blame_date_width = sizeof("1161298804 -0700");
2271 break;
2272 case DATE_SHORT:
2273 blame_date_width = sizeof("2006-10-19");
2274 break;
2275 case DATE_RELATIVE:
2276 /* "normal" is used as the fallback for "relative" */
2277 case DATE_LOCAL:
2278 case DATE_NORMAL:
2279 blame_date_width = sizeof("Thu Oct 19 16:00:04 2006 -0700");
2280 break;
2282 blame_date_width -= 1; /* strip the null */
2284 if (DIFF_OPT_TST(&revs.diffopt, FIND_COPIES_HARDER))
2285 opt |= (PICKAXE_BLAME_COPY | PICKAXE_BLAME_MOVE |
2286 PICKAXE_BLAME_COPY_HARDER);
2288 if (!blame_move_score)
2289 blame_move_score = BLAME_DEFAULT_MOVE_SCORE;
2290 if (!blame_copy_score)
2291 blame_copy_score = BLAME_DEFAULT_COPY_SCORE;
2294 * We have collected options unknown to us in argv[1..unk]
2295 * which are to be passed to revision machinery if we are
2296 * going to do the "bottom" processing.
2298 * The remaining are:
2300 * (1) if dashdash_pos != 0, it is either
2301 * "blame [revisions] -- <path>" or
2302 * "blame -- <path> <rev>"
2304 * (2) otherwise, it is one of the two:
2305 * "blame [revisions] <path>"
2306 * "blame <path> <rev>"
2308 * Note that we must strip out <path> from the arguments: we do not
2309 * want the path pruning but we may want "bottom" processing.
2311 if (dashdash_pos) {
2312 switch (argc - dashdash_pos - 1) {
2313 case 2: /* (1b) */
2314 if (argc != 4)
2315 usage_with_options(blame_opt_usage, options);
2316 /* reorder for the new way: <rev> -- <path> */
2317 argv[1] = argv[3];
2318 argv[3] = argv[2];
2319 argv[2] = "--";
2320 /* FALLTHROUGH */
2321 case 1: /* (1a) */
2322 path = add_prefix(prefix, argv[--argc]);
2323 argv[argc] = NULL;
2324 break;
2325 default:
2326 usage_with_options(blame_opt_usage, options);
2328 } else {
2329 if (argc < 2)
2330 usage_with_options(blame_opt_usage, options);
2331 path = add_prefix(prefix, argv[argc - 1]);
2332 if (argc == 3 && !has_string_in_work_tree(path)) { /* (2b) */
2333 path = add_prefix(prefix, argv[1]);
2334 argv[1] = argv[2];
2336 argv[argc - 1] = "--";
2338 setup_work_tree();
2339 if (!has_string_in_work_tree(path))
2340 die_errno("cannot stat path '%s'", path);
2343 revs.disable_stdin = 1;
2344 setup_revisions(argc, argv, &revs, NULL);
2345 memset(&sb, 0, sizeof(sb));
2347 sb.revs = &revs;
2348 if (!reverse)
2349 final_commit_name = prepare_final(&sb);
2350 else if (contents_from)
2351 die("--contents and --children do not blend well.");
2352 else
2353 final_commit_name = prepare_initial(&sb);
2355 if (!sb.final) {
2357 * "--not A B -- path" without anything positive;
2358 * do not default to HEAD, but use the working tree
2359 * or "--contents".
2361 setup_work_tree();
2362 sb.final = fake_working_tree_commit(&sb.revs->diffopt,
2363 path, contents_from);
2364 add_pending_object(&revs, &(sb.final->object), ":");
2366 else if (contents_from)
2367 die("Cannot use --contents with final commit object name");
2370 * If we have bottom, this will mark the ancestors of the
2371 * bottom commits we would reach while traversing as
2372 * uninteresting.
2374 if (prepare_revision_walk(&revs))
2375 die("revision walk setup failed");
2377 if (is_null_sha1(sb.final->object.sha1)) {
2378 char *buf;
2379 o = sb.final->util;
2380 buf = xmalloc(o->file.size + 1);
2381 memcpy(buf, o->file.ptr, o->file.size + 1);
2382 sb.final_buf = buf;
2383 sb.final_buf_size = o->file.size;
2385 else {
2386 o = get_origin(&sb, sb.final, path);
2387 if (fill_blob_sha1(o))
2388 die("no such path %s in %s", path, final_commit_name);
2390 if (DIFF_OPT_TST(&sb.revs->diffopt, ALLOW_TEXTCONV) &&
2391 textconv_object(path, o->blob_sha1, (char **) &sb.final_buf,
2392 &sb.final_buf_size))
2394 else
2395 sb.final_buf = read_sha1_file(o->blob_sha1, &type,
2396 &sb.final_buf_size);
2398 if (!sb.final_buf)
2399 die("Cannot read blob %s for path %s",
2400 sha1_to_hex(o->blob_sha1),
2401 path);
2403 num_read_blob++;
2404 lno = prepare_lines(&sb);
2406 bottom = top = 0;
2407 if (bottomtop)
2408 prepare_blame_range(&sb, bottomtop, lno, &bottom, &top);
2409 if (bottom && top && top < bottom) {
2410 long tmp;
2411 tmp = top; top = bottom; bottom = tmp;
2413 if (bottom < 1)
2414 bottom = 1;
2415 if (top < 1)
2416 top = lno;
2417 bottom--;
2418 if (lno < top || lno < bottom)
2419 die("file %s has only %lu lines", path, lno);
2421 ent = xcalloc(1, sizeof(*ent));
2422 ent->lno = bottom;
2423 ent->num_lines = top - bottom;
2424 ent->suspect = o;
2425 ent->s_lno = bottom;
2427 sb.ent = ent;
2428 sb.path = path;
2430 read_mailmap(&mailmap, NULL);
2432 if (!incremental)
2433 setup_pager();
2435 assign_blame(&sb, opt);
2437 if (incremental)
2438 return 0;
2440 coalesce(&sb);
2442 if (!(output_option & OUTPUT_PORCELAIN))
2443 find_alignment(&sb, &output_option);
2445 output(&sb, output_option);
2446 free((void *)sb.final_buf);
2447 for (ent = sb.ent; ent; ) {
2448 struct blame_entry *e = ent->next;
2449 free(ent);
2450 ent = e;
2453 if (show_stats) {
2454 printf("num read blob: %d\n", num_read_blob);
2455 printf("num get patch: %d\n", num_get_patch);
2456 printf("num commits: %d\n", num_commits);
2458 return 0;