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