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