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