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