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 diff_setup_done(&diff_opts);
396
397 if (is_null_sha1(origin->commit->object.sha1))
398 do_diff_cache(parent->tree->object.sha1, &diff_opts);
399 else
400 diff_tree_sha1(parent->tree->object.sha1,
401 origin->commit->tree->object.sha1,
402 "", &diff_opts);
403 diffcore_std(&diff_opts);
404
405 if (!diff_queued_diff.nr) {
406 /* The path is the same as parent */
407 porigin = get_origin(sb, parent, origin->path);
408 hashcpy(porigin->blob_sha1, origin->blob_sha1);
409 porigin->mode = origin->mode;
410 } else {
411 /*
412 * Since origin->path is a pathspec, if the parent
413 * commit had it as a directory, we will see a whole
414 * bunch of deletion of files in the directory that we
415 * do not care about.
416 */
417 int i;
418 struct diff_filepair *p = NULL;
419 for (i = 0; i < diff_queued_diff.nr; i++) {
420 const char *name;
421 p = diff_queued_diff.queue[i];
422 name = p->one->path ? p->one->path : p->two->path;
423 if (!strcmp(name, origin->path))
424 break;
425 }
426 if (!p)
427 die("internal error in blame::find_origin");
428 switch (p->status) {
429 default:
430 die("internal error in blame::find_origin (%c)",
431 p->status);
432 case 'M':
433 porigin = get_origin(sb, parent, origin->path);
434 hashcpy(porigin->blob_sha1, p->one->sha1);
435 porigin->mode = p->one->mode;
436 break;
437 case 'A':
438 case 'T':
439 /* Did not exist in parent, or type changed */
440 break;
441 }
442 }
443 diff_flush(&diff_opts);
444 diff_tree_release_paths(&diff_opts);
445 if (porigin) {
446 /*
447 * Create a freestanding copy that is not part of
448 * the refcounted origin found in the scoreboard, and
449 * cache it in the commit.
450 */
451 struct origin *cached;
452
453 cached = make_origin(porigin->commit, porigin->path);
454 hashcpy(cached->blob_sha1, porigin->blob_sha1);
455 cached->mode = porigin->mode;
456 parent->util = cached;
457 }
458 return porigin;
459}
460
461/*
462 * We have an origin -- find the path that corresponds to it in its
463 * parent and return an origin structure to represent it.
464 */
465static struct origin *find_rename(struct scoreboard *sb,
466 struct commit *parent,
467 struct origin *origin)
468{
469 struct origin *porigin = NULL;
470 struct diff_options diff_opts;
471 int i;
472 const char *paths[2];
473
474 diff_setup(&diff_opts);
475 DIFF_OPT_SET(&diff_opts, RECURSIVE);
476 diff_opts.detect_rename = DIFF_DETECT_RENAME;
477 diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;
478 diff_opts.single_follow = origin->path;
479 paths[0] = NULL;
480 diff_tree_setup_paths(paths, &diff_opts);
481 diff_setup_done(&diff_opts);
482
483 if (is_null_sha1(origin->commit->object.sha1))
484 do_diff_cache(parent->tree->object.sha1, &diff_opts);
485 else
486 diff_tree_sha1(parent->tree->object.sha1,
487 origin->commit->tree->object.sha1,
488 "", &diff_opts);
489 diffcore_std(&diff_opts);
490
491 for (i = 0; i < diff_queued_diff.nr; i++) {
492 struct diff_filepair *p = diff_queued_diff.queue[i];
493 if ((p->status == 'R' || p->status == 'C') &&
494 !strcmp(p->two->path, origin->path)) {
495 porigin = get_origin(sb, parent, p->one->path);
496 hashcpy(porigin->blob_sha1, p->one->sha1);
497 porigin->mode = p->one->mode;
498 break;
499 }
500 }
501 diff_flush(&diff_opts);
502 diff_tree_release_paths(&diff_opts);
503 return porigin;
504}
505
506/*
507 * Link in a new blame entry to the scoreboard. Entries that cover the
508 * same line range have been removed from the scoreboard previously.
509 */
510static void add_blame_entry(struct scoreboard *sb, struct blame_entry *e)
511{
512 struct blame_entry *ent, *prev = NULL;
513
514 origin_incref(e->suspect);
515
516 for (ent = sb->ent; ent && ent->lno < e->lno; ent = ent->next)
517 prev = ent;
518
519 /* prev, if not NULL, is the last one that is below e */
520 e->prev = prev;
521 if (prev) {
522 e->next = prev->next;
523 prev->next = e;
524 }
525 else {
526 e->next = sb->ent;
527 sb->ent = e;
528 }
529 if (e->next)
530 e->next->prev = e;
531}
532
533/*
534 * src typically is on-stack; we want to copy the information in it to
535 * a malloced blame_entry that is already on the linked list of the
536 * scoreboard. The origin of dst loses a refcnt while the origin of src
537 * gains one.
538 */
539static void dup_entry(struct blame_entry *dst, struct blame_entry *src)
540{
541 struct blame_entry *p, *n;
542
543 p = dst->prev;
544 n = dst->next;
545 origin_incref(src->suspect);
546 origin_decref(dst->suspect);
547 memcpy(dst, src, sizeof(*src));
548 dst->prev = p;
549 dst->next = n;
550 dst->score = 0;
551}
552
553static const char *nth_line(struct scoreboard *sb, int lno)
554{
555 return sb->final_buf + sb->lineno[lno];
556}
557
558/*
559 * It is known that lines between tlno to same came from parent, and e
560 * has an overlap with that range. it also is known that parent's
561 * line plno corresponds to e's line tlno.
562 *
563 * <---- e ----->
564 * <------>
565 * <------------>
566 * <------------>
567 * <------------------>
568 *
569 * Split e into potentially three parts; before this chunk, the chunk
570 * to be blamed for the parent, and after that portion.
571 */
572static void split_overlap(struct blame_entry *split,
573 struct blame_entry *e,
574 int tlno, int plno, int same,
575 struct origin *parent)
576{
577 int chunk_end_lno;
578 memset(split, 0, sizeof(struct blame_entry [3]));
579
580 if (e->s_lno < tlno) {
581 /* there is a pre-chunk part not blamed on parent */
582 split[0].suspect = origin_incref(e->suspect);
583 split[0].lno = e->lno;
584 split[0].s_lno = e->s_lno;
585 split[0].num_lines = tlno - e->s_lno;
586 split[1].lno = e->lno + tlno - e->s_lno;
587 split[1].s_lno = plno;
588 }
589 else {
590 split[1].lno = e->lno;
591 split[1].s_lno = plno + (e->s_lno - tlno);
592 }
593
594 if (same < e->s_lno + e->num_lines) {
595 /* there is a post-chunk part not blamed on parent */
596 split[2].suspect = origin_incref(e->suspect);
597 split[2].lno = e->lno + (same - e->s_lno);
598 split[2].s_lno = e->s_lno + (same - e->s_lno);
599 split[2].num_lines = e->s_lno + e->num_lines - same;
600 chunk_end_lno = split[2].lno;
601 }
602 else
603 chunk_end_lno = e->lno + e->num_lines;
604 split[1].num_lines = chunk_end_lno - split[1].lno;
605
606 /*
607 * if it turns out there is nothing to blame the parent for,
608 * forget about the splitting. !split[1].suspect signals this.
609 */
610 if (split[1].num_lines < 1)
611 return;
612 split[1].suspect = origin_incref(parent);
613}
614
615/*
616 * split_overlap() divided an existing blame e into up to three parts
617 * in split. Adjust the linked list of blames in the scoreboard to
618 * reflect the split.
619 */
620static void split_blame(struct scoreboard *sb,
621 struct blame_entry *split,
622 struct blame_entry *e)
623{
624 struct blame_entry *new_entry;
625
626 if (split[0].suspect && split[2].suspect) {
627 /* The first part (reuse storage for the existing entry e) */
628 dup_entry(e, &split[0]);
629
630 /* The last part -- me */
631 new_entry = xmalloc(sizeof(*new_entry));
632 memcpy(new_entry, &(split[2]), sizeof(struct blame_entry));
633 add_blame_entry(sb, new_entry);
634
635 /* ... and the middle part -- parent */
636 new_entry = xmalloc(sizeof(*new_entry));
637 memcpy(new_entry, &(split[1]), sizeof(struct blame_entry));
638 add_blame_entry(sb, new_entry);
639 }
640 else if (!split[0].suspect && !split[2].suspect)
641 /*
642 * The parent covers the entire area; reuse storage for
643 * e and replace it with the parent.
644 */
645 dup_entry(e, &split[1]);
646 else if (split[0].suspect) {
647 /* me and then parent */
648 dup_entry(e, &split[0]);
649
650 new_entry = xmalloc(sizeof(*new_entry));
651 memcpy(new_entry, &(split[1]), sizeof(struct blame_entry));
652 add_blame_entry(sb, new_entry);
653 }
654 else {
655 /* parent and then me */
656 dup_entry(e, &split[1]);
657
658 new_entry = xmalloc(sizeof(*new_entry));
659 memcpy(new_entry, &(split[2]), sizeof(struct blame_entry));
660 add_blame_entry(sb, new_entry);
661 }
662
663 if (DEBUG) { /* sanity */
664 struct blame_entry *ent;
665 int lno = sb->ent->lno, corrupt = 0;
666
667 for (ent = sb->ent; ent; ent = ent->next) {
668 if (lno != ent->lno)
669 corrupt = 1;
670 if (ent->s_lno < 0)
671 corrupt = 1;
672 lno += ent->num_lines;
673 }
674 if (corrupt) {
675 lno = sb->ent->lno;
676 for (ent = sb->ent; ent; ent = ent->next) {
677 printf("L %8d l %8d n %8d\n",
678 lno, ent->lno, ent->num_lines);
679 lno = ent->lno + ent->num_lines;
680 }
681 die("oops");
682 }
683 }
684}
685
686/*
687 * After splitting the blame, the origins used by the
688 * on-stack blame_entry should lose one refcnt each.
689 */
690static void decref_split(struct blame_entry *split)
691{
692 int i;
693
694 for (i = 0; i < 3; i++)
695 origin_decref(split[i].suspect);
696}
697
698/*
699 * Helper for blame_chunk(). blame_entry e is known to overlap with
700 * the patch hunk; split it and pass blame to the parent.
701 */
702static void blame_overlap(struct scoreboard *sb, struct blame_entry *e,
703 int tlno, int plno, int same,
704 struct origin *parent)
705{
706 struct blame_entry split[3];
707
708 split_overlap(split, e, tlno, plno, same, parent);
709 if (split[1].suspect)
710 split_blame(sb, split, e);
711 decref_split(split);
712}
713
714/*
715 * Find the line number of the last line the target is suspected for.
716 */
717static int find_last_in_target(struct scoreboard *sb, struct origin *target)
718{
719 struct blame_entry *e;
720 int last_in_target = -1;
721
722 for (e = sb->ent; e; e = e->next) {
723 if (e->guilty || !same_suspect(e->suspect, target))
724 continue;
725 if (last_in_target < e->s_lno + e->num_lines)
726 last_in_target = e->s_lno + e->num_lines;
727 }
728 return last_in_target;
729}
730
731/*
732 * Process one hunk from the patch between the current suspect for
733 * blame_entry e and its parent. Find and split the overlap, and
734 * pass blame to the overlapping part to the parent.
735 */
736static void blame_chunk(struct scoreboard *sb,
737 int tlno, int plno, int same,
738 struct origin *target, struct origin *parent)
739{
740 struct blame_entry *e;
741
742 for (e = sb->ent; e; e = e->next) {
743 if (e->guilty || !same_suspect(e->suspect, target))
744 continue;
745 if (same <= e->s_lno)
746 continue;
747 if (tlno < e->s_lno + e->num_lines)
748 blame_overlap(sb, e, tlno, plno, same, parent);
749 }
750}
751
752struct blame_chunk_cb_data {
753 struct scoreboard *sb;
754 struct origin *target;
755 struct origin *parent;
756 long plno;
757 long tlno;
758};
759
760static void blame_chunk_cb(void *data, long same, long p_next, long t_next)
761{
762 struct blame_chunk_cb_data *d = data;
763 blame_chunk(d->sb, d->tlno, d->plno, same, d->target, d->parent);
764 d->plno = p_next;
765 d->tlno = t_next;
766}
767
768/*
769 * We are looking at the origin 'target' and aiming to pass blame
770 * for the lines it is suspected to its parent. Run diff to find
771 * which lines came from parent and pass blame for them.
772 */
773static int pass_blame_to_parent(struct scoreboard *sb,
774 struct origin *target,
775 struct origin *parent)
776{
777 int last_in_target;
778 mmfile_t file_p, file_o;
779 struct blame_chunk_cb_data d;
780 xpparam_t xpp;
781 xdemitconf_t xecfg;
782 memset(&d, 0, sizeof(d));
783 d.sb = sb; d.target = target; d.parent = parent;
784 last_in_target = find_last_in_target(sb, target);
785 if (last_in_target < 0)
786 return 1; /* nothing remains for this target */
787
788 fill_origin_blob(&sb->revs->diffopt, parent, &file_p);
789 fill_origin_blob(&sb->revs->diffopt, target, &file_o);
790 num_get_patch++;
791
792 memset(&xpp, 0, sizeof(xpp));
793 xpp.flags = xdl_opts;
794 memset(&xecfg, 0, sizeof(xecfg));
795 xecfg.ctxlen = 0;
796 xdi_diff_hunks(&file_p, &file_o, blame_chunk_cb, &d, &xpp, &xecfg);
797 /* The rest (i.e. anything after tlno) are the same as the parent */
798 blame_chunk(sb, d.tlno, d.plno, last_in_target, target, parent);
799
800 return 0;
801}
802
803/*
804 * The lines in blame_entry after splitting blames many times can become
805 * very small and trivial, and at some point it becomes pointless to
806 * blame the parents. E.g. "\t\t}\n\t}\n\n" appears everywhere in any
807 * ordinary C program, and it is not worth to say it was copied from
808 * totally unrelated file in the parent.
809 *
810 * Compute how trivial the lines in the blame_entry are.
811 */
812static unsigned ent_score(struct scoreboard *sb, struct blame_entry *e)
813{
814 unsigned score;
815 const char *cp, *ep;
816
817 if (e->score)
818 return e->score;
819
820 score = 1;
821 cp = nth_line(sb, e->lno);
822 ep = nth_line(sb, e->lno + e->num_lines);
823 while (cp < ep) {
824 unsigned ch = *((unsigned char *)cp);
825 if (isalnum(ch))
826 score++;
827 cp++;
828 }
829 e->score = score;
830 return score;
831}
832
833/*
834 * best_so_far[] and this[] are both a split of an existing blame_entry
835 * that passes blame to the parent. Maintain best_so_far the best split
836 * so far, by comparing this and best_so_far and copying this into
837 * bst_so_far as needed.
838 */
839static void copy_split_if_better(struct scoreboard *sb,
840 struct blame_entry *best_so_far,
841 struct blame_entry *this)
842{
843 int i;
844
845 if (!this[1].suspect)
846 return;
847 if (best_so_far[1].suspect) {
848 if (ent_score(sb, &this[1]) < ent_score(sb, &best_so_far[1]))
849 return;
850 }
851
852 for (i = 0; i < 3; i++)
853 origin_incref(this[i].suspect);
854 decref_split(best_so_far);
855 memcpy(best_so_far, this, sizeof(struct blame_entry [3]));
856}
857
858/*
859 * We are looking at a part of the final image represented by
860 * ent (tlno and same are offset by ent->s_lno).
861 * tlno is where we are looking at in the final image.
862 * up to (but not including) same match preimage.
863 * plno is where we are looking at in the preimage.
864 *
865 * <-------------- final image ---------------------->
866 * <------ent------>
867 * ^tlno ^same
868 * <---------preimage----->
869 * ^plno
870 *
871 * All line numbers are 0-based.
872 */
873static void handle_split(struct scoreboard *sb,
874 struct blame_entry *ent,
875 int tlno, int plno, int same,
876 struct origin *parent,
877 struct blame_entry *split)
878{
879 if (ent->num_lines <= tlno)
880 return;
881 if (tlno < same) {
882 struct blame_entry this[3];
883 tlno += ent->s_lno;
884 same += ent->s_lno;
885 split_overlap(this, ent, tlno, plno, same, parent);
886 copy_split_if_better(sb, split, this);
887 decref_split(this);
888 }
889}
890
891struct handle_split_cb_data {
892 struct scoreboard *sb;
893 struct blame_entry *ent;
894 struct origin *parent;
895 struct blame_entry *split;
896 long plno;
897 long tlno;
898};
899
900static void handle_split_cb(void *data, long same, long p_next, long t_next)
901{
902 struct handle_split_cb_data *d = data;
903 handle_split(d->sb, d->ent, d->tlno, d->plno, same, d->parent, d->split);
904 d->plno = p_next;
905 d->tlno = t_next;
906}
907
908/*
909 * Find the lines from parent that are the same as ent so that
910 * we can pass blames to it. file_p has the blob contents for
911 * the parent.
912 */
913static void find_copy_in_blob(struct scoreboard *sb,
914 struct blame_entry *ent,
915 struct origin *parent,
916 struct blame_entry *split,
917 mmfile_t *file_p)
918{
919 const char *cp;
920 int cnt;
921 mmfile_t file_o;
922 struct handle_split_cb_data d;
923 xpparam_t xpp;
924 xdemitconf_t xecfg;
925 memset(&d, 0, sizeof(d));
926 d.sb = sb; d.ent = ent; d.parent = parent; d.split = split;
927 /*
928 * Prepare mmfile that contains only the lines in ent.
929 */
930 cp = nth_line(sb, ent->lno);
931 file_o.ptr = (char *) cp;
932 cnt = ent->num_lines;
933
934 while (cnt && cp < sb->final_buf + sb->final_buf_size) {
935 if (*cp++ == '\n')
936 cnt--;
937 }
938 file_o.size = cp - file_o.ptr;
939
940 /*
941 * file_o is a part of final image we are annotating.
942 * file_p partially may match that image.
943 */
944 memset(&xpp, 0, sizeof(xpp));
945 xpp.flags = xdl_opts;
946 memset(&xecfg, 0, sizeof(xecfg));
947 xecfg.ctxlen = 1;
948 memset(split, 0, sizeof(struct blame_entry [3]));
949 xdi_diff_hunks(file_p, &file_o, handle_split_cb, &d, &xpp, &xecfg);
950 /* remainder, if any, all match the preimage */
951 handle_split(sb, ent, d.tlno, d.plno, ent->num_lines, parent, split);
952}
953
954/*
955 * See if lines currently target is suspected for can be attributed to
956 * parent.
957 */
958static int find_move_in_parent(struct scoreboard *sb,
959 struct origin *target,
960 struct origin *parent)
961{
962 int last_in_target, made_progress;
963 struct blame_entry *e, split[3];
964 mmfile_t file_p;
965
966 last_in_target = find_last_in_target(sb, target);
967 if (last_in_target < 0)
968 return 1; /* nothing remains for this target */
969
970 fill_origin_blob(&sb->revs->diffopt, parent, &file_p);
971 if (!file_p.ptr)
972 return 0;
973
974 made_progress = 1;
975 while (made_progress) {
976 made_progress = 0;
977 for (e = sb->ent; e; e = e->next) {
978 if (e->guilty || !same_suspect(e->suspect, target) ||
979 ent_score(sb, e) < blame_move_score)
980 continue;
981 find_copy_in_blob(sb, e, parent, split, &file_p);
982 if (split[1].suspect &&
983 blame_move_score < ent_score(sb, &split[1])) {
984 split_blame(sb, split, e);
985 made_progress = 1;
986 }
987 decref_split(split);
988 }
989 }
990 return 0;
991}
992
993struct blame_list {
994 struct blame_entry *ent;
995 struct blame_entry split[3];
996};
997
998/*
999 * Count the number of entries the target is suspected for,
1000 * and prepare a list of entry and the best split.
1001 */
1002static struct blame_list *setup_blame_list(struct scoreboard *sb,
1003 struct origin *target,
1004 int min_score,
1005 int *num_ents_p)
1006{
1007 struct blame_entry *e;
1008 int num_ents, i;
1009 struct blame_list *blame_list = NULL;
1010
1011 for (e = sb->ent, num_ents = 0; e; e = e->next)
1012 if (!e->scanned && !e->guilty &&
1013 same_suspect(e->suspect, target) &&
1014 min_score < ent_score(sb, e))
1015 num_ents++;
1016 if (num_ents) {
1017 blame_list = xcalloc(num_ents, sizeof(struct blame_list));
1018 for (e = sb->ent, i = 0; e; e = e->next)
1019 if (!e->scanned && !e->guilty &&
1020 same_suspect(e->suspect, target) &&
1021 min_score < ent_score(sb, e))
1022 blame_list[i++].ent = e;
1023 }
1024 *num_ents_p = num_ents;
1025 return blame_list;
1026}
1027
1028/*
1029 * Reset the scanned status on all entries.
1030 */
1031static void reset_scanned_flag(struct scoreboard *sb)
1032{
1033 struct blame_entry *e;
1034 for (e = sb->ent; e; e = e->next)
1035 e->scanned = 0;
1036}
1037
1038/*
1039 * For lines target is suspected for, see if we can find code movement
1040 * across file boundary from the parent commit. porigin is the path
1041 * in the parent we already tried.
1042 */
1043static int find_copy_in_parent(struct scoreboard *sb,
1044 struct origin *target,
1045 struct commit *parent,
1046 struct origin *porigin,
1047 int opt)
1048{
1049 struct diff_options diff_opts;
1050 const char *paths[1];
1051 int i, j;
1052 int retval;
1053 struct blame_list *blame_list;
1054 int num_ents;
1055
1056 blame_list = setup_blame_list(sb, target, blame_copy_score, &num_ents);
1057 if (!blame_list)
1058 return 1; /* nothing remains for this target */
1059
1060 diff_setup(&diff_opts);
1061 DIFF_OPT_SET(&diff_opts, RECURSIVE);
1062 diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;
1063
1064 paths[0] = NULL;
1065 diff_tree_setup_paths(paths, &diff_opts);
1066 diff_setup_done(&diff_opts);
1067
1068 /* Try "find copies harder" on new path if requested;
1069 * we do not want to use diffcore_rename() actually to
1070 * match things up; find_copies_harder is set only to
1071 * force diff_tree_sha1() to feed all filepairs to diff_queue,
1072 * and this code needs to be after diff_setup_done(), which
1073 * usually makes find-copies-harder imply copy detection.
1074 */
1075 if ((opt & PICKAXE_BLAME_COPY_HARDEST)
1076 || ((opt & PICKAXE_BLAME_COPY_HARDER)
1077 && (!porigin || strcmp(target->path, porigin->path))))
1078 DIFF_OPT_SET(&diff_opts, FIND_COPIES_HARDER);
1079
1080 if (is_null_sha1(target->commit->object.sha1))
1081 do_diff_cache(parent->tree->object.sha1, &diff_opts);
1082 else
1083 diff_tree_sha1(parent->tree->object.sha1,
1084 target->commit->tree->object.sha1,
1085 "", &diff_opts);
1086
1087 if (!DIFF_OPT_TST(&diff_opts, FIND_COPIES_HARDER))
1088 diffcore_std(&diff_opts);
1089
1090 retval = 0;
1091 while (1) {
1092 int made_progress = 0;
1093
1094 for (i = 0; i < diff_queued_diff.nr; i++) {
1095 struct diff_filepair *p = diff_queued_diff.queue[i];
1096 struct origin *norigin;
1097 mmfile_t file_p;
1098 struct blame_entry this[3];
1099
1100 if (!DIFF_FILE_VALID(p->one))
1101 continue; /* does not exist in parent */
1102 if (S_ISGITLINK(p->one->mode))
1103 continue; /* ignore git links */
1104 if (porigin && !strcmp(p->one->path, porigin->path))
1105 /* find_move already dealt with this path */
1106 continue;
1107
1108 norigin = get_origin(sb, parent, p->one->path);
1109 hashcpy(norigin->blob_sha1, p->one->sha1);
1110 norigin->mode = p->one->mode;
1111 fill_origin_blob(&sb->revs->diffopt, norigin, &file_p);
1112 if (!file_p.ptr)
1113 continue;
1114
1115 for (j = 0; j < num_ents; j++) {
1116 find_copy_in_blob(sb, blame_list[j].ent,
1117 norigin, this, &file_p);
1118 copy_split_if_better(sb, blame_list[j].split,
1119 this);
1120 decref_split(this);
1121 }
1122 origin_decref(norigin);
1123 }
1124
1125 for (j = 0; j < num_ents; j++) {
1126 struct blame_entry *split = blame_list[j].split;
1127 if (split[1].suspect &&
1128 blame_copy_score < ent_score(sb, &split[1])) {
1129 split_blame(sb, split, blame_list[j].ent);
1130 made_progress = 1;
1131 }
1132 else
1133 blame_list[j].ent->scanned = 1;
1134 decref_split(split);
1135 }
1136 free(blame_list);
1137
1138 if (!made_progress)
1139 break;
1140 blame_list = setup_blame_list(sb, target, blame_copy_score, &num_ents);
1141 if (!blame_list) {
1142 retval = 1;
1143 break;
1144 }
1145 }
1146 reset_scanned_flag(sb);
1147 diff_flush(&diff_opts);
1148 diff_tree_release_paths(&diff_opts);
1149 return retval;
1150}
1151
1152/*
1153 * The blobs of origin and porigin exactly match, so everything
1154 * origin is suspected for can be blamed on the parent.
1155 */
1156static void pass_whole_blame(struct scoreboard *sb,
1157 struct origin *origin, struct origin *porigin)
1158{
1159 struct blame_entry *e;
1160
1161 if (!porigin->file.ptr && origin->file.ptr) {
1162 /* Steal its file */
1163 porigin->file = origin->file;
1164 origin->file.ptr = NULL;
1165 }
1166 for (e = sb->ent; e; e = e->next) {
1167 if (!same_suspect(e->suspect, origin))
1168 continue;
1169 origin_incref(porigin);
1170 origin_decref(e->suspect);
1171 e->suspect = porigin;
1172 }
1173}
1174
1175/*
1176 * We pass blame from the current commit to its parents. We keep saying
1177 * "parent" (and "porigin"), but what we mean is to find scapegoat to
1178 * exonerate ourselves.
1179 */
1180static struct commit_list *first_scapegoat(struct rev_info *revs, struct commit *commit)
1181{
1182 if (!reverse)
1183 return commit->parents;
1184 return lookup_decoration(&revs->children, &commit->object);
1185}
1186
1187static int num_scapegoats(struct rev_info *revs, struct commit *commit)
1188{
1189 int cnt;
1190 struct commit_list *l = first_scapegoat(revs, commit);
1191 for (cnt = 0; l; l = l->next)
1192 cnt++;
1193 return cnt;
1194}
1195
1196#define MAXSG 16
1197
1198static void pass_blame(struct scoreboard *sb, struct origin *origin, int opt)
1199{
1200 struct rev_info *revs = sb->revs;
1201 int i, pass, num_sg;
1202 struct commit *commit = origin->commit;
1203 struct commit_list *sg;
1204 struct origin *sg_buf[MAXSG];
1205 struct origin *porigin, **sg_origin = sg_buf;
1206
1207 num_sg = num_scapegoats(revs, commit);
1208 if (!num_sg)
1209 goto finish;
1210 else if (num_sg < ARRAY_SIZE(sg_buf))
1211 memset(sg_buf, 0, sizeof(sg_buf));
1212 else
1213 sg_origin = xcalloc(num_sg, sizeof(*sg_origin));
1214
1215 /*
1216 * The first pass looks for unrenamed path to optimize for
1217 * common cases, then we look for renames in the second pass.
1218 */
1219 for (pass = 0; pass < 2; pass++) {
1220 struct origin *(*find)(struct scoreboard *,
1221 struct commit *, struct origin *);
1222 find = pass ? find_rename : find_origin;
1223
1224 for (i = 0, sg = first_scapegoat(revs, commit);
1225 i < num_sg && sg;
1226 sg = sg->next, i++) {
1227 struct commit *p = sg->item;
1228 int j, same;
1229
1230 if (sg_origin[i])
1231 continue;
1232 if (parse_commit(p))
1233 continue;
1234 porigin = find(sb, p, origin);
1235 if (!porigin)
1236 continue;
1237 if (!hashcmp(porigin->blob_sha1, origin->blob_sha1)) {
1238 pass_whole_blame(sb, origin, porigin);
1239 origin_decref(porigin);
1240 goto finish;
1241 }
1242 for (j = same = 0; j < i; j++)
1243 if (sg_origin[j] &&
1244 !hashcmp(sg_origin[j]->blob_sha1,
1245 porigin->blob_sha1)) {
1246 same = 1;
1247 break;
1248 }
1249 if (!same)
1250 sg_origin[i] = porigin;
1251 else
1252 origin_decref(porigin);
1253 }
1254 }
1255
1256 num_commits++;
1257 for (i = 0, sg = first_scapegoat(revs, commit);
1258 i < num_sg && sg;
1259 sg = sg->next, i++) {
1260 struct origin *porigin = sg_origin[i];
1261 if (!porigin)
1262 continue;
1263 if (!origin->previous) {
1264 origin_incref(porigin);
1265 origin->previous = porigin;
1266 }
1267 if (pass_blame_to_parent(sb, origin, porigin))
1268 goto finish;
1269 }
1270
1271 /*
1272 * Optionally find moves in parents' files.
1273 */
1274 if (opt & PICKAXE_BLAME_MOVE)
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 (find_move_in_parent(sb, origin, porigin))
1282 goto finish;
1283 }
1284
1285 /*
1286 * Optionally find copies from parents' files.
1287 */
1288 if (opt & PICKAXE_BLAME_COPY)
1289 for (i = 0, sg = first_scapegoat(revs, commit);
1290 i < num_sg && sg;
1291 sg = sg->next, i++) {
1292 struct origin *porigin = sg_origin[i];
1293 if (find_copy_in_parent(sb, origin, sg->item,
1294 porigin, opt))
1295 goto finish;
1296 }
1297
1298 finish:
1299 for (i = 0; i < num_sg; i++) {
1300 if (sg_origin[i]) {
1301 drop_origin_blob(sg_origin[i]);
1302 origin_decref(sg_origin[i]);
1303 }
1304 }
1305 drop_origin_blob(origin);
1306 if (sg_buf != sg_origin)
1307 free(sg_origin);
1308}
1309
1310/*
1311 * Information on commits, used for output.
1312 */
1313struct commit_info {
1314 const char *author;
1315 const char *author_mail;
1316 unsigned long author_time;
1317 const char *author_tz;
1318
1319 /* filled only when asked for details */
1320 const char *committer;
1321 const char *committer_mail;
1322 unsigned long committer_time;
1323 const char *committer_tz;
1324
1325 const char *summary;
1326};
1327
1328/*
1329 * Parse author/committer line in the commit object buffer
1330 */
1331static void get_ac_line(const char *inbuf, const char *what,
1332 int person_len, char *person,
1333 int mail_len, char *mail,
1334 unsigned long *time, const char **tz)
1335{
1336 int len, tzlen, maillen;
1337 char *tmp, *endp, *timepos, *mailpos;
1338
1339 tmp = strstr(inbuf, what);
1340 if (!tmp)
1341 goto error_out;
1342 tmp += strlen(what);
1343 endp = strchr(tmp, '\n');
1344 if (!endp)
1345 len = strlen(tmp);
1346 else
1347 len = endp - tmp;
1348 if (person_len <= len) {
1349 error_out:
1350 /* Ugh */
1351 *tz = "(unknown)";
1352 strcpy(person, *tz);
1353 strcpy(mail, *tz);
1354 *time = 0;
1355 return;
1356 }
1357 memcpy(person, tmp, len);
1358
1359 tmp = person;
1360 tmp += len;
1361 *tmp = 0;
1362 while (person < tmp && *tmp != ' ')
1363 tmp--;
1364 if (tmp <= person)
1365 goto error_out;
1366 *tz = tmp+1;
1367 tzlen = (person+len)-(tmp+1);
1368
1369 *tmp = 0;
1370 while (person < tmp && *tmp != ' ')
1371 tmp--;
1372 if (tmp <= person)
1373 goto error_out;
1374 *time = strtoul(tmp, NULL, 10);
1375 timepos = tmp;
1376
1377 *tmp = 0;
1378 while (person < tmp && !(*tmp == ' ' && tmp[1] == '<'))
1379 tmp--;
1380 if (tmp <= person)
1381 return;
1382 mailpos = tmp + 1;
1383 *tmp = 0;
1384 maillen = timepos - tmp;
1385 memcpy(mail, mailpos, maillen);
1386
1387 if (!mailmap.nr)
1388 return;
1389
1390 /*
1391 * mailmap expansion may make the name longer.
1392 * make room by pushing stuff down.
1393 */
1394 tmp = person + person_len - (tzlen + 1);
1395 memmove(tmp, *tz, tzlen);
1396 tmp[tzlen] = 0;
1397 *tz = tmp;
1398
1399 /*
1400 * Now, convert both name and e-mail using mailmap
1401 */
1402 if (map_user(&mailmap, mail+1, mail_len-1, person, tmp-person-1)) {
1403 /* Add a trailing '>' to email, since map_user returns plain emails
1404 Note: It already has '<', since we replace from mail+1 */
1405 mailpos = memchr(mail, '\0', mail_len);
1406 if (mailpos && mailpos-mail < mail_len - 1) {
1407 *mailpos = '>';
1408 *(mailpos+1) = '\0';
1409 }
1410 }
1411}
1412
1413static void get_commit_info(struct commit *commit,
1414 struct commit_info *ret,
1415 int detailed)
1416{
1417 int len;
1418 const char *subject;
1419 char *reencoded, *message;
1420 static char author_name[1024];
1421 static char author_mail[1024];
1422 static char committer_name[1024];
1423 static char committer_mail[1024];
1424 static char summary_buf[1024];
1425
1426 /*
1427 * We've operated without save_commit_buffer, so
1428 * we now need to populate them for output.
1429 */
1430 if (!commit->buffer) {
1431 enum object_type type;
1432 unsigned long size;
1433 commit->buffer =
1434 read_sha1_file(commit->object.sha1, &type, &size);
1435 if (!commit->buffer)
1436 die("Cannot read commit %s",
1437 sha1_to_hex(commit->object.sha1));
1438 }
1439 reencoded = reencode_commit_message(commit, NULL);
1440 message = reencoded ? reencoded : commit->buffer;
1441 ret->author = author_name;
1442 ret->author_mail = author_mail;
1443 get_ac_line(message, "\nauthor ",
1444 sizeof(author_name), author_name,
1445 sizeof(author_mail), author_mail,
1446 &ret->author_time, &ret->author_tz);
1447
1448 if (!detailed) {
1449 free(reencoded);
1450 return;
1451 }
1452
1453 ret->committer = committer_name;
1454 ret->committer_mail = committer_mail;
1455 get_ac_line(message, "\ncommitter ",
1456 sizeof(committer_name), committer_name,
1457 sizeof(committer_mail), committer_mail,
1458 &ret->committer_time, &ret->committer_tz);
1459
1460 ret->summary = summary_buf;
1461 len = find_commit_subject(message, &subject);
1462 if (len && len < sizeof(summary_buf)) {
1463 memcpy(summary_buf, subject, len);
1464 summary_buf[len] = 0;
1465 } else {
1466 sprintf(summary_buf, "(%s)", sha1_to_hex(commit->object.sha1));
1467 }
1468 free(reencoded);
1469}
1470
1471/*
1472 * To allow LF and other nonportable characters in pathnames,
1473 * they are c-style quoted as needed.
1474 */
1475static void write_filename_info(const char *path)
1476{
1477 printf("filename ");
1478 write_name_quoted(path, stdout, '\n');
1479}
1480
1481/*
1482 * Porcelain/Incremental format wants to show a lot of details per
1483 * commit. Instead of repeating this every line, emit it only once,
1484 * the first time each commit appears in the output (unless the
1485 * user has specifically asked for us to repeat).
1486 */
1487static int emit_one_suspect_detail(struct origin *suspect, int repeat)
1488{
1489 struct commit_info ci;
1490
1491 if (!repeat && (suspect->commit->object.flags & METAINFO_SHOWN))
1492 return 0;
1493
1494 suspect->commit->object.flags |= METAINFO_SHOWN;
1495 get_commit_info(suspect->commit, &ci, 1);
1496 printf("author %s\n", ci.author);
1497 printf("author-mail %s\n", ci.author_mail);
1498 printf("author-time %lu\n", ci.author_time);
1499 printf("author-tz %s\n", ci.author_tz);
1500 printf("committer %s\n", ci.committer);
1501 printf("committer-mail %s\n", ci.committer_mail);
1502 printf("committer-time %lu\n", ci.committer_time);
1503 printf("committer-tz %s\n", ci.committer_tz);
1504 printf("summary %s\n", ci.summary);
1505 if (suspect->commit->object.flags & UNINTERESTING)
1506 printf("boundary\n");
1507 if (suspect->previous) {
1508 struct origin *prev = suspect->previous;
1509 printf("previous %s ", sha1_to_hex(prev->commit->object.sha1));
1510 write_name_quoted(prev->path, stdout, '\n');
1511 }
1512 return 1;
1513}
1514
1515/*
1516 * The blame_entry is found to be guilty for the range. Mark it
1517 * as such, and show it in incremental output.
1518 */
1519static void found_guilty_entry(struct blame_entry *ent)
1520{
1521 if (ent->guilty)
1522 return;
1523 ent->guilty = 1;
1524 if (incremental) {
1525 struct origin *suspect = ent->suspect;
1526
1527 printf("%s %d %d %d\n",
1528 sha1_to_hex(suspect->commit->object.sha1),
1529 ent->s_lno + 1, ent->lno + 1, ent->num_lines);
1530 emit_one_suspect_detail(suspect, 0);
1531 write_filename_info(suspect->path);
1532 maybe_flush_or_die(stdout, "stdout");
1533 }
1534}
1535
1536/*
1537 * The main loop -- while the scoreboard has lines whose true origin
1538 * is still unknown, pick one blame_entry, and allow its current
1539 * suspect to pass blames to its parents.
1540 */
1541static void assign_blame(struct scoreboard *sb, int opt)
1542{
1543 struct rev_info *revs = sb->revs;
1544
1545 while (1) {
1546 struct blame_entry *ent;
1547 struct commit *commit;
1548 struct origin *suspect = NULL;
1549
1550 /* find one suspect to break down */
1551 for (ent = sb->ent; !suspect && ent; ent = ent->next)
1552 if (!ent->guilty)
1553 suspect = ent->suspect;
1554 if (!suspect)
1555 return; /* all done */
1556
1557 /*
1558 * We will use this suspect later in the loop,
1559 * so hold onto it in the meantime.
1560 */
1561 origin_incref(suspect);
1562 commit = suspect->commit;
1563 if (!commit->object.parsed)
1564 parse_commit(commit);
1565 if (reverse ||
1566 (!(commit->object.flags & UNINTERESTING) &&
1567 !(revs->max_age != -1 && commit->date < revs->max_age)))
1568 pass_blame(sb, suspect, opt);
1569 else {
1570 commit->object.flags |= UNINTERESTING;
1571 if (commit->object.parsed)
1572 mark_parents_uninteresting(commit);
1573 }
1574 /* treat root commit as boundary */
1575 if (!commit->parents && !show_root)
1576 commit->object.flags |= UNINTERESTING;
1577
1578 /* Take responsibility for the remaining entries */
1579 for (ent = sb->ent; ent; ent = ent->next)
1580 if (same_suspect(ent->suspect, suspect))
1581 found_guilty_entry(ent);
1582 origin_decref(suspect);
1583
1584 if (DEBUG) /* sanity */
1585 sanity_check_refcnt(sb);
1586 }
1587}
1588
1589static const char *format_time(unsigned long time, const char *tz_str,
1590 int show_raw_time)
1591{
1592 static char time_buf[128];
1593 const char *time_str;
1594 int time_len;
1595 int tz;
1596
1597 if (show_raw_time) {
1598 snprintf(time_buf, sizeof(time_buf), "%lu %s", time, tz_str);
1599 }
1600 else {
1601 tz = atoi(tz_str);
1602 time_str = show_date(time, tz, blame_date_mode);
1603 time_len = strlen(time_str);
1604 memcpy(time_buf, time_str, time_len);
1605 memset(time_buf + time_len, ' ', blame_date_width - time_len);
1606 }
1607 return time_buf;
1608}
1609
1610#define OUTPUT_ANNOTATE_COMPAT 001
1611#define OUTPUT_LONG_OBJECT_NAME 002
1612#define OUTPUT_RAW_TIMESTAMP 004
1613#define OUTPUT_PORCELAIN 010
1614#define OUTPUT_SHOW_NAME 020
1615#define OUTPUT_SHOW_NUMBER 040
1616#define OUTPUT_SHOW_SCORE 0100
1617#define OUTPUT_NO_AUTHOR 0200
1618#define OUTPUT_SHOW_EMAIL 0400
1619#define OUTPUT_LINE_PORCELAIN 01000
1620
1621static void emit_porcelain_details(struct origin *suspect, int repeat)
1622{
1623 if (emit_one_suspect_detail(suspect, repeat) ||
1624 (suspect->commit->object.flags & MORE_THAN_ONE_PATH))
1625 write_filename_info(suspect->path);
1626}
1627
1628static void emit_porcelain(struct scoreboard *sb, struct blame_entry *ent,
1629 int opt)
1630{
1631 int repeat = opt & OUTPUT_LINE_PORCELAIN;
1632 int cnt;
1633 const char *cp;
1634 struct origin *suspect = ent->suspect;
1635 char hex[41];
1636
1637 strcpy(hex, sha1_to_hex(suspect->commit->object.sha1));
1638 printf("%s%c%d %d %d\n",
1639 hex,
1640 ent->guilty ? ' ' : '*', /* purely for debugging */
1641 ent->s_lno + 1,
1642 ent->lno + 1,
1643 ent->num_lines);
1644 emit_porcelain_details(suspect, repeat);
1645
1646 cp = nth_line(sb, ent->lno);
1647 for (cnt = 0; cnt < ent->num_lines; cnt++) {
1648 char ch;
1649 if (cnt) {
1650 printf("%s %d %d\n", hex,
1651 ent->s_lno + 1 + cnt,
1652 ent->lno + 1 + cnt);
1653 if (repeat)
1654 emit_porcelain_details(suspect, 1);
1655 }
1656 putchar('\t');
1657 do {
1658 ch = *cp++;
1659 putchar(ch);
1660 } while (ch != '\n' &&
1661 cp < sb->final_buf + sb->final_buf_size);
1662 }
1663
1664 if (sb->final_buf_size && cp[-1] != '\n')
1665 putchar('\n');
1666}
1667
1668static void emit_other(struct scoreboard *sb, struct blame_entry *ent, int opt)
1669{
1670 int cnt;
1671 const char *cp;
1672 struct origin *suspect = ent->suspect;
1673 struct commit_info ci;
1674 char hex[41];
1675 int show_raw_time = !!(opt & OUTPUT_RAW_TIMESTAMP);
1676
1677 get_commit_info(suspect->commit, &ci, 1);
1678 strcpy(hex, sha1_to_hex(suspect->commit->object.sha1));
1679
1680 cp = nth_line(sb, ent->lno);
1681 for (cnt = 0; cnt < ent->num_lines; cnt++) {
1682 char ch;
1683 int length = (opt & OUTPUT_LONG_OBJECT_NAME) ? 40 : abbrev;
1684
1685 if (suspect->commit->object.flags & UNINTERESTING) {
1686 if (blank_boundary)
1687 memset(hex, ' ', length);
1688 else if (!(opt & OUTPUT_ANNOTATE_COMPAT)) {
1689 length--;
1690 putchar('^');
1691 }
1692 }
1693
1694 printf("%.*s", length, hex);
1695 if (opt & OUTPUT_ANNOTATE_COMPAT) {
1696 const char *name;
1697 if (opt & OUTPUT_SHOW_EMAIL)
1698 name = ci.author_mail;
1699 else
1700 name = ci.author;
1701 printf("\t(%10s\t%10s\t%d)", name,
1702 format_time(ci.author_time, ci.author_tz,
1703 show_raw_time),
1704 ent->lno + 1 + cnt);
1705 } else {
1706 if (opt & OUTPUT_SHOW_SCORE)
1707 printf(" %*d %02d",
1708 max_score_digits, ent->score,
1709 ent->suspect->refcnt);
1710 if (opt & OUTPUT_SHOW_NAME)
1711 printf(" %-*.*s", longest_file, longest_file,
1712 suspect->path);
1713 if (opt & OUTPUT_SHOW_NUMBER)
1714 printf(" %*d", max_orig_digits,
1715 ent->s_lno + 1 + cnt);
1716
1717 if (!(opt & OUTPUT_NO_AUTHOR)) {
1718 const char *name;
1719 int pad;
1720 if (opt & OUTPUT_SHOW_EMAIL)
1721 name = ci.author_mail;
1722 else
1723 name = ci.author;
1724 pad = longest_author - utf8_strwidth(name);
1725 printf(" (%s%*s %10s",
1726 name, pad, "",
1727 format_time(ci.author_time,
1728 ci.author_tz,
1729 show_raw_time));
1730 }
1731 printf(" %*d) ",
1732 max_digits, ent->lno + 1 + cnt);
1733 }
1734 do {
1735 ch = *cp++;
1736 putchar(ch);
1737 } while (ch != '\n' &&
1738 cp < sb->final_buf + sb->final_buf_size);
1739 }
1740
1741 if (sb->final_buf_size && cp[-1] != '\n')
1742 putchar('\n');
1743}
1744
1745static void output(struct scoreboard *sb, int option)
1746{
1747 struct blame_entry *ent;
1748
1749 if (option & OUTPUT_PORCELAIN) {
1750 for (ent = sb->ent; ent; ent = ent->next) {
1751 struct blame_entry *oth;
1752 struct origin *suspect = ent->suspect;
1753 struct commit *commit = suspect->commit;
1754 if (commit->object.flags & MORE_THAN_ONE_PATH)
1755 continue;
1756 for (oth = ent->next; oth; oth = oth->next) {
1757 if ((oth->suspect->commit != commit) ||
1758 !strcmp(oth->suspect->path, suspect->path))
1759 continue;
1760 commit->object.flags |= MORE_THAN_ONE_PATH;
1761 break;
1762 }
1763 }
1764 }
1765
1766 for (ent = sb->ent; ent; ent = ent->next) {
1767 if (option & OUTPUT_PORCELAIN)
1768 emit_porcelain(sb, ent, option);
1769 else {
1770 emit_other(sb, ent, option);
1771 }
1772 }
1773}
1774
1775/*
1776 * To allow quick access to the contents of nth line in the
1777 * final image, prepare an index in the scoreboard.
1778 */
1779static int prepare_lines(struct scoreboard *sb)
1780{
1781 const char *buf = sb->final_buf;
1782 unsigned long len = sb->final_buf_size;
1783 int num = 0, incomplete = 0, bol = 1;
1784
1785 if (len && buf[len-1] != '\n')
1786 incomplete++; /* incomplete line at the end */
1787 while (len--) {
1788 if (bol) {
1789 sb->lineno = xrealloc(sb->lineno,
1790 sizeof(int *) * (num + 1));
1791 sb->lineno[num] = buf - sb->final_buf;
1792 bol = 0;
1793 }
1794 if (*buf++ == '\n') {
1795 num++;
1796 bol = 1;
1797 }
1798 }
1799 sb->lineno = xrealloc(sb->lineno,
1800 sizeof(int *) * (num + incomplete + 1));
1801 sb->lineno[num + incomplete] = buf - sb->final_buf;
1802 sb->num_lines = num + incomplete;
1803 return sb->num_lines;
1804}
1805
1806/*
1807 * Add phony grafts for use with -S; this is primarily to
1808 * support git's cvsserver that wants to give a linear history
1809 * to its clients.
1810 */
1811static int read_ancestry(const char *graft_file)
1812{
1813 FILE *fp = fopen(graft_file, "r");
1814 char buf[1024];
1815 if (!fp)
1816 return -1;
1817 while (fgets(buf, sizeof(buf), fp)) {
1818 /* The format is just "Commit Parent1 Parent2 ...\n" */
1819 int len = strlen(buf);
1820 struct commit_graft *graft = read_graft_line(buf, len);
1821 if (graft)
1822 register_commit_graft(graft, 0);
1823 }
1824 fclose(fp);
1825 return 0;
1826}
1827
1828/*
1829 * How many columns do we need to show line numbers in decimal?
1830 */
1831static int lineno_width(int lines)
1832{
1833 int i, width;
1834
1835 for (width = 1, i = 10; i <= lines; width++)
1836 i *= 10;
1837 return width;
1838}
1839
1840/*
1841 * How many columns do we need to show line numbers, authors,
1842 * and filenames?
1843 */
1844static void find_alignment(struct scoreboard *sb, int *option)
1845{
1846 int longest_src_lines = 0;
1847 int longest_dst_lines = 0;
1848 unsigned largest_score = 0;
1849 struct blame_entry *e;
1850
1851 for (e = sb->ent; e; e = e->next) {
1852 struct origin *suspect = e->suspect;
1853 struct commit_info ci;
1854 int num;
1855
1856 if (strcmp(suspect->path, sb->path))
1857 *option |= OUTPUT_SHOW_NAME;
1858 num = strlen(suspect->path);
1859 if (longest_file < num)
1860 longest_file = num;
1861 if (!(suspect->commit->object.flags & METAINFO_SHOWN)) {
1862 suspect->commit->object.flags |= METAINFO_SHOWN;
1863 get_commit_info(suspect->commit, &ci, 1);
1864 if (*option & OUTPUT_SHOW_EMAIL)
1865 num = utf8_strwidth(ci.author_mail);
1866 else
1867 num = utf8_strwidth(ci.author);
1868 if (longest_author < num)
1869 longest_author = num;
1870 }
1871 num = e->s_lno + e->num_lines;
1872 if (longest_src_lines < num)
1873 longest_src_lines = num;
1874 num = e->lno + e->num_lines;
1875 if (longest_dst_lines < num)
1876 longest_dst_lines = num;
1877 if (largest_score < ent_score(sb, e))
1878 largest_score = ent_score(sb, e);
1879 }
1880 max_orig_digits = lineno_width(longest_src_lines);
1881 max_digits = lineno_width(longest_dst_lines);
1882 max_score_digits = lineno_width(largest_score);
1883}
1884
1885/*
1886 * For debugging -- origin is refcounted, and this asserts that
1887 * we do not underflow.
1888 */
1889static void sanity_check_refcnt(struct scoreboard *sb)
1890{
1891 int baa = 0;
1892 struct blame_entry *ent;
1893
1894 for (ent = sb->ent; ent; ent = ent->next) {
1895 /* Nobody should have zero or negative refcnt */
1896 if (ent->suspect->refcnt <= 0) {
1897 fprintf(stderr, "%s in %s has negative refcnt %d\n",
1898 ent->suspect->path,
1899 sha1_to_hex(ent->suspect->commit->object.sha1),
1900 ent->suspect->refcnt);
1901 baa = 1;
1902 }
1903 }
1904 if (baa) {
1905 int opt = 0160;
1906 find_alignment(sb, &opt);
1907 output(sb, opt);
1908 die("Baa %d!", baa);
1909 }
1910}
1911
1912/*
1913 * Used for the command line parsing; check if the path exists
1914 * in the working tree.
1915 */
1916static int has_string_in_work_tree(const char *path)
1917{
1918 struct stat st;
1919 return !lstat(path, &st);
1920}
1921
1922static unsigned parse_score(const char *arg)
1923{
1924 char *end;
1925 unsigned long score = strtoul(arg, &end, 10);
1926 if (*end)
1927 return 0;
1928 return score;
1929}
1930
1931static const char *add_prefix(const char *prefix, const char *path)
1932{
1933 return prefix_path(prefix, prefix ? strlen(prefix) : 0, path);
1934}
1935
1936/*
1937 * Parsing of (comma separated) one item in the -L option
1938 */
1939static const char *parse_loc(const char *spec,
1940 struct scoreboard *sb, long lno,
1941 long begin, long *ret)
1942{
1943 char *term;
1944 const char *line;
1945 long num;
1946 int reg_error;
1947 regex_t regexp;
1948 regmatch_t match[1];
1949
1950 /* Allow "-L <something>,+20" to mean starting at <something>
1951 * for 20 lines, or "-L <something>,-5" for 5 lines ending at
1952 * <something>.
1953 */
1954 if (1 < begin && (spec[0] == '+' || spec[0] == '-')) {
1955 num = strtol(spec + 1, &term, 10);
1956 if (term != spec + 1) {
1957 if (spec[0] == '-')
1958 num = 0 - num;
1959 if (0 < num)
1960 *ret = begin + num - 2;
1961 else if (!num)
1962 *ret = begin;
1963 else
1964 *ret = begin + num;
1965 return term;
1966 }
1967 return spec;
1968 }
1969 num = strtol(spec, &term, 10);
1970 if (term != spec) {
1971 *ret = num;
1972 return term;
1973 }
1974 if (spec[0] != '/')
1975 return spec;
1976
1977 /* it could be a regexp of form /.../ */
1978 for (term = (char *) spec + 1; *term && *term != '/'; term++) {
1979 if (*term == '\\')
1980 term++;
1981 }
1982 if (*term != '/')
1983 return spec;
1984
1985 /* try [spec+1 .. term-1] as regexp */
1986 *term = 0;
1987 begin--; /* input is in human terms */
1988 line = nth_line(sb, begin);
1989
1990 if (!(reg_error = regcomp(®exp, spec + 1, REG_NEWLINE)) &&
1991 !(reg_error = regexec(®exp, line, 1, match, 0))) {
1992 const char *cp = line + match[0].rm_so;
1993 const char *nline;
1994
1995 while (begin++ < lno) {
1996 nline = nth_line(sb, begin);
1997 if (line <= cp && cp < nline)
1998 break;
1999 line = nline;
2000 }
2001 *ret = begin;
2002 regfree(®exp);
2003 *term++ = '/';
2004 return term;
2005 }
2006 else {
2007 char errbuf[1024];
2008 regerror(reg_error, ®exp, errbuf, 1024);
2009 die("-L parameter '%s': %s", spec + 1, errbuf);
2010 }
2011}
2012
2013/*
2014 * Parsing of -L option
2015 */
2016static void prepare_blame_range(struct scoreboard *sb,
2017 const char *bottomtop,
2018 long lno,
2019 long *bottom, long *top)
2020{
2021 const char *term;
2022
2023 term = parse_loc(bottomtop, sb, lno, 1, bottom);
2024 if (*term == ',') {
2025 term = parse_loc(term + 1, sb, lno, *bottom + 1, top);
2026 if (*term)
2027 usage(blame_usage);
2028 }
2029 if (*term)
2030 usage(blame_usage);
2031}
2032
2033static int git_blame_config(const char *var, const char *value, void *cb)
2034{
2035 if (!strcmp(var, "blame.showroot")) {
2036 show_root = git_config_bool(var, value);
2037 return 0;
2038 }
2039 if (!strcmp(var, "blame.blankboundary")) {
2040 blank_boundary = git_config_bool(var, value);
2041 return 0;
2042 }
2043 if (!strcmp(var, "blame.date")) {
2044 if (!value)
2045 return config_error_nonbool(var);
2046 blame_date_mode = parse_date_format(value);
2047 return 0;
2048 }
2049
2050 switch (userdiff_config(var, value)) {
2051 case 0:
2052 break;
2053 case -1:
2054 return -1;
2055 default:
2056 return 0;
2057 }
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_STRING('S', NULL, &revs_file, "file", "Use revisions from <file> instead of calling git-rev-list"),
2321 OPT_STRING(0, "contents", &contents_from, "file", "Use <file>'s contents as the final image"),
2322 { OPTION_CALLBACK, 'C', NULL, &opt, "score", "Find line copies within and across files", PARSE_OPT_OPTARG, blame_copy_callback },
2323 { OPTION_CALLBACK, 'M', NULL, &opt, "score", "Find line movements within and across files", PARSE_OPT_OPTARG, blame_move_callback },
2324 OPT_CALLBACK('L', NULL, &bottomtop, "n,m", "Process only line range n,m, counting from 1", blame_bottomtop_callback),
2325 OPT__ABBREV(&abbrev),
2326 OPT_END()
2327 };
2328
2329 struct parse_opt_ctx_t ctx;
2330 int cmd_is_annotate = !strcmp(argv[0], "annotate");
2331
2332 git_config(git_blame_config, NULL);
2333 init_revisions(&revs, NULL);
2334 revs.date_mode = blame_date_mode;
2335 DIFF_OPT_SET(&revs.diffopt, ALLOW_TEXTCONV);
2336
2337 save_commit_buffer = 0;
2338 dashdash_pos = 0;
2339
2340 parse_options_start(&ctx, argc, argv, prefix, options,
2341 PARSE_OPT_KEEP_DASHDASH | PARSE_OPT_KEEP_ARGV0);
2342 for (;;) {
2343 switch (parse_options_step(&ctx, options, blame_opt_usage)) {
2344 case PARSE_OPT_HELP:
2345 exit(129);
2346 case PARSE_OPT_DONE:
2347 if (ctx.argv[0])
2348 dashdash_pos = ctx.cpidx;
2349 goto parse_done;
2350 }
2351
2352 if (!strcmp(ctx.argv[0], "--reverse")) {
2353 ctx.argv[0] = "--children";
2354 reverse = 1;
2355 }
2356 parse_revision_opt(&revs, &ctx, options, blame_opt_usage);
2357 }
2358parse_done:
2359 argc = parse_options_end(&ctx);
2360
2361 if (abbrev == -1)
2362 abbrev = default_abbrev;
2363 /* one more abbrev length is needed for the boundary commit */
2364 abbrev++;
2365
2366 if (revs_file && read_ancestry(revs_file))
2367 die_errno("reading graft file '%s' failed", revs_file);
2368
2369 if (cmd_is_annotate) {
2370 output_option |= OUTPUT_ANNOTATE_COMPAT;
2371 blame_date_mode = DATE_ISO8601;
2372 } else {
2373 blame_date_mode = revs.date_mode;
2374 }
2375
2376 /* The maximum width used to show the dates */
2377 switch (blame_date_mode) {
2378 case DATE_RFC2822:
2379 blame_date_width = sizeof("Thu, 19 Oct 2006 16:00:04 -0700");
2380 break;
2381 case DATE_ISO8601:
2382 blame_date_width = sizeof("2006-10-19 16:00:04 -0700");
2383 break;
2384 case DATE_RAW:
2385 blame_date_width = sizeof("1161298804 -0700");
2386 break;
2387 case DATE_SHORT:
2388 blame_date_width = sizeof("2006-10-19");
2389 break;
2390 case DATE_RELATIVE:
2391 /* "normal" is used as the fallback for "relative" */
2392 case DATE_LOCAL:
2393 case DATE_NORMAL:
2394 blame_date_width = sizeof("Thu Oct 19 16:00:04 2006 -0700");
2395 break;
2396 }
2397 blame_date_width -= 1; /* strip the null */
2398
2399 if (DIFF_OPT_TST(&revs.diffopt, FIND_COPIES_HARDER))
2400 opt |= (PICKAXE_BLAME_COPY | PICKAXE_BLAME_MOVE |
2401 PICKAXE_BLAME_COPY_HARDER);
2402
2403 if (!blame_move_score)
2404 blame_move_score = BLAME_DEFAULT_MOVE_SCORE;
2405 if (!blame_copy_score)
2406 blame_copy_score = BLAME_DEFAULT_COPY_SCORE;
2407
2408 /*
2409 * We have collected options unknown to us in argv[1..unk]
2410 * which are to be passed to revision machinery if we are
2411 * going to do the "bottom" processing.
2412 *
2413 * The remaining are:
2414 *
2415 * (1) if dashdash_pos != 0, it is either
2416 * "blame [revisions] -- <path>" or
2417 * "blame -- <path> <rev>"
2418 *
2419 * (2) otherwise, it is one of the two:
2420 * "blame [revisions] <path>"
2421 * "blame <path> <rev>"
2422 *
2423 * Note that we must strip out <path> from the arguments: we do not
2424 * want the path pruning but we may want "bottom" processing.
2425 */
2426 if (dashdash_pos) {
2427 switch (argc - dashdash_pos - 1) {
2428 case 2: /* (1b) */
2429 if (argc != 4)
2430 usage_with_options(blame_opt_usage, options);
2431 /* reorder for the new way: <rev> -- <path> */
2432 argv[1] = argv[3];
2433 argv[3] = argv[2];
2434 argv[2] = "--";
2435 /* FALLTHROUGH */
2436 case 1: /* (1a) */
2437 path = add_prefix(prefix, argv[--argc]);
2438 argv[argc] = NULL;
2439 break;
2440 default:
2441 usage_with_options(blame_opt_usage, options);
2442 }
2443 } else {
2444 if (argc < 2)
2445 usage_with_options(blame_opt_usage, options);
2446 path = add_prefix(prefix, argv[argc - 1]);
2447 if (argc == 3 && !has_string_in_work_tree(path)) { /* (2b) */
2448 path = add_prefix(prefix, argv[1]);
2449 argv[1] = argv[2];
2450 }
2451 argv[argc - 1] = "--";
2452
2453 setup_work_tree();
2454 if (!has_string_in_work_tree(path))
2455 die_errno("cannot stat path '%s'", path);
2456 }
2457
2458 revs.disable_stdin = 1;
2459 setup_revisions(argc, argv, &revs, NULL);
2460 memset(&sb, 0, sizeof(sb));
2461
2462 sb.revs = &revs;
2463 if (!reverse)
2464 final_commit_name = prepare_final(&sb);
2465 else if (contents_from)
2466 die("--contents and --children do not blend well.");
2467 else
2468 final_commit_name = prepare_initial(&sb);
2469
2470 if (!sb.final) {
2471 /*
2472 * "--not A B -- path" without anything positive;
2473 * do not default to HEAD, but use the working tree
2474 * or "--contents".
2475 */
2476 setup_work_tree();
2477 sb.final = fake_working_tree_commit(&sb.revs->diffopt,
2478 path, contents_from);
2479 add_pending_object(&revs, &(sb.final->object), ":");
2480 }
2481 else if (contents_from)
2482 die("Cannot use --contents with final commit object name");
2483
2484 /*
2485 * If we have bottom, this will mark the ancestors of the
2486 * bottom commits we would reach while traversing as
2487 * uninteresting.
2488 */
2489 if (prepare_revision_walk(&revs))
2490 die("revision walk setup failed");
2491
2492 if (is_null_sha1(sb.final->object.sha1)) {
2493 char *buf;
2494 o = sb.final->util;
2495 buf = xmalloc(o->file.size + 1);
2496 memcpy(buf, o->file.ptr, o->file.size + 1);
2497 sb.final_buf = buf;
2498 sb.final_buf_size = o->file.size;
2499 }
2500 else {
2501 o = get_origin(&sb, sb.final, path);
2502 if (fill_blob_sha1_and_mode(o))
2503 die("no such path %s in %s", path, final_commit_name);
2504
2505 if (DIFF_OPT_TST(&sb.revs->diffopt, ALLOW_TEXTCONV) &&
2506 textconv_object(path, o->mode, o->blob_sha1, (char **) &sb.final_buf,
2507 &sb.final_buf_size))
2508 ;
2509 else
2510 sb.final_buf = read_sha1_file(o->blob_sha1, &type,
2511 &sb.final_buf_size);
2512
2513 if (!sb.final_buf)
2514 die("Cannot read blob %s for path %s",
2515 sha1_to_hex(o->blob_sha1),
2516 path);
2517 }
2518 num_read_blob++;
2519 lno = prepare_lines(&sb);
2520
2521 bottom = top = 0;
2522 if (bottomtop)
2523 prepare_blame_range(&sb, bottomtop, lno, &bottom, &top);
2524 if (bottom && top && top < bottom) {
2525 long tmp;
2526 tmp = top; top = bottom; bottom = tmp;
2527 }
2528 if (bottom < 1)
2529 bottom = 1;
2530 if (top < 1)
2531 top = lno;
2532 bottom--;
2533 if (lno < top || lno < bottom)
2534 die("file %s has only %lu lines", path, lno);
2535
2536 ent = xcalloc(1, sizeof(*ent));
2537 ent->lno = bottom;
2538 ent->num_lines = top - bottom;
2539 ent->suspect = o;
2540 ent->s_lno = bottom;
2541
2542 sb.ent = ent;
2543 sb.path = path;
2544
2545 read_mailmap(&mailmap, NULL);
2546
2547 if (!incremental)
2548 setup_pager();
2549
2550 assign_blame(&sb, opt);
2551
2552 if (incremental)
2553 return 0;
2554
2555 coalesce(&sb);
2556
2557 if (!(output_option & OUTPUT_PORCELAIN))
2558 find_alignment(&sb, &output_option);
2559
2560 output(&sb, output_option);
2561 free((void *)sb.final_buf);
2562 for (ent = sb.ent; ent; ) {
2563 struct blame_entry *e = ent->next;
2564 free(ent);
2565 ent = e;
2566 }
2567
2568 if (show_stats) {
2569 printf("num read blob: %d\n", num_read_blob);
2570 printf("num get patch: %d\n", num_get_patch);
2571 printf("num commits: %d\n", num_commits);
2572 }
2573 return 0;
2574}