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