Code

blame: show "previous" information in --porcelain/--incremental format
[git.git] / builtin-blame.c
1 /*
2  * Pickaxe
3  *
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"
23 static char blame_usage[] = "git blame [options] [rev-opts] [rev] [--] file";
25 static const char *blame_opt_usage[] = {
26         blame_usage,
27         "",
28         "[rev-opts] are documented in git-rev-list(1)",
29         NULL
30 };
32 static int longest_file;
33 static int longest_author;
34 static int max_orig_digits;
35 static int max_digits;
36 static int max_score_digits;
37 static int show_root;
38 static int reverse;
39 static int blank_boundary;
40 static int incremental;
41 static int xdl_opts = XDF_NEED_MINIMAL;
42 static struct string_list mailmap;
44 #ifndef DEBUG
45 #define DEBUG 0
46 #endif
48 /* stats */
49 static int num_read_blob;
50 static int num_get_patch;
51 static int num_commits;
53 #define PICKAXE_BLAME_MOVE              01
54 #define PICKAXE_BLAME_COPY              02
55 #define PICKAXE_BLAME_COPY_HARDER       04
56 #define PICKAXE_BLAME_COPY_HARDEST      010
58 /*
59  * blame for a blame_entry with score lower than these thresholds
60  * is not passed to the parent using move/copy logic.
61  */
62 static unsigned blame_move_score;
63 static unsigned blame_copy_score;
64 #define BLAME_DEFAULT_MOVE_SCORE        20
65 #define BLAME_DEFAULT_COPY_SCORE        40
67 /* bits #0..7 in revision.h, #8..11 used for merge_bases() in commit.c */
68 #define METAINFO_SHOWN          (1u<<12)
69 #define MORE_THAN_ONE_PATH      (1u<<13)
71 /*
72  * One blob in a commit that is being suspected
73  */
74 struct origin {
75         int refcnt;
76         struct origin *previous;
77         struct commit *commit;
78         mmfile_t file;
79         unsigned char blob_sha1[20];
80         char path[FLEX_ARRAY];
81 };
83 /*
84  * Given an origin, prepare mmfile_t structure to be used by the
85  * diff machinery
86  */
87 static void fill_origin_blob(struct origin *o, mmfile_t *file)
88 {
89         if (!o->file.ptr) {
90                 enum object_type type;
91                 num_read_blob++;
92                 file->ptr = read_sha1_file(o->blob_sha1, &type,
93                                            (unsigned long *)(&(file->size)));
94                 if (!file->ptr)
95                         die("Cannot read blob %s for path %s",
96                             sha1_to_hex(o->blob_sha1),
97                             o->path);
98                 o->file = *file;
99         }
100         else
101                 *file = o->file;
104 /*
105  * Origin is refcounted and usually we keep the blob contents to be
106  * reused.
107  */
108 static inline struct origin *origin_incref(struct origin *o)
110         if (o)
111                 o->refcnt++;
112         return o;
115 static void origin_decref(struct origin *o)
117         if (o && --o->refcnt <= 0) {
118                 if (o->previous)
119                         origin_decref(o->previous);
120                 free(o->file.ptr);
121                 free(o);
122         }
125 static void drop_origin_blob(struct origin *o)
127         if (o->file.ptr) {
128                 free(o->file.ptr);
129                 o->file.ptr = NULL;
130         }
133 /*
134  * Each group of lines is described by a blame_entry; it can be split
135  * as we pass blame to the parents.  They form a linked list in the
136  * scoreboard structure, sorted by the target line number.
137  */
138 struct blame_entry {
139         struct blame_entry *prev;
140         struct blame_entry *next;
142         /* the first line of this group in the final image;
143          * internally all line numbers are 0 based.
144          */
145         int lno;
147         /* how many lines this group has */
148         int num_lines;
150         /* the commit that introduced this group into the final image */
151         struct origin *suspect;
153         /* true if the suspect is truly guilty; false while we have not
154          * checked if the group came from one of its parents.
155          */
156         char guilty;
158         /* true if the entry has been scanned for copies in the current parent
159          */
160         char scanned;
162         /* the line number of the first line of this group in the
163          * suspect's file; internally all line numbers are 0 based.
164          */
165         int s_lno;
167         /* how significant this entry is -- cached to avoid
168          * scanning the lines over and over.
169          */
170         unsigned score;
171 };
173 /*
174  * The current state of the blame assignment.
175  */
176 struct scoreboard {
177         /* the final commit (i.e. where we started digging from) */
178         struct commit *final;
179         struct rev_info *revs;
180         const char *path;
182         /*
183          * The contents in the final image.
184          * Used by many functions to obtain contents of the nth line,
185          * indexed with scoreboard.lineno[blame_entry.lno].
186          */
187         const char *final_buf;
188         unsigned long final_buf_size;
190         /* linked list of blames */
191         struct blame_entry *ent;
193         /* look-up a line in the final buffer */
194         int num_lines;
195         int *lineno;
196 };
198 static inline int same_suspect(struct origin *a, struct origin *b)
200         if (a == b)
201                 return 1;
202         if (a->commit != b->commit)
203                 return 0;
204         return !strcmp(a->path, b->path);
207 static void sanity_check_refcnt(struct scoreboard *);
209 /*
210  * If two blame entries that are next to each other came from
211  * contiguous lines in the same origin (i.e. <commit, path> pair),
212  * merge them together.
213  */
214 static void coalesce(struct scoreboard *sb)
216         struct blame_entry *ent, *next;
218         for (ent = sb->ent; ent && (next = ent->next); ent = next) {
219                 if (same_suspect(ent->suspect, next->suspect) &&
220                     ent->guilty == next->guilty &&
221                     ent->s_lno + ent->num_lines == next->s_lno) {
222                         ent->num_lines += next->num_lines;
223                         ent->next = next->next;
224                         if (ent->next)
225                                 ent->next->prev = ent;
226                         origin_decref(next->suspect);
227                         free(next);
228                         ent->score = 0;
229                         next = ent; /* again */
230                 }
231         }
233         if (DEBUG) /* sanity */
234                 sanity_check_refcnt(sb);
237 /*
238  * Given a commit and a path in it, create a new origin structure.
239  * The callers that add blame to the scoreboard should use
240  * get_origin() to obtain shared, refcounted copy instead of calling
241  * this function directly.
242  */
243 static struct origin *make_origin(struct commit *commit, const char *path)
245         struct origin *o;
246         o = xcalloc(1, sizeof(*o) + strlen(path) + 1);
247         o->commit = commit;
248         o->refcnt = 1;
249         strcpy(o->path, path);
250         return o;
253 /*
254  * Locate an existing origin or create a new one.
255  */
256 static struct origin *get_origin(struct scoreboard *sb,
257                                  struct commit *commit,
258                                  const char *path)
260         struct blame_entry *e;
262         for (e = sb->ent; e; e = e->next) {
263                 if (e->suspect->commit == commit &&
264                     !strcmp(e->suspect->path, path))
265                         return origin_incref(e->suspect);
266         }
267         return make_origin(commit, path);
270 /*
271  * Fill the blob_sha1 field of an origin if it hasn't, so that later
272  * call to fill_origin_blob() can use it to locate the data.  blob_sha1
273  * for an origin is also used to pass the blame for the entire file to
274  * the parent to detect the case where a child's blob is identical to
275  * that of its parent's.
276  */
277 static int fill_blob_sha1(struct origin *origin)
279         unsigned mode;
281         if (!is_null_sha1(origin->blob_sha1))
282                 return 0;
283         if (get_tree_entry(origin->commit->object.sha1,
284                            origin->path,
285                            origin->blob_sha1, &mode))
286                 goto error_out;
287         if (sha1_object_info(origin->blob_sha1, NULL) != OBJ_BLOB)
288                 goto error_out;
289         return 0;
290  error_out:
291         hashclr(origin->blob_sha1);
292         return -1;
295 /*
296  * We have an origin -- check if the same path exists in the
297  * parent and return an origin structure to represent it.
298  */
299 static struct origin *find_origin(struct scoreboard *sb,
300                                   struct commit *parent,
301                                   struct origin *origin)
303         struct origin *porigin = NULL;
304         struct diff_options diff_opts;
305         const char *paths[2];
307         if (parent->util) {
308                 /*
309                  * Each commit object can cache one origin in that
310                  * commit.  This is a freestanding copy of origin and
311                  * not refcounted.
312                  */
313                 struct origin *cached = parent->util;
314                 if (!strcmp(cached->path, origin->path)) {
315                         /*
316                          * The same path between origin and its parent
317                          * without renaming -- the most common case.
318                          */
319                         porigin = get_origin(sb, parent, cached->path);
321                         /*
322                          * If the origin was newly created (i.e. get_origin
323                          * would call make_origin if none is found in the
324                          * scoreboard), it does not know the blob_sha1,
325                          * so copy it.  Otherwise porigin was in the
326                          * scoreboard and already knows blob_sha1.
327                          */
328                         if (porigin->refcnt == 1)
329                                 hashcpy(porigin->blob_sha1, cached->blob_sha1);
330                         return porigin;
331                 }
332                 /* otherwise it was not very useful; free it */
333                 free(parent->util);
334                 parent->util = NULL;
335         }
337         /* See if the origin->path is different between parent
338          * and origin first.  Most of the time they are the
339          * same and diff-tree is fairly efficient about this.
340          */
341         diff_setup(&diff_opts);
342         DIFF_OPT_SET(&diff_opts, RECURSIVE);
343         diff_opts.detect_rename = 0;
344         diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;
345         paths[0] = origin->path;
346         paths[1] = NULL;
348         diff_tree_setup_paths(paths, &diff_opts);
349         if (diff_setup_done(&diff_opts) < 0)
350                 die("diff-setup");
352         if (is_null_sha1(origin->commit->object.sha1))
353                 do_diff_cache(parent->tree->object.sha1, &diff_opts);
354         else
355                 diff_tree_sha1(parent->tree->object.sha1,
356                                origin->commit->tree->object.sha1,
357                                "", &diff_opts);
358         diffcore_std(&diff_opts);
360         /* It is either one entry that says "modified", or "created",
361          * or nothing.
362          */
363         if (!diff_queued_diff.nr) {
364                 /* The path is the same as parent */
365                 porigin = get_origin(sb, parent, origin->path);
366                 hashcpy(porigin->blob_sha1, origin->blob_sha1);
367         }
368         else if (diff_queued_diff.nr != 1)
369                 die("internal error in blame::find_origin");
370         else {
371                 struct diff_filepair *p = diff_queued_diff.queue[0];
372                 switch (p->status) {
373                 default:
374                         die("internal error in blame::find_origin (%c)",
375                             p->status);
376                 case 'M':
377                         porigin = get_origin(sb, parent, origin->path);
378                         hashcpy(porigin->blob_sha1, p->one->sha1);
379                         break;
380                 case 'A':
381                 case 'T':
382                         /* Did not exist in parent, or type changed */
383                         break;
384                 }
385         }
386         diff_flush(&diff_opts);
387         diff_tree_release_paths(&diff_opts);
388         if (porigin) {
389                 /*
390                  * Create a freestanding copy that is not part of
391                  * the refcounted origin found in the scoreboard, and
392                  * cache it in the commit.
393                  */
394                 struct origin *cached;
396                 cached = make_origin(porigin->commit, porigin->path);
397                 hashcpy(cached->blob_sha1, porigin->blob_sha1);
398                 parent->util = cached;
399         }
400         return porigin;
403 /*
404  * We have an origin -- find the path that corresponds to it in its
405  * parent and return an origin structure to represent it.
406  */
407 static struct origin *find_rename(struct scoreboard *sb,
408                                   struct commit *parent,
409                                   struct origin *origin)
411         struct origin *porigin = NULL;
412         struct diff_options diff_opts;
413         int i;
414         const char *paths[2];
416         diff_setup(&diff_opts);
417         DIFF_OPT_SET(&diff_opts, RECURSIVE);
418         diff_opts.detect_rename = DIFF_DETECT_RENAME;
419         diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;
420         diff_opts.single_follow = origin->path;
421         paths[0] = NULL;
422         diff_tree_setup_paths(paths, &diff_opts);
423         if (diff_setup_done(&diff_opts) < 0)
424                 die("diff-setup");
426         if (is_null_sha1(origin->commit->object.sha1))
427                 do_diff_cache(parent->tree->object.sha1, &diff_opts);
428         else
429                 diff_tree_sha1(parent->tree->object.sha1,
430                                origin->commit->tree->object.sha1,
431                                "", &diff_opts);
432         diffcore_std(&diff_opts);
434         for (i = 0; i < diff_queued_diff.nr; i++) {
435                 struct diff_filepair *p = diff_queued_diff.queue[i];
436                 if ((p->status == 'R' || p->status == 'C') &&
437                     !strcmp(p->two->path, origin->path)) {
438                         porigin = get_origin(sb, parent, p->one->path);
439                         hashcpy(porigin->blob_sha1, p->one->sha1);
440                         break;
441                 }
442         }
443         diff_flush(&diff_opts);
444         diff_tree_release_paths(&diff_opts);
445         return porigin;
448 /*
449  * Parsing of patch chunks...
450  */
451 struct chunk {
452         /* line number in postimage; up to but not including this
453          * line is the same as preimage
454          */
455         int same;
457         /* preimage line number after this chunk */
458         int p_next;
460         /* postimage line number after this chunk */
461         int t_next;
462 };
464 struct patch {
465         struct chunk *chunks;
466         int num;
467 };
469 struct blame_diff_state {
470         struct patch *ret;
471         unsigned hunk_post_context;
472         unsigned hunk_in_pre_context : 1;
473 };
475 static void process_u_diff(void *state_, char *line, unsigned long len)
477         struct blame_diff_state *state = state_;
478         struct chunk *chunk;
479         int off1, off2, len1, len2, num;
481         num = state->ret->num;
482         if (len < 4 || line[0] != '@' || line[1] != '@') {
483                 if (state->hunk_in_pre_context && line[0] == ' ')
484                         state->ret->chunks[num - 1].same++;
485                 else {
486                         state->hunk_in_pre_context = 0;
487                         if (line[0] == ' ')
488                                 state->hunk_post_context++;
489                         else
490                                 state->hunk_post_context = 0;
491                 }
492                 return;
493         }
495         if (num && state->hunk_post_context) {
496                 chunk = &state->ret->chunks[num - 1];
497                 chunk->p_next -= state->hunk_post_context;
498                 chunk->t_next -= state->hunk_post_context;
499         }
500         state->ret->num = ++num;
501         state->ret->chunks = xrealloc(state->ret->chunks,
502                                       sizeof(struct chunk) * num);
503         chunk = &state->ret->chunks[num - 1];
504         if (parse_hunk_header(line, len, &off1, &len1, &off2, &len2)) {
505                 state->ret->num--;
506                 return;
507         }
509         /* Line numbers in patch output are one based. */
510         off1--;
511         off2--;
513         chunk->same = len2 ? off2 : (off2 + 1);
515         chunk->p_next = off1 + (len1 ? len1 : 1);
516         chunk->t_next = chunk->same + len2;
517         state->hunk_in_pre_context = 1;
518         state->hunk_post_context = 0;
521 static struct patch *compare_buffer(mmfile_t *file_p, mmfile_t *file_o,
522                                     int context)
524         struct blame_diff_state state;
525         xpparam_t xpp;
526         xdemitconf_t xecfg;
527         xdemitcb_t ecb;
529         xpp.flags = xdl_opts;
530         memset(&xecfg, 0, sizeof(xecfg));
531         xecfg.ctxlen = context;
532         memset(&state, 0, sizeof(state));
533         state.ret = xmalloc(sizeof(struct patch));
534         state.ret->chunks = NULL;
535         state.ret->num = 0;
537         xdi_diff_outf(file_p, file_o, process_u_diff, &state, &xpp, &xecfg, &ecb);
539         if (state.ret->num) {
540                 struct chunk *chunk;
541                 chunk = &state.ret->chunks[state.ret->num - 1];
542                 chunk->p_next -= state.hunk_post_context;
543                 chunk->t_next -= state.hunk_post_context;
544         }
545         return state.ret;
548 /*
549  * Run diff between two origins and grab the patch output, so that
550  * we can pass blame for lines origin is currently suspected for
551  * to its parent.
552  */
553 static struct patch *get_patch(struct origin *parent, struct origin *origin)
555         mmfile_t file_p, file_o;
556         struct patch *patch;
558         fill_origin_blob(parent, &file_p);
559         fill_origin_blob(origin, &file_o);
560         if (!file_p.ptr || !file_o.ptr)
561                 return NULL;
562         patch = compare_buffer(&file_p, &file_o, 0);
563         num_get_patch++;
564         return patch;
567 static void free_patch(struct patch *p)
569         free(p->chunks);
570         free(p);
573 /*
574  * Link in a new blame entry to the scoreboard.  Entries that cover the
575  * same line range have been removed from the scoreboard previously.
576  */
577 static void add_blame_entry(struct scoreboard *sb, struct blame_entry *e)
579         struct blame_entry *ent, *prev = NULL;
581         origin_incref(e->suspect);
583         for (ent = sb->ent; ent && ent->lno < e->lno; ent = ent->next)
584                 prev = ent;
586         /* prev, if not NULL, is the last one that is below e */
587         e->prev = prev;
588         if (prev) {
589                 e->next = prev->next;
590                 prev->next = e;
591         }
592         else {
593                 e->next = sb->ent;
594                 sb->ent = e;
595         }
596         if (e->next)
597                 e->next->prev = e;
600 /*
601  * src typically is on-stack; we want to copy the information in it to
602  * a malloced blame_entry that is already on the linked list of the
603  * scoreboard.  The origin of dst loses a refcnt while the origin of src
604  * gains one.
605  */
606 static void dup_entry(struct blame_entry *dst, struct blame_entry *src)
608         struct blame_entry *p, *n;
610         p = dst->prev;
611         n = dst->next;
612         origin_incref(src->suspect);
613         origin_decref(dst->suspect);
614         memcpy(dst, src, sizeof(*src));
615         dst->prev = p;
616         dst->next = n;
617         dst->score = 0;
620 static const char *nth_line(struct scoreboard *sb, int lno)
622         return sb->final_buf + sb->lineno[lno];
625 /*
626  * It is known that lines between tlno to same came from parent, and e
627  * has an overlap with that range.  it also is known that parent's
628  * line plno corresponds to e's line tlno.
629  *
630  *                <---- e ----->
631  *                   <------>
632  *                   <------------>
633  *             <------------>
634  *             <------------------>
635  *
636  * Split e into potentially three parts; before this chunk, the chunk
637  * to be blamed for the parent, and after that portion.
638  */
639 static void split_overlap(struct blame_entry *split,
640                           struct blame_entry *e,
641                           int tlno, int plno, int same,
642                           struct origin *parent)
644         int chunk_end_lno;
645         memset(split, 0, sizeof(struct blame_entry [3]));
647         if (e->s_lno < tlno) {
648                 /* there is a pre-chunk part not blamed on parent */
649                 split[0].suspect = origin_incref(e->suspect);
650                 split[0].lno = e->lno;
651                 split[0].s_lno = e->s_lno;
652                 split[0].num_lines = tlno - e->s_lno;
653                 split[1].lno = e->lno + tlno - e->s_lno;
654                 split[1].s_lno = plno;
655         }
656         else {
657                 split[1].lno = e->lno;
658                 split[1].s_lno = plno + (e->s_lno - tlno);
659         }
661         if (same < e->s_lno + e->num_lines) {
662                 /* there is a post-chunk part not blamed on parent */
663                 split[2].suspect = origin_incref(e->suspect);
664                 split[2].lno = e->lno + (same - e->s_lno);
665                 split[2].s_lno = e->s_lno + (same - e->s_lno);
666                 split[2].num_lines = e->s_lno + e->num_lines - same;
667                 chunk_end_lno = split[2].lno;
668         }
669         else
670                 chunk_end_lno = e->lno + e->num_lines;
671         split[1].num_lines = chunk_end_lno - split[1].lno;
673         /*
674          * if it turns out there is nothing to blame the parent for,
675          * forget about the splitting.  !split[1].suspect signals this.
676          */
677         if (split[1].num_lines < 1)
678                 return;
679         split[1].suspect = origin_incref(parent);
682 /*
683  * split_overlap() divided an existing blame e into up to three parts
684  * in split.  Adjust the linked list of blames in the scoreboard to
685  * reflect the split.
686  */
687 static void split_blame(struct scoreboard *sb,
688                         struct blame_entry *split,
689                         struct blame_entry *e)
691         struct blame_entry *new_entry;
693         if (split[0].suspect && split[2].suspect) {
694                 /* The first part (reuse storage for the existing entry e) */
695                 dup_entry(e, &split[0]);
697                 /* The last part -- me */
698                 new_entry = xmalloc(sizeof(*new_entry));
699                 memcpy(new_entry, &(split[2]), sizeof(struct blame_entry));
700                 add_blame_entry(sb, new_entry);
702                 /* ... and the middle part -- parent */
703                 new_entry = xmalloc(sizeof(*new_entry));
704                 memcpy(new_entry, &(split[1]), sizeof(struct blame_entry));
705                 add_blame_entry(sb, new_entry);
706         }
707         else if (!split[0].suspect && !split[2].suspect)
708                 /*
709                  * The parent covers the entire area; reuse storage for
710                  * e and replace it with the parent.
711                  */
712                 dup_entry(e, &split[1]);
713         else if (split[0].suspect) {
714                 /* me and then parent */
715                 dup_entry(e, &split[0]);
717                 new_entry = xmalloc(sizeof(*new_entry));
718                 memcpy(new_entry, &(split[1]), sizeof(struct blame_entry));
719                 add_blame_entry(sb, new_entry);
720         }
721         else {
722                 /* parent and then me */
723                 dup_entry(e, &split[1]);
725                 new_entry = xmalloc(sizeof(*new_entry));
726                 memcpy(new_entry, &(split[2]), sizeof(struct blame_entry));
727                 add_blame_entry(sb, new_entry);
728         }
730         if (DEBUG) { /* sanity */
731                 struct blame_entry *ent;
732                 int lno = sb->ent->lno, corrupt = 0;
734                 for (ent = sb->ent; ent; ent = ent->next) {
735                         if (lno != ent->lno)
736                                 corrupt = 1;
737                         if (ent->s_lno < 0)
738                                 corrupt = 1;
739                         lno += ent->num_lines;
740                 }
741                 if (corrupt) {
742                         lno = sb->ent->lno;
743                         for (ent = sb->ent; ent; ent = ent->next) {
744                                 printf("L %8d l %8d n %8d\n",
745                                        lno, ent->lno, ent->num_lines);
746                                 lno = ent->lno + ent->num_lines;
747                         }
748                         die("oops");
749                 }
750         }
753 /*
754  * After splitting the blame, the origins used by the
755  * on-stack blame_entry should lose one refcnt each.
756  */
757 static void decref_split(struct blame_entry *split)
759         int i;
761         for (i = 0; i < 3; i++)
762                 origin_decref(split[i].suspect);
765 /*
766  * Helper for blame_chunk().  blame_entry e is known to overlap with
767  * the patch hunk; split it and pass blame to the parent.
768  */
769 static void blame_overlap(struct scoreboard *sb, struct blame_entry *e,
770                           int tlno, int plno, int same,
771                           struct origin *parent)
773         struct blame_entry split[3];
775         split_overlap(split, e, tlno, plno, same, parent);
776         if (split[1].suspect)
777                 split_blame(sb, split, e);
778         decref_split(split);
781 /*
782  * Find the line number of the last line the target is suspected for.
783  */
784 static int find_last_in_target(struct scoreboard *sb, struct origin *target)
786         struct blame_entry *e;
787         int last_in_target = -1;
789         for (e = sb->ent; e; e = e->next) {
790                 if (e->guilty || !same_suspect(e->suspect, target))
791                         continue;
792                 if (last_in_target < e->s_lno + e->num_lines)
793                         last_in_target = e->s_lno + e->num_lines;
794         }
795         return last_in_target;
798 /*
799  * Process one hunk from the patch between the current suspect for
800  * blame_entry e and its parent.  Find and split the overlap, and
801  * pass blame to the overlapping part to the parent.
802  */
803 static void blame_chunk(struct scoreboard *sb,
804                         int tlno, int plno, int same,
805                         struct origin *target, struct origin *parent)
807         struct blame_entry *e;
809         for (e = sb->ent; e; e = e->next) {
810                 if (e->guilty || !same_suspect(e->suspect, target))
811                         continue;
812                 if (same <= e->s_lno)
813                         continue;
814                 if (tlno < e->s_lno + e->num_lines)
815                         blame_overlap(sb, e, tlno, plno, same, parent);
816         }
819 /*
820  * We are looking at the origin 'target' and aiming to pass blame
821  * for the lines it is suspected to its parent.  Run diff to find
822  * which lines came from parent and pass blame for them.
823  */
824 static int pass_blame_to_parent(struct scoreboard *sb,
825                                 struct origin *target,
826                                 struct origin *parent)
828         int i, last_in_target, plno, tlno;
829         struct patch *patch;
831         last_in_target = find_last_in_target(sb, target);
832         if (last_in_target < 0)
833                 return 1; /* nothing remains for this target */
835         patch = get_patch(parent, target);
836         plno = tlno = 0;
837         for (i = 0; i < patch->num; i++) {
838                 struct chunk *chunk = &patch->chunks[i];
840                 blame_chunk(sb, tlno, plno, chunk->same, target, parent);
841                 plno = chunk->p_next;
842                 tlno = chunk->t_next;
843         }
844         /* The rest (i.e. anything after tlno) are the same as the parent */
845         blame_chunk(sb, tlno, plno, last_in_target, target, parent);
847         free_patch(patch);
848         return 0;
851 /*
852  * The lines in blame_entry after splitting blames many times can become
853  * very small and trivial, and at some point it becomes pointless to
854  * blame the parents.  E.g. "\t\t}\n\t}\n\n" appears everywhere in any
855  * ordinary C program, and it is not worth to say it was copied from
856  * totally unrelated file in the parent.
857  *
858  * Compute how trivial the lines in the blame_entry are.
859  */
860 static unsigned ent_score(struct scoreboard *sb, struct blame_entry *e)
862         unsigned score;
863         const char *cp, *ep;
865         if (e->score)
866                 return e->score;
868         score = 1;
869         cp = nth_line(sb, e->lno);
870         ep = nth_line(sb, e->lno + e->num_lines);
871         while (cp < ep) {
872                 unsigned ch = *((unsigned char *)cp);
873                 if (isalnum(ch))
874                         score++;
875                 cp++;
876         }
877         e->score = score;
878         return score;
881 /*
882  * best_so_far[] and this[] are both a split of an existing blame_entry
883  * that passes blame to the parent.  Maintain best_so_far the best split
884  * so far, by comparing this and best_so_far and copying this into
885  * bst_so_far as needed.
886  */
887 static void copy_split_if_better(struct scoreboard *sb,
888                                  struct blame_entry *best_so_far,
889                                  struct blame_entry *this)
891         int i;
893         if (!this[1].suspect)
894                 return;
895         if (best_so_far[1].suspect) {
896                 if (ent_score(sb, &this[1]) < ent_score(sb, &best_so_far[1]))
897                         return;
898         }
900         for (i = 0; i < 3; i++)
901                 origin_incref(this[i].suspect);
902         decref_split(best_so_far);
903         memcpy(best_so_far, this, sizeof(struct blame_entry [3]));
906 /*
907  * We are looking at a part of the final image represented by
908  * ent (tlno and same are offset by ent->s_lno).
909  * tlno is where we are looking at in the final image.
910  * up to (but not including) same match preimage.
911  * plno is where we are looking at in the preimage.
912  *
913  * <-------------- final image ---------------------->
914  *       <------ent------>
915  *         ^tlno ^same
916  *    <---------preimage----->
917  *         ^plno
918  *
919  * All line numbers are 0-based.
920  */
921 static void handle_split(struct scoreboard *sb,
922                          struct blame_entry *ent,
923                          int tlno, int plno, int same,
924                          struct origin *parent,
925                          struct blame_entry *split)
927         if (ent->num_lines <= tlno)
928                 return;
929         if (tlno < same) {
930                 struct blame_entry this[3];
931                 tlno += ent->s_lno;
932                 same += ent->s_lno;
933                 split_overlap(this, ent, tlno, plno, same, parent);
934                 copy_split_if_better(sb, split, this);
935                 decref_split(this);
936         }
939 /*
940  * Find the lines from parent that are the same as ent so that
941  * we can pass blames to it.  file_p has the blob contents for
942  * the parent.
943  */
944 static void find_copy_in_blob(struct scoreboard *sb,
945                               struct blame_entry *ent,
946                               struct origin *parent,
947                               struct blame_entry *split,
948                               mmfile_t *file_p)
950         const char *cp;
951         int cnt;
952         mmfile_t file_o;
953         struct patch *patch;
954         int i, plno, tlno;
956         /*
957          * Prepare mmfile that contains only the lines in ent.
958          */
959         cp = nth_line(sb, ent->lno);
960         file_o.ptr = (char*) cp;
961         cnt = ent->num_lines;
963         while (cnt && cp < sb->final_buf + sb->final_buf_size) {
964                 if (*cp++ == '\n')
965                         cnt--;
966         }
967         file_o.size = cp - file_o.ptr;
969         patch = compare_buffer(file_p, &file_o, 1);
971         /*
972          * file_o is a part of final image we are annotating.
973          * file_p partially may match that image.
974          */
975         memset(split, 0, sizeof(struct blame_entry [3]));
976         plno = tlno = 0;
977         for (i = 0; i < patch->num; i++) {
978                 struct chunk *chunk = &patch->chunks[i];
980                 handle_split(sb, ent, tlno, plno, chunk->same, parent, split);
981                 plno = chunk->p_next;
982                 tlno = chunk->t_next;
983         }
984         /* remainder, if any, all match the preimage */
985         handle_split(sb, ent, tlno, plno, ent->num_lines, parent, split);
986         free_patch(patch);
989 /*
990  * See if lines currently target is suspected for can be attributed to
991  * parent.
992  */
993 static int find_move_in_parent(struct scoreboard *sb,
994                                struct origin *target,
995                                struct origin *parent)
997         int last_in_target, made_progress;
998         struct blame_entry *e, split[3];
999         mmfile_t file_p;
1001         last_in_target = find_last_in_target(sb, target);
1002         if (last_in_target < 0)
1003                 return 1; /* nothing remains for this target */
1005         fill_origin_blob(parent, &file_p);
1006         if (!file_p.ptr)
1007                 return 0;
1009         made_progress = 1;
1010         while (made_progress) {
1011                 made_progress = 0;
1012                 for (e = sb->ent; e; e = e->next) {
1013                         if (e->guilty || !same_suspect(e->suspect, target) ||
1014                             ent_score(sb, e) < blame_move_score)
1015                                 continue;
1016                         find_copy_in_blob(sb, e, parent, split, &file_p);
1017                         if (split[1].suspect &&
1018                             blame_move_score < ent_score(sb, &split[1])) {
1019                                 split_blame(sb, split, e);
1020                                 made_progress = 1;
1021                         }
1022                         decref_split(split);
1023                 }
1024         }
1025         return 0;
1028 struct blame_list {
1029         struct blame_entry *ent;
1030         struct blame_entry split[3];
1031 };
1033 /*
1034  * Count the number of entries the target is suspected for,
1035  * and prepare a list of entry and the best split.
1036  */
1037 static struct blame_list *setup_blame_list(struct scoreboard *sb,
1038                                            struct origin *target,
1039                                            int min_score,
1040                                            int *num_ents_p)
1042         struct blame_entry *e;
1043         int num_ents, i;
1044         struct blame_list *blame_list = NULL;
1046         for (e = sb->ent, num_ents = 0; e; e = e->next)
1047                 if (!e->scanned && !e->guilty &&
1048                     same_suspect(e->suspect, target) &&
1049                     min_score < ent_score(sb, e))
1050                         num_ents++;
1051         if (num_ents) {
1052                 blame_list = xcalloc(num_ents, sizeof(struct blame_list));
1053                 for (e = sb->ent, i = 0; e; e = e->next)
1054                         if (!e->scanned && !e->guilty &&
1055                             same_suspect(e->suspect, target) &&
1056                             min_score < ent_score(sb, e))
1057                                 blame_list[i++].ent = e;
1058         }
1059         *num_ents_p = num_ents;
1060         return blame_list;
1063 /*
1064  * Reset the scanned status on all entries.
1065  */
1066 static void reset_scanned_flag(struct scoreboard *sb)
1068         struct blame_entry *e;
1069         for (e = sb->ent; e; e = e->next)
1070                 e->scanned = 0;
1073 /*
1074  * For lines target is suspected for, see if we can find code movement
1075  * across file boundary from the parent commit.  porigin is the path
1076  * in the parent we already tried.
1077  */
1078 static int find_copy_in_parent(struct scoreboard *sb,
1079                                struct origin *target,
1080                                struct commit *parent,
1081                                struct origin *porigin,
1082                                int opt)
1084         struct diff_options diff_opts;
1085         const char *paths[1];
1086         int i, j;
1087         int retval;
1088         struct blame_list *blame_list;
1089         int num_ents;
1091         blame_list = setup_blame_list(sb, target, blame_copy_score, &num_ents);
1092         if (!blame_list)
1093                 return 1; /* nothing remains for this target */
1095         diff_setup(&diff_opts);
1096         DIFF_OPT_SET(&diff_opts, RECURSIVE);
1097         diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;
1099         paths[0] = NULL;
1100         diff_tree_setup_paths(paths, &diff_opts);
1101         if (diff_setup_done(&diff_opts) < 0)
1102                 die("diff-setup");
1104         /* Try "find copies harder" on new path if requested;
1105          * we do not want to use diffcore_rename() actually to
1106          * match things up; find_copies_harder is set only to
1107          * force diff_tree_sha1() to feed all filepairs to diff_queue,
1108          * and this code needs to be after diff_setup_done(), which
1109          * usually makes find-copies-harder imply copy detection.
1110          */
1111         if ((opt & PICKAXE_BLAME_COPY_HARDEST)
1112             || ((opt & PICKAXE_BLAME_COPY_HARDER)
1113                 && (!porigin || strcmp(target->path, porigin->path))))
1114                 DIFF_OPT_SET(&diff_opts, FIND_COPIES_HARDER);
1116         if (is_null_sha1(target->commit->object.sha1))
1117                 do_diff_cache(parent->tree->object.sha1, &diff_opts);
1118         else
1119                 diff_tree_sha1(parent->tree->object.sha1,
1120                                target->commit->tree->object.sha1,
1121                                "", &diff_opts);
1123         if (!DIFF_OPT_TST(&diff_opts, FIND_COPIES_HARDER))
1124                 diffcore_std(&diff_opts);
1126         retval = 0;
1127         while (1) {
1128                 int made_progress = 0;
1130                 for (i = 0; i < diff_queued_diff.nr; i++) {
1131                         struct diff_filepair *p = diff_queued_diff.queue[i];
1132                         struct origin *norigin;
1133                         mmfile_t file_p;
1134                         struct blame_entry this[3];
1136                         if (!DIFF_FILE_VALID(p->one))
1137                                 continue; /* does not exist in parent */
1138                         if (S_ISGITLINK(p->one->mode))
1139                                 continue; /* ignore git links */
1140                         if (porigin && !strcmp(p->one->path, porigin->path))
1141                                 /* find_move already dealt with this path */
1142                                 continue;
1144                         norigin = get_origin(sb, parent, p->one->path);
1145                         hashcpy(norigin->blob_sha1, p->one->sha1);
1146                         fill_origin_blob(norigin, &file_p);
1147                         if (!file_p.ptr)
1148                                 continue;
1150                         for (j = 0; j < num_ents; j++) {
1151                                 find_copy_in_blob(sb, blame_list[j].ent,
1152                                                   norigin, this, &file_p);
1153                                 copy_split_if_better(sb, blame_list[j].split,
1154                                                      this);
1155                                 decref_split(this);
1156                         }
1157                         origin_decref(norigin);
1158                 }
1160                 for (j = 0; j < num_ents; j++) {
1161                         struct blame_entry *split = blame_list[j].split;
1162                         if (split[1].suspect &&
1163                             blame_copy_score < ent_score(sb, &split[1])) {
1164                                 split_blame(sb, split, blame_list[j].ent);
1165                                 made_progress = 1;
1166                         }
1167                         else
1168                                 blame_list[j].ent->scanned = 1;
1169                         decref_split(split);
1170                 }
1171                 free(blame_list);
1173                 if (!made_progress)
1174                         break;
1175                 blame_list = setup_blame_list(sb, target, blame_copy_score, &num_ents);
1176                 if (!blame_list) {
1177                         retval = 1;
1178                         break;
1179                 }
1180         }
1181         reset_scanned_flag(sb);
1182         diff_flush(&diff_opts);
1183         diff_tree_release_paths(&diff_opts);
1184         return retval;
1187 /*
1188  * The blobs of origin and porigin exactly match, so everything
1189  * origin is suspected for can be blamed on the parent.
1190  */
1191 static void pass_whole_blame(struct scoreboard *sb,
1192                              struct origin *origin, struct origin *porigin)
1194         struct blame_entry *e;
1196         if (!porigin->file.ptr && origin->file.ptr) {
1197                 /* Steal its file */
1198                 porigin->file = origin->file;
1199                 origin->file.ptr = NULL;
1200         }
1201         for (e = sb->ent; e; e = e->next) {
1202                 if (!same_suspect(e->suspect, origin))
1203                         continue;
1204                 origin_incref(porigin);
1205                 origin_decref(e->suspect);
1206                 e->suspect = porigin;
1207         }
1210 /*
1211  * We pass blame from the current commit to its parents.  We keep saying
1212  * "parent" (and "porigin"), but what we mean is to find scapegoat to
1213  * exonerate ourselves.
1214  */
1215 static struct commit_list *first_scapegoat(struct rev_info *revs, struct commit *commit)
1217         if (!reverse)
1218                 return commit->parents;
1219         return lookup_decoration(&revs->children, &commit->object);
1222 static int num_scapegoats(struct rev_info *revs, struct commit *commit)
1224         int cnt;
1225         struct commit_list *l = first_scapegoat(revs, commit);
1226         for (cnt = 0; l; l = l->next)
1227                 cnt++;
1228         return cnt;
1231 #define MAXSG 16
1233 static void pass_blame(struct scoreboard *sb, struct origin *origin, int opt)
1235         struct rev_info *revs = sb->revs;
1236         int i, pass, num_sg;
1237         struct commit *commit = origin->commit;
1238         struct commit_list *sg;
1239         struct origin *sg_buf[MAXSG];
1240         struct origin *porigin, **sg_origin = sg_buf;
1242         num_sg = num_scapegoats(revs, commit);
1243         if (!num_sg)
1244                 goto finish;
1245         else if (num_sg < ARRAY_SIZE(sg_buf))
1246                 memset(sg_buf, 0, sizeof(sg_buf));
1247         else
1248                 sg_origin = xcalloc(num_sg, sizeof(*sg_origin));
1250         /*
1251          * The first pass looks for unrenamed path to optimize for
1252          * common cases, then we look for renames in the second pass.
1253          */
1254         for (pass = 0; pass < 2; pass++) {
1255                 struct origin *(*find)(struct scoreboard *,
1256                                        struct commit *, struct origin *);
1257                 find = pass ? find_rename : find_origin;
1259                 for (i = 0, sg = first_scapegoat(revs, commit);
1260                      i < num_sg && sg;
1261                      sg = sg->next, i++) {
1262                         struct commit *p = sg->item;
1263                         int j, same;
1265                         if (sg_origin[i])
1266                                 continue;
1267                         if (parse_commit(p))
1268                                 continue;
1269                         porigin = find(sb, p, origin);
1270                         if (!porigin)
1271                                 continue;
1272                         if (!hashcmp(porigin->blob_sha1, origin->blob_sha1)) {
1273                                 pass_whole_blame(sb, origin, porigin);
1274                                 origin_decref(porigin);
1275                                 goto finish;
1276                         }
1277                         for (j = same = 0; j < i; j++)
1278                                 if (sg_origin[j] &&
1279                                     !hashcmp(sg_origin[j]->blob_sha1,
1280                                              porigin->blob_sha1)) {
1281                                         same = 1;
1282                                         break;
1283                                 }
1284                         if (!same)
1285                                 sg_origin[i] = porigin;
1286                         else
1287                                 origin_decref(porigin);
1288                 }
1289         }
1291         num_commits++;
1292         for (i = 0, sg = first_scapegoat(revs, commit);
1293              i < num_sg && sg;
1294              sg = sg->next, i++) {
1295                 struct origin *porigin = sg_origin[i];
1296                 if (!porigin)
1297                         continue;
1298                 if (!origin->previous) {
1299                         origin_incref(porigin);
1300                         origin->previous = porigin;
1301                 }
1302                 if (pass_blame_to_parent(sb, origin, porigin))
1303                         goto finish;
1304         }
1306         /*
1307          * Optionally find moves in parents' files.
1308          */
1309         if (opt & PICKAXE_BLAME_MOVE)
1310                 for (i = 0, sg = first_scapegoat(revs, commit);
1311                      i < num_sg && sg;
1312                      sg = sg->next, i++) {
1313                         struct origin *porigin = sg_origin[i];
1314                         if (!porigin)
1315                                 continue;
1316                         if (find_move_in_parent(sb, origin, porigin))
1317                                 goto finish;
1318                 }
1320         /*
1321          * Optionally find copies from parents' files.
1322          */
1323         if (opt & PICKAXE_BLAME_COPY)
1324                 for (i = 0, sg = first_scapegoat(revs, commit);
1325                      i < num_sg && sg;
1326                      sg = sg->next, i++) {
1327                         struct origin *porigin = sg_origin[i];
1328                         if (find_copy_in_parent(sb, origin, sg->item,
1329                                                 porigin, opt))
1330                                 goto finish;
1331                 }
1333  finish:
1334         for (i = 0; i < num_sg; i++) {
1335                 if (sg_origin[i]) {
1336                         drop_origin_blob(sg_origin[i]);
1337                         origin_decref(sg_origin[i]);
1338                 }
1339         }
1340         drop_origin_blob(origin);
1341         if (sg_buf != sg_origin)
1342                 free(sg_origin);
1345 /*
1346  * Information on commits, used for output.
1347  */
1348 struct commit_info
1350         const char *author;
1351         const char *author_mail;
1352         unsigned long author_time;
1353         const char *author_tz;
1355         /* filled only when asked for details */
1356         const char *committer;
1357         const char *committer_mail;
1358         unsigned long committer_time;
1359         const char *committer_tz;
1361         const char *summary;
1362 };
1364 /*
1365  * Parse author/committer line in the commit object buffer
1366  */
1367 static void get_ac_line(const char *inbuf, const char *what,
1368                         int bufsz, char *person, const char **mail,
1369                         unsigned long *time, const char **tz)
1371         int len, tzlen, maillen;
1372         char *tmp, *endp, *timepos;
1374         tmp = strstr(inbuf, what);
1375         if (!tmp)
1376                 goto error_out;
1377         tmp += strlen(what);
1378         endp = strchr(tmp, '\n');
1379         if (!endp)
1380                 len = strlen(tmp);
1381         else
1382                 len = endp - tmp;
1383         if (bufsz <= len) {
1384         error_out:
1385                 /* Ugh */
1386                 *mail = *tz = "(unknown)";
1387                 *time = 0;
1388                 return;
1389         }
1390         memcpy(person, tmp, len);
1392         tmp = person;
1393         tmp += len;
1394         *tmp = 0;
1395         while (*tmp != ' ')
1396                 tmp--;
1397         *tz = tmp+1;
1398         tzlen = (person+len)-(tmp+1);
1400         *tmp = 0;
1401         while (*tmp != ' ')
1402                 tmp--;
1403         *time = strtoul(tmp, NULL, 10);
1404         timepos = tmp;
1406         *tmp = 0;
1407         while (*tmp != ' ')
1408                 tmp--;
1409         *mail = tmp + 1;
1410         *tmp = 0;
1411         maillen = timepos - tmp;
1413         if (!mailmap.nr)
1414                 return;
1416         /*
1417          * mailmap expansion may make the name longer.
1418          * make room by pushing stuff down.
1419          */
1420         tmp = person + bufsz - (tzlen + 1);
1421         memmove(tmp, *tz, tzlen);
1422         tmp[tzlen] = 0;
1423         *tz = tmp;
1425         tmp = tmp - (maillen + 1);
1426         memmove(tmp, *mail, maillen);
1427         tmp[maillen] = 0;
1428         *mail = tmp;
1430         /*
1431          * Now, convert e-mail using mailmap
1432          */
1433         map_email(&mailmap, tmp + 1, person, tmp-person-1);
1436 static void get_commit_info(struct commit *commit,
1437                             struct commit_info *ret,
1438                             int detailed)
1440         int len;
1441         char *tmp, *endp;
1442         static char author_buf[1024];
1443         static char committer_buf[1024];
1444         static char summary_buf[1024];
1446         /*
1447          * We've operated without save_commit_buffer, so
1448          * we now need to populate them for output.
1449          */
1450         if (!commit->buffer) {
1451                 enum object_type type;
1452                 unsigned long size;
1453                 commit->buffer =
1454                         read_sha1_file(commit->object.sha1, &type, &size);
1455                 if (!commit->buffer)
1456                         die("Cannot read commit %s",
1457                             sha1_to_hex(commit->object.sha1));
1458         }
1459         ret->author = author_buf;
1460         get_ac_line(commit->buffer, "\nauthor ",
1461                     sizeof(author_buf), author_buf, &ret->author_mail,
1462                     &ret->author_time, &ret->author_tz);
1464         if (!detailed)
1465                 return;
1467         ret->committer = committer_buf;
1468         get_ac_line(commit->buffer, "\ncommitter ",
1469                     sizeof(committer_buf), committer_buf, &ret->committer_mail,
1470                     &ret->committer_time, &ret->committer_tz);
1472         ret->summary = summary_buf;
1473         tmp = strstr(commit->buffer, "\n\n");
1474         if (!tmp) {
1475         error_out:
1476                 sprintf(summary_buf, "(%s)", sha1_to_hex(commit->object.sha1));
1477                 return;
1478         }
1479         tmp += 2;
1480         endp = strchr(tmp, '\n');
1481         if (!endp)
1482                 endp = tmp + strlen(tmp);
1483         len = endp - tmp;
1484         if (len >= sizeof(summary_buf) || len == 0)
1485                 goto error_out;
1486         memcpy(summary_buf, tmp, len);
1487         summary_buf[len] = 0;
1490 /*
1491  * To allow LF and other nonportable characters in pathnames,
1492  * they are c-style quoted as needed.
1493  */
1494 static void write_filename_info(const char *path)
1496         printf("filename ");
1497         write_name_quoted(path, stdout, '\n');
1500 /*
1501  * Porcelain/Incremental format wants to show a lot of details per
1502  * commit.  Instead of repeating this every line, emit it only once,
1503  * the first time each commit appears in the output.
1504  */
1505 static int emit_one_suspect_detail(struct origin *suspect)
1507         struct commit_info ci;
1509         if (suspect->commit->object.flags & METAINFO_SHOWN)
1510                 return 0;
1512         suspect->commit->object.flags |= METAINFO_SHOWN;
1513         get_commit_info(suspect->commit, &ci, 1);
1514         printf("author %s\n", ci.author);
1515         printf("author-mail %s\n", ci.author_mail);
1516         printf("author-time %lu\n", ci.author_time);
1517         printf("author-tz %s\n", ci.author_tz);
1518         printf("committer %s\n", ci.committer);
1519         printf("committer-mail %s\n", ci.committer_mail);
1520         printf("committer-time %lu\n", ci.committer_time);
1521         printf("committer-tz %s\n", ci.committer_tz);
1522         printf("summary %s\n", ci.summary);
1523         if (suspect->commit->object.flags & UNINTERESTING)
1524                 printf("boundary\n");
1525         if (suspect->previous) {
1526                 struct origin *prev = suspect->previous;
1527                 printf("previous %s ", sha1_to_hex(prev->commit->object.sha1));
1528                 write_name_quoted(prev->path, stdout, '\n');
1529         }
1530         return 1;
1533 /*
1534  * The blame_entry is found to be guilty for the range.  Mark it
1535  * as such, and show it in incremental output.
1536  */
1537 static void found_guilty_entry(struct blame_entry *ent)
1539         if (ent->guilty)
1540                 return;
1541         ent->guilty = 1;
1542         if (incremental) {
1543                 struct origin *suspect = ent->suspect;
1545                 printf("%s %d %d %d\n",
1546                        sha1_to_hex(suspect->commit->object.sha1),
1547                        ent->s_lno + 1, ent->lno + 1, ent->num_lines);
1548                 emit_one_suspect_detail(suspect);
1549                 write_filename_info(suspect->path);
1550                 maybe_flush_or_die(stdout, "stdout");
1551         }
1554 /*
1555  * The main loop -- while the scoreboard has lines whose true origin
1556  * is still unknown, pick one blame_entry, and allow its current
1557  * suspect to pass blames to its parents.
1558  */
1559 static void assign_blame(struct scoreboard *sb, int opt)
1561         struct rev_info *revs = sb->revs;
1563         while (1) {
1564                 struct blame_entry *ent;
1565                 struct commit *commit;
1566                 struct origin *suspect = NULL;
1568                 /* find one suspect to break down */
1569                 for (ent = sb->ent; !suspect && ent; ent = ent->next)
1570                         if (!ent->guilty)
1571                                 suspect = ent->suspect;
1572                 if (!suspect)
1573                         return; /* all done */
1575                 /*
1576                  * We will use this suspect later in the loop,
1577                  * so hold onto it in the meantime.
1578                  */
1579                 origin_incref(suspect);
1580                 commit = suspect->commit;
1581                 if (!commit->object.parsed)
1582                         parse_commit(commit);
1583                 if (reverse ||
1584                     (!(commit->object.flags & UNINTERESTING) &&
1585                      !(revs->max_age != -1 && commit->date < revs->max_age)))
1586                         pass_blame(sb, suspect, opt);
1587                 else {
1588                         commit->object.flags |= UNINTERESTING;
1589                         if (commit->object.parsed)
1590                                 mark_parents_uninteresting(commit);
1591                 }
1592                 /* treat root commit as boundary */
1593                 if (!commit->parents && !show_root)
1594                         commit->object.flags |= UNINTERESTING;
1596                 /* Take responsibility for the remaining entries */
1597                 for (ent = sb->ent; ent; ent = ent->next)
1598                         if (same_suspect(ent->suspect, suspect))
1599                                 found_guilty_entry(ent);
1600                 origin_decref(suspect);
1602                 if (DEBUG) /* sanity */
1603                         sanity_check_refcnt(sb);
1604         }
1607 static const char *format_time(unsigned long time, const char *tz_str,
1608                                int show_raw_time)
1610         static char time_buf[128];
1611         time_t t = time;
1612         int minutes, tz;
1613         struct tm *tm;
1615         if (show_raw_time) {
1616                 sprintf(time_buf, "%lu %s", time, tz_str);
1617                 return time_buf;
1618         }
1620         tz = atoi(tz_str);
1621         minutes = tz < 0 ? -tz : tz;
1622         minutes = (minutes / 100)*60 + (minutes % 100);
1623         minutes = tz < 0 ? -minutes : minutes;
1624         t = time + minutes * 60;
1625         tm = gmtime(&t);
1627         strftime(time_buf, sizeof(time_buf), "%Y-%m-%d %H:%M:%S ", tm);
1628         strcat(time_buf, tz_str);
1629         return time_buf;
1632 #define OUTPUT_ANNOTATE_COMPAT  001
1633 #define OUTPUT_LONG_OBJECT_NAME 002
1634 #define OUTPUT_RAW_TIMESTAMP    004
1635 #define OUTPUT_PORCELAIN        010
1636 #define OUTPUT_SHOW_NAME        020
1637 #define OUTPUT_SHOW_NUMBER      040
1638 #define OUTPUT_SHOW_SCORE      0100
1639 #define OUTPUT_NO_AUTHOR       0200
1641 static void emit_porcelain(struct scoreboard *sb, struct blame_entry *ent)
1643         int cnt;
1644         const char *cp;
1645         struct origin *suspect = ent->suspect;
1646         char hex[41];
1648         strcpy(hex, sha1_to_hex(suspect->commit->object.sha1));
1649         printf("%s%c%d %d %d\n",
1650                hex,
1651                ent->guilty ? ' ' : '*', // purely for debugging
1652                ent->s_lno + 1,
1653                ent->lno + 1,
1654                ent->num_lines);
1655         if (emit_one_suspect_detail(suspect) ||
1656             (suspect->commit->object.flags & MORE_THAN_ONE_PATH))
1657                 write_filename_info(suspect->path);
1659         cp = nth_line(sb, ent->lno);
1660         for (cnt = 0; cnt < ent->num_lines; cnt++) {
1661                 char ch;
1662                 if (cnt)
1663                         printf("%s %d %d\n", hex,
1664                                ent->s_lno + 1 + cnt,
1665                                ent->lno + 1 + cnt);
1666                 putchar('\t');
1667                 do {
1668                         ch = *cp++;
1669                         putchar(ch);
1670                 } while (ch != '\n' &&
1671                          cp < sb->final_buf + sb->final_buf_size);
1672         }
1675 static void emit_other(struct scoreboard *sb, struct blame_entry *ent, int opt)
1677         int cnt;
1678         const char *cp;
1679         struct origin *suspect = ent->suspect;
1680         struct commit_info ci;
1681         char hex[41];
1682         int show_raw_time = !!(opt & OUTPUT_RAW_TIMESTAMP);
1684         get_commit_info(suspect->commit, &ci, 1);
1685         strcpy(hex, sha1_to_hex(suspect->commit->object.sha1));
1687         cp = nth_line(sb, ent->lno);
1688         for (cnt = 0; cnt < ent->num_lines; cnt++) {
1689                 char ch;
1690                 int length = (opt & OUTPUT_LONG_OBJECT_NAME) ? 40 : 8;
1692                 if (suspect->commit->object.flags & UNINTERESTING) {
1693                         if (blank_boundary)
1694                                 memset(hex, ' ', length);
1695                         else if (!(opt & OUTPUT_ANNOTATE_COMPAT)) {
1696                                 length--;
1697                                 putchar('^');
1698                         }
1699                 }
1701                 printf("%.*s", length, hex);
1702                 if (opt & OUTPUT_ANNOTATE_COMPAT)
1703                         printf("\t(%10s\t%10s\t%d)", ci.author,
1704                                format_time(ci.author_time, ci.author_tz,
1705                                            show_raw_time),
1706                                ent->lno + 1 + cnt);
1707                 else {
1708                         if (opt & OUTPUT_SHOW_SCORE)
1709                                 printf(" %*d %02d",
1710                                        max_score_digits, ent->score,
1711                                        ent->suspect->refcnt);
1712                         if (opt & OUTPUT_SHOW_NAME)
1713                                 printf(" %-*.*s", longest_file, longest_file,
1714                                        suspect->path);
1715                         if (opt & OUTPUT_SHOW_NUMBER)
1716                                 printf(" %*d", max_orig_digits,
1717                                        ent->s_lno + 1 + cnt);
1719                         if (!(opt & OUTPUT_NO_AUTHOR))
1720                                 printf(" (%-*.*s %10s",
1721                                        longest_author, longest_author,
1722                                        ci.author,
1723                                        format_time(ci.author_time,
1724                                                    ci.author_tz,
1725                                                    show_raw_time));
1726                         printf(" %*d) ",
1727                                max_digits, ent->lno + 1 + cnt);
1728                 }
1729                 do {
1730                         ch = *cp++;
1731                         putchar(ch);
1732                 } while (ch != '\n' &&
1733                          cp < sb->final_buf + sb->final_buf_size);
1734         }
1737 static void output(struct scoreboard *sb, int option)
1739         struct blame_entry *ent;
1741         if (option & OUTPUT_PORCELAIN) {
1742                 for (ent = sb->ent; ent; ent = ent->next) {
1743                         struct blame_entry *oth;
1744                         struct origin *suspect = ent->suspect;
1745                         struct commit *commit = suspect->commit;
1746                         if (commit->object.flags & MORE_THAN_ONE_PATH)
1747                                 continue;
1748                         for (oth = ent->next; oth; oth = oth->next) {
1749                                 if ((oth->suspect->commit != commit) ||
1750                                     !strcmp(oth->suspect->path, suspect->path))
1751                                         continue;
1752                                 commit->object.flags |= MORE_THAN_ONE_PATH;
1753                                 break;
1754                         }
1755                 }
1756         }
1758         for (ent = sb->ent; ent; ent = ent->next) {
1759                 if (option & OUTPUT_PORCELAIN)
1760                         emit_porcelain(sb, ent);
1761                 else {
1762                         emit_other(sb, ent, option);
1763                 }
1764         }
1767 /*
1768  * To allow quick access to the contents of nth line in the
1769  * final image, prepare an index in the scoreboard.
1770  */
1771 static int prepare_lines(struct scoreboard *sb)
1773         const char *buf = sb->final_buf;
1774         unsigned long len = sb->final_buf_size;
1775         int num = 0, incomplete = 0, bol = 1;
1777         if (len && buf[len-1] != '\n')
1778                 incomplete++; /* incomplete line at the end */
1779         while (len--) {
1780                 if (bol) {
1781                         sb->lineno = xrealloc(sb->lineno,
1782                                               sizeof(int* ) * (num + 1));
1783                         sb->lineno[num] = buf - sb->final_buf;
1784                         bol = 0;
1785                 }
1786                 if (*buf++ == '\n') {
1787                         num++;
1788                         bol = 1;
1789                 }
1790         }
1791         sb->lineno = xrealloc(sb->lineno,
1792                               sizeof(int* ) * (num + incomplete + 1));
1793         sb->lineno[num + incomplete] = buf - sb->final_buf;
1794         sb->num_lines = num + incomplete;
1795         return sb->num_lines;
1798 /*
1799  * Add phony grafts for use with -S; this is primarily to
1800  * support git's cvsserver that wants to give a linear history
1801  * to its clients.
1802  */
1803 static int read_ancestry(const char *graft_file)
1805         FILE *fp = fopen(graft_file, "r");
1806         char buf[1024];
1807         if (!fp)
1808                 return -1;
1809         while (fgets(buf, sizeof(buf), fp)) {
1810                 /* The format is just "Commit Parent1 Parent2 ...\n" */
1811                 int len = strlen(buf);
1812                 struct commit_graft *graft = read_graft_line(buf, len);
1813                 if (graft)
1814                         register_commit_graft(graft, 0);
1815         }
1816         fclose(fp);
1817         return 0;
1820 /*
1821  * How many columns do we need to show line numbers in decimal?
1822  */
1823 static int lineno_width(int lines)
1825         int i, width;
1827         for (width = 1, i = 10; i <= lines + 1; width++)
1828                 i *= 10;
1829         return width;
1832 /*
1833  * How many columns do we need to show line numbers, authors,
1834  * and filenames?
1835  */
1836 static void find_alignment(struct scoreboard *sb, int *option)
1838         int longest_src_lines = 0;
1839         int longest_dst_lines = 0;
1840         unsigned largest_score = 0;
1841         struct blame_entry *e;
1843         for (e = sb->ent; e; e = e->next) {
1844                 struct origin *suspect = e->suspect;
1845                 struct commit_info ci;
1846                 int num;
1848                 if (strcmp(suspect->path, sb->path))
1849                         *option |= OUTPUT_SHOW_NAME;
1850                 num = strlen(suspect->path);
1851                 if (longest_file < num)
1852                         longest_file = num;
1853                 if (!(suspect->commit->object.flags & METAINFO_SHOWN)) {
1854                         suspect->commit->object.flags |= METAINFO_SHOWN;
1855                         get_commit_info(suspect->commit, &ci, 1);
1856                         num = strlen(ci.author);
1857                         if (longest_author < num)
1858                                 longest_author = num;
1859                 }
1860                 num = e->s_lno + e->num_lines;
1861                 if (longest_src_lines < num)
1862                         longest_src_lines = num;
1863                 num = e->lno + e->num_lines;
1864                 if (longest_dst_lines < num)
1865                         longest_dst_lines = num;
1866                 if (largest_score < ent_score(sb, e))
1867                         largest_score = ent_score(sb, e);
1868         }
1869         max_orig_digits = lineno_width(longest_src_lines);
1870         max_digits = lineno_width(longest_dst_lines);
1871         max_score_digits = lineno_width(largest_score);
1874 /*
1875  * For debugging -- origin is refcounted, and this asserts that
1876  * we do not underflow.
1877  */
1878 static void sanity_check_refcnt(struct scoreboard *sb)
1880         int baa = 0;
1881         struct blame_entry *ent;
1883         for (ent = sb->ent; ent; ent = ent->next) {
1884                 /* Nobody should have zero or negative refcnt */
1885                 if (ent->suspect->refcnt <= 0) {
1886                         fprintf(stderr, "%s in %s has negative refcnt %d\n",
1887                                 ent->suspect->path,
1888                                 sha1_to_hex(ent->suspect->commit->object.sha1),
1889                                 ent->suspect->refcnt);
1890                         baa = 1;
1891                 }
1892         }
1893         if (baa) {
1894                 int opt = 0160;
1895                 find_alignment(sb, &opt);
1896                 output(sb, opt);
1897                 die("Baa %d!", baa);
1898         }
1901 /*
1902  * Used for the command line parsing; check if the path exists
1903  * in the working tree.
1904  */
1905 static int has_string_in_work_tree(const char *path)
1907         struct stat st;
1908         return !lstat(path, &st);
1911 static unsigned parse_score(const char *arg)
1913         char *end;
1914         unsigned long score = strtoul(arg, &end, 10);
1915         if (*end)
1916                 return 0;
1917         return score;
1920 static const char *add_prefix(const char *prefix, const char *path)
1922         return prefix_path(prefix, prefix ? strlen(prefix) : 0, path);
1925 /*
1926  * Parsing of (comma separated) one item in the -L option
1927  */
1928 static const char *parse_loc(const char *spec,
1929                              struct scoreboard *sb, long lno,
1930                              long begin, long *ret)
1932         char *term;
1933         const char *line;
1934         long num;
1935         int reg_error;
1936         regex_t regexp;
1937         regmatch_t match[1];
1939         /* Allow "-L <something>,+20" to mean starting at <something>
1940          * for 20 lines, or "-L <something>,-5" for 5 lines ending at
1941          * <something>.
1942          */
1943         if (1 < begin && (spec[0] == '+' || spec[0] == '-')) {
1944                 num = strtol(spec + 1, &term, 10);
1945                 if (term != spec + 1) {
1946                         if (spec[0] == '-')
1947                                 num = 0 - num;
1948                         if (0 < num)
1949                                 *ret = begin + num - 2;
1950                         else if (!num)
1951                                 *ret = begin;
1952                         else
1953                                 *ret = begin + num;
1954                         return term;
1955                 }
1956                 return spec;
1957         }
1958         num = strtol(spec, &term, 10);
1959         if (term != spec) {
1960                 *ret = num;
1961                 return term;
1962         }
1963         if (spec[0] != '/')
1964                 return spec;
1966         /* it could be a regexp of form /.../ */
1967         for (term = (char*) spec + 1; *term && *term != '/'; term++) {
1968                 if (*term == '\\')
1969                         term++;
1970         }
1971         if (*term != '/')
1972                 return spec;
1974         /* try [spec+1 .. term-1] as regexp */
1975         *term = 0;
1976         begin--; /* input is in human terms */
1977         line = nth_line(sb, begin);
1979         if (!(reg_error = regcomp(&regexp, spec + 1, REG_NEWLINE)) &&
1980             !(reg_error = regexec(&regexp, line, 1, match, 0))) {
1981                 const char *cp = line + match[0].rm_so;
1982                 const char *nline;
1984                 while (begin++ < lno) {
1985                         nline = nth_line(sb, begin);
1986                         if (line <= cp && cp < nline)
1987                                 break;
1988                         line = nline;
1989                 }
1990                 *ret = begin;
1991                 regfree(&regexp);
1992                 *term++ = '/';
1993                 return term;
1994         }
1995         else {
1996                 char errbuf[1024];
1997                 regerror(reg_error, &regexp, errbuf, 1024);
1998                 die("-L parameter '%s': %s", spec + 1, errbuf);
1999         }
2002 /*
2003  * Parsing of -L option
2004  */
2005 static void prepare_blame_range(struct scoreboard *sb,
2006                                 const char *bottomtop,
2007                                 long lno,
2008                                 long *bottom, long *top)
2010         const char *term;
2012         term = parse_loc(bottomtop, sb, lno, 1, bottom);
2013         if (*term == ',') {
2014                 term = parse_loc(term + 1, sb, lno, *bottom + 1, top);
2015                 if (*term)
2016                         usage(blame_usage);
2017         }
2018         if (*term)
2019                 usage(blame_usage);
2022 static int git_blame_config(const char *var, const char *value, void *cb)
2024         if (!strcmp(var, "blame.showroot")) {
2025                 show_root = git_config_bool(var, value);
2026                 return 0;
2027         }
2028         if (!strcmp(var, "blame.blankboundary")) {
2029                 blank_boundary = git_config_bool(var, value);
2030                 return 0;
2031         }
2032         return git_default_config(var, value, cb);
2035 /*
2036  * Prepare a dummy commit that represents the work tree (or staged) item.
2037  * Note that annotating work tree item never works in the reverse.
2038  */
2039 static struct commit *fake_working_tree_commit(const char *path, const char *contents_from)
2041         struct commit *commit;
2042         struct origin *origin;
2043         unsigned char head_sha1[20];
2044         struct strbuf buf = STRBUF_INIT;
2045         const char *ident;
2046         time_t now;
2047         int size, len;
2048         struct cache_entry *ce;
2049         unsigned mode;
2051         if (get_sha1("HEAD", head_sha1))
2052                 die("No such ref: HEAD");
2054         time(&now);
2055         commit = xcalloc(1, sizeof(*commit));
2056         commit->parents = xcalloc(1, sizeof(*commit->parents));
2057         commit->parents->item = lookup_commit_reference(head_sha1);
2058         commit->object.parsed = 1;
2059         commit->date = now;
2060         commit->object.type = OBJ_COMMIT;
2062         origin = make_origin(commit, path);
2064         if (!contents_from || strcmp("-", contents_from)) {
2065                 struct stat st;
2066                 const char *read_from;
2067                 unsigned long fin_size;
2069                 if (contents_from) {
2070                         if (stat(contents_from, &st) < 0)
2071                                 die("Cannot stat %s", contents_from);
2072                         read_from = contents_from;
2073                 }
2074                 else {
2075                         if (lstat(path, &st) < 0)
2076                                 die("Cannot lstat %s", path);
2077                         read_from = path;
2078                 }
2079                 fin_size = xsize_t(st.st_size);
2080                 mode = canon_mode(st.st_mode);
2081                 switch (st.st_mode & S_IFMT) {
2082                 case S_IFREG:
2083                         if (strbuf_read_file(&buf, read_from, st.st_size) != st.st_size)
2084                                 die("cannot open or read %s", read_from);
2085                         break;
2086                 case S_IFLNK:
2087                         if (readlink(read_from, buf.buf, buf.alloc) != fin_size)
2088                                 die("cannot readlink %s", read_from);
2089                         buf.len = fin_size;
2090                         break;
2091                 default:
2092                         die("unsupported file type %s", read_from);
2093                 }
2094         }
2095         else {
2096                 /* Reading from stdin */
2097                 contents_from = "standard input";
2098                 mode = 0;
2099                 if (strbuf_read(&buf, 0, 0) < 0)
2100                         die("read error %s from stdin", strerror(errno));
2101         }
2102         convert_to_git(path, buf.buf, buf.len, &buf, 0);
2103         origin->file.ptr = buf.buf;
2104         origin->file.size = buf.len;
2105         pretend_sha1_file(buf.buf, buf.len, OBJ_BLOB, origin->blob_sha1);
2106         commit->util = origin;
2108         /*
2109          * Read the current index, replace the path entry with
2110          * origin->blob_sha1 without mucking with its mode or type
2111          * bits; we are not going to write this index out -- we just
2112          * want to run "diff-index --cached".
2113          */
2114         discard_cache();
2115         read_cache();
2117         len = strlen(path);
2118         if (!mode) {
2119                 int pos = cache_name_pos(path, len);
2120                 if (0 <= pos)
2121                         mode = active_cache[pos]->ce_mode;
2122                 else
2123                         /* Let's not bother reading from HEAD tree */
2124                         mode = S_IFREG | 0644;
2125         }
2126         size = cache_entry_size(len);
2127         ce = xcalloc(1, size);
2128         hashcpy(ce->sha1, origin->blob_sha1);
2129         memcpy(ce->name, path, len);
2130         ce->ce_flags = create_ce_flags(len, 0);
2131         ce->ce_mode = create_ce_mode(mode);
2132         add_cache_entry(ce, ADD_CACHE_OK_TO_ADD|ADD_CACHE_OK_TO_REPLACE);
2134         /*
2135          * We are not going to write this out, so this does not matter
2136          * right now, but someday we might optimize diff-index --cached
2137          * with cache-tree information.
2138          */
2139         cache_tree_invalidate_path(active_cache_tree, path);
2141         commit->buffer = xmalloc(400);
2142         ident = fmt_ident("Not Committed Yet", "not.committed.yet", NULL, 0);
2143         snprintf(commit->buffer, 400,
2144                 "tree 0000000000000000000000000000000000000000\n"
2145                 "parent %s\n"
2146                 "author %s\n"
2147                 "committer %s\n\n"
2148                 "Version of %s from %s\n",
2149                 sha1_to_hex(head_sha1),
2150                 ident, ident, path, contents_from ? contents_from : path);
2151         return commit;
2154 static const char *prepare_final(struct scoreboard *sb)
2156         int i;
2157         const char *final_commit_name = NULL;
2158         struct rev_info *revs = sb->revs;
2160         /*
2161          * There must be one and only one positive commit in the
2162          * revs->pending array.
2163          */
2164         for (i = 0; i < revs->pending.nr; i++) {
2165                 struct object *obj = revs->pending.objects[i].item;
2166                 if (obj->flags & UNINTERESTING)
2167                         continue;
2168                 while (obj->type == OBJ_TAG)
2169                         obj = deref_tag(obj, NULL, 0);
2170                 if (obj->type != OBJ_COMMIT)
2171                         die("Non commit %s?", revs->pending.objects[i].name);
2172                 if (sb->final)
2173                         die("More than one commit to dig from %s and %s?",
2174                             revs->pending.objects[i].name,
2175                             final_commit_name);
2176                 sb->final = (struct commit *) obj;
2177                 final_commit_name = revs->pending.objects[i].name;
2178         }
2179         return final_commit_name;
2182 static const char *prepare_initial(struct scoreboard *sb)
2184         int i;
2185         const char *final_commit_name = NULL;
2186         struct rev_info *revs = sb->revs;
2188         /*
2189          * There must be one and only one negative commit, and it must be
2190          * the boundary.
2191          */
2192         for (i = 0; i < revs->pending.nr; i++) {
2193                 struct object *obj = revs->pending.objects[i].item;
2194                 if (!(obj->flags & UNINTERESTING))
2195                         continue;
2196                 while (obj->type == OBJ_TAG)
2197                         obj = deref_tag(obj, NULL, 0);
2198                 if (obj->type != OBJ_COMMIT)
2199                         die("Non commit %s?", revs->pending.objects[i].name);
2200                 if (sb->final)
2201                         die("More than one commit to dig down to %s and %s?",
2202                             revs->pending.objects[i].name,
2203                             final_commit_name);
2204                 sb->final = (struct commit *) obj;
2205                 final_commit_name = revs->pending.objects[i].name;
2206         }
2207         if (!final_commit_name)
2208                 die("No commit to dig down to?");
2209         return final_commit_name;
2212 static int blame_copy_callback(const struct option *option, const char *arg, int unset)
2214         int *opt = option->value;
2216         /*
2217          * -C enables copy from removed files;
2218          * -C -C enables copy from existing files, but only
2219          *       when blaming a new file;
2220          * -C -C -C enables copy from existing files for
2221          *          everybody
2222          */
2223         if (*opt & PICKAXE_BLAME_COPY_HARDER)
2224                 *opt |= PICKAXE_BLAME_COPY_HARDEST;
2225         if (*opt & PICKAXE_BLAME_COPY)
2226                 *opt |= PICKAXE_BLAME_COPY_HARDER;
2227         *opt |= PICKAXE_BLAME_COPY | PICKAXE_BLAME_MOVE;
2229         if (arg)
2230                 blame_copy_score = parse_score(arg);
2231         return 0;
2234 static int blame_move_callback(const struct option *option, const char *arg, int unset)
2236         int *opt = option->value;
2238         *opt |= PICKAXE_BLAME_MOVE;
2240         if (arg)
2241                 blame_move_score = parse_score(arg);
2242         return 0;
2245 static int blame_bottomtop_callback(const struct option *option, const char *arg, int unset)
2247         const char **bottomtop = option->value;
2248         if (!arg)
2249                 return -1;
2250         if (*bottomtop)
2251                 die("More than one '-L n,m' option given");
2252         *bottomtop = arg;
2253         return 0;
2256 int cmd_blame(int argc, const char **argv, const char *prefix)
2258         struct rev_info revs;
2259         const char *path;
2260         struct scoreboard sb;
2261         struct origin *o;
2262         struct blame_entry *ent;
2263         long dashdash_pos, bottom, top, lno;
2264         const char *final_commit_name = NULL;
2265         enum object_type type;
2267         static const char *bottomtop = NULL;
2268         static int output_option = 0, opt = 0;
2269         static int show_stats = 0;
2270         static const char *revs_file = NULL;
2271         static const char *contents_from = NULL;
2272         static const struct option options[] = {
2273                 OPT_BOOLEAN(0, "incremental", &incremental, "Show blame entries as we find them, incrementally"),
2274                 OPT_BOOLEAN('b', NULL, &blank_boundary, "Show blank SHA-1 for boundary commits (Default: off)"),
2275                 OPT_BOOLEAN(0, "root", &show_root, "Do not treat root commits as boundaries (Default: off)"),
2276                 OPT_BOOLEAN(0, "show-stats", &show_stats, "Show work cost statistics"),
2277                 OPT_BIT(0, "score-debug", &output_option, "Show output score for blame entries", OUTPUT_SHOW_SCORE),
2278                 OPT_BIT('f', "show-name", &output_option, "Show original filename (Default: auto)", OUTPUT_SHOW_NAME),
2279                 OPT_BIT('n', "show-number", &output_option, "Show original linenumber (Default: off)", OUTPUT_SHOW_NUMBER),
2280                 OPT_BIT('p', "porcelain", &output_option, "Show in a format designed for machine consumption", OUTPUT_PORCELAIN),
2281                 OPT_BIT('c', NULL, &output_option, "Use the same output mode as git-annotate (Default: off)", OUTPUT_ANNOTATE_COMPAT),
2282                 OPT_BIT('t', NULL, &output_option, "Show raw timestamp (Default: off)", OUTPUT_RAW_TIMESTAMP),
2283                 OPT_BIT('l', NULL, &output_option, "Show long commit SHA1 (Default: off)", OUTPUT_LONG_OBJECT_NAME),
2284                 OPT_BIT('s', NULL, &output_option, "Suppress author name and timestamp (Default: off)", OUTPUT_NO_AUTHOR),
2285                 OPT_BIT('w', NULL, &xdl_opts, "Ignore whitespace differences", XDF_IGNORE_WHITESPACE),
2286                 OPT_STRING('S', NULL, &revs_file, "file", "Use revisions from <file> instead of calling git-rev-list"),
2287                 OPT_STRING(0, "contents", &contents_from, "file", "Use <file>'s contents as the final image"),
2288                 { OPTION_CALLBACK, 'C', NULL, &opt, "score", "Find line copies within and across files", PARSE_OPT_OPTARG, blame_copy_callback },
2289                 { OPTION_CALLBACK, 'M', NULL, &opt, "score", "Find line movements within and across files", PARSE_OPT_OPTARG, blame_move_callback },
2290                 OPT_CALLBACK('L', NULL, &bottomtop, "n,m", "Process only line range n,m, counting from 1", blame_bottomtop_callback),
2291                 OPT_END()
2292         };
2294         struct parse_opt_ctx_t ctx;
2295         int cmd_is_annotate = !strcmp(argv[0], "annotate");
2297         git_config(git_blame_config, NULL);
2298         init_revisions(&revs, NULL);
2299         save_commit_buffer = 0;
2300         dashdash_pos = 0;
2302         parse_options_start(&ctx, argc, argv, PARSE_OPT_KEEP_DASHDASH |
2303                             PARSE_OPT_KEEP_ARGV0);
2304         for (;;) {
2305                 switch (parse_options_step(&ctx, options, blame_opt_usage)) {
2306                 case PARSE_OPT_HELP:
2307                         exit(129);
2308                 case PARSE_OPT_DONE:
2309                         if (ctx.argv[0])
2310                                 dashdash_pos = ctx.cpidx;
2311                         goto parse_done;
2312                 }
2314                 if (!strcmp(ctx.argv[0], "--reverse")) {
2315                         ctx.argv[0] = "--children";
2316                         reverse = 1;
2317                 }
2318                 parse_revision_opt(&revs, &ctx, options, blame_opt_usage);
2319         }
2320 parse_done:
2321         argc = parse_options_end(&ctx);
2323         if (cmd_is_annotate)
2324                 output_option |= OUTPUT_ANNOTATE_COMPAT;
2326         if (DIFF_OPT_TST(&revs.diffopt, FIND_COPIES_HARDER))
2327                 opt |= (PICKAXE_BLAME_COPY | PICKAXE_BLAME_MOVE |
2328                         PICKAXE_BLAME_COPY_HARDER);
2330         if (!blame_move_score)
2331                 blame_move_score = BLAME_DEFAULT_MOVE_SCORE;
2332         if (!blame_copy_score)
2333                 blame_copy_score = BLAME_DEFAULT_COPY_SCORE;
2335         /*
2336          * We have collected options unknown to us in argv[1..unk]
2337          * which are to be passed to revision machinery if we are
2338          * going to do the "bottom" processing.
2339          *
2340          * The remaining are:
2341          *
2342          * (1) if dashdash_pos != 0, its either
2343          *     "blame [revisions] -- <path>" or
2344          *     "blame -- <path> <rev>"
2345          *
2346          * (2) otherwise, its one of the two:
2347          *     "blame [revisions] <path>"
2348          *     "blame <path> <rev>"
2349          *
2350          * Note that we must strip out <path> from the arguments: we do not
2351          * want the path pruning but we may want "bottom" processing.
2352          */
2353         if (dashdash_pos) {
2354                 switch (argc - dashdash_pos - 1) {
2355                 case 2: /* (1b) */
2356                         if (argc != 4)
2357                                 usage_with_options(blame_opt_usage, options);
2358                         /* reorder for the new way: <rev> -- <path> */
2359                         argv[1] = argv[3];
2360                         argv[3] = argv[2];
2361                         argv[2] = "--";
2362                         /* FALLTHROUGH */
2363                 case 1: /* (1a) */
2364                         path = add_prefix(prefix, argv[--argc]);
2365                         argv[argc] = NULL;
2366                         break;
2367                 default:
2368                         usage_with_options(blame_opt_usage, options);
2369                 }
2370         } else {
2371                 if (argc < 2)
2372                         usage_with_options(blame_opt_usage, options);
2373                 path = add_prefix(prefix, argv[argc - 1]);
2374                 if (argc == 3 && !has_string_in_work_tree(path)) { /* (2b) */
2375                         path = add_prefix(prefix, argv[1]);
2376                         argv[1] = argv[2];
2377                 }
2378                 argv[argc - 1] = "--";
2380                 setup_work_tree();
2381                 if (!has_string_in_work_tree(path))
2382                         die("cannot stat path %s: %s", path, strerror(errno));
2383         }
2385         setup_revisions(argc, argv, &revs, NULL);
2386         memset(&sb, 0, sizeof(sb));
2388         sb.revs = &revs;
2389         if (!reverse)
2390                 final_commit_name = prepare_final(&sb);
2391         else if (contents_from)
2392                 die("--contents and --children do not blend well.");
2393         else
2394                 final_commit_name = prepare_initial(&sb);
2396         if (!sb.final) {
2397                 /*
2398                  * "--not A B -- path" without anything positive;
2399                  * do not default to HEAD, but use the working tree
2400                  * or "--contents".
2401                  */
2402                 setup_work_tree();
2403                 sb.final = fake_working_tree_commit(path, contents_from);
2404                 add_pending_object(&revs, &(sb.final->object), ":");
2405         }
2406         else if (contents_from)
2407                 die("Cannot use --contents with final commit object name");
2409         /*
2410          * If we have bottom, this will mark the ancestors of the
2411          * bottom commits we would reach while traversing as
2412          * uninteresting.
2413          */
2414         if (prepare_revision_walk(&revs))
2415                 die("revision walk setup failed");
2417         if (is_null_sha1(sb.final->object.sha1)) {
2418                 char *buf;
2419                 o = sb.final->util;
2420                 buf = xmalloc(o->file.size + 1);
2421                 memcpy(buf, o->file.ptr, o->file.size + 1);
2422                 sb.final_buf = buf;
2423                 sb.final_buf_size = o->file.size;
2424         }
2425         else {
2426                 o = get_origin(&sb, sb.final, path);
2427                 if (fill_blob_sha1(o))
2428                         die("no such path %s in %s", path, final_commit_name);
2430                 sb.final_buf = read_sha1_file(o->blob_sha1, &type,
2431                                               &sb.final_buf_size);
2432                 if (!sb.final_buf)
2433                         die("Cannot read blob %s for path %s",
2434                             sha1_to_hex(o->blob_sha1),
2435                             path);
2436         }
2437         num_read_blob++;
2438         lno = prepare_lines(&sb);
2440         bottom = top = 0;
2441         if (bottomtop)
2442                 prepare_blame_range(&sb, bottomtop, lno, &bottom, &top);
2443         if (bottom && top && top < bottom) {
2444                 long tmp;
2445                 tmp = top; top = bottom; bottom = tmp;
2446         }
2447         if (bottom < 1)
2448                 bottom = 1;
2449         if (top < 1)
2450                 top = lno;
2451         bottom--;
2452         if (lno < top)
2453                 die("file %s has only %lu lines", path, lno);
2455         ent = xcalloc(1, sizeof(*ent));
2456         ent->lno = bottom;
2457         ent->num_lines = top - bottom;
2458         ent->suspect = o;
2459         ent->s_lno = bottom;
2461         sb.ent = ent;
2462         sb.path = path;
2464         if (revs_file && read_ancestry(revs_file))
2465                 die("reading graft file %s failed: %s",
2466                     revs_file, strerror(errno));
2468         read_mailmap(&mailmap, ".mailmap", NULL);
2470         if (!incremental)
2471                 setup_pager();
2473         assign_blame(&sb, opt);
2475         if (incremental)
2476                 return 0;
2478         coalesce(&sb);
2480         if (!(output_option & OUTPUT_PORCELAIN))
2481                 find_alignment(&sb, &output_option);
2483         output(&sb, output_option);
2484         free((void *)sb.final_buf);
2485         for (ent = sb.ent; ent; ) {
2486                 struct blame_entry *e = ent->next;
2487                 free(ent);
2488                 ent = e;
2489         }
2491         if (show_stats) {
2492                 printf("num read blob: %d\n", num_read_blob);
2493                 printf("num get patch: %d\n", num_get_patch);
2494                 printf("num commits: %d\n", num_commits);
2495         }
2496         return 0;