]> git.ipfire.org Git - thirdparty/git.git/blob - builtin-blame.c
blame: -b (blame.blankboundary) and --root (blame.showroot)
[thirdparty/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 "xdiff-interface.h"
17
18 #include <time.h>
19 #include <sys/time.h>
20 #include <regex.h>
21
22 static char blame_usage[] =
23 "git-blame [-c] [-l] [-t] [-f] [-n] [-p] [-L n,m] [-S <revs-file>] [-M] [-C] [-C] [commit] [--] file\n"
24 " -c, --compatibility 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, --long Show long commit SHA1 (Default: off)\n"
27 " --root Do not treat root commits as boundaries (Default: off)\n"
28 " -t, --time Show raw timestamp (Default: off)\n"
29 " -f, --show-name Show original filename (Default: auto)\n"
30 " -n, --show-number Show original linenumber (Default: off)\n"
31 " -p, --porcelain Show in a format designed for machine consumption\n"
32 " -L n,m Process only line range n,m, counting from 1\n"
33 " -M, -C Find line movements within and across files\n"
34 " -S revs-file Use revisions from revs-file instead of calling git-rev-list\n";
35
36 static int longest_file;
37 static int longest_author;
38 static int max_orig_digits;
39 static int max_digits;
40 static int max_score_digits;
41 static int show_root;
42 static int blank_boundary;
43
44 #ifndef DEBUG
45 #define DEBUG 0
46 #endif
47
48 /* stats */
49 static int num_read_blob;
50 static int num_get_patch;
51 static int num_commits;
52
53 #define PICKAXE_BLAME_MOVE 01
54 #define PICKAXE_BLAME_COPY 02
55 #define PICKAXE_BLAME_COPY_HARDER 04
56
57 /*
58 * blame for a blame_entry with score lower than these thresholds
59 * is not passed to the parent using move/copy logic.
60 */
61 static unsigned blame_move_score;
62 static unsigned blame_copy_score;
63 #define BLAME_DEFAULT_MOVE_SCORE 20
64 #define BLAME_DEFAULT_COPY_SCORE 40
65
66 /* bits #0..7 in revision.h, #8..11 used for merge_bases() in commit.c */
67 #define METAINFO_SHOWN (1u<<12)
68 #define MORE_THAN_ONE_PATH (1u<<13)
69
70 /*
71 * One blob in a commit that is being suspected
72 */
73 struct origin {
74 int refcnt;
75 struct commit *commit;
76 mmfile_t file;
77 unsigned char blob_sha1[20];
78 char path[FLEX_ARRAY];
79 };
80
81 static char *fill_origin_blob(struct origin *o, mmfile_t *file)
82 {
83 if (!o->file.ptr) {
84 char type[10];
85 num_read_blob++;
86 file->ptr = read_sha1_file(o->blob_sha1, type,
87 (unsigned long *)(&(file->size)));
88 o->file = *file;
89 }
90 else
91 *file = o->file;
92 return file->ptr;
93 }
94
95 static inline struct origin *origin_incref(struct origin *o)
96 {
97 if (o)
98 o->refcnt++;
99 return o;
100 }
101
102 static void origin_decref(struct origin *o)
103 {
104 if (o && --o->refcnt <= 0) {
105 if (o->file.ptr)
106 free(o->file.ptr);
107 memset(o, 0, sizeof(*o));
108 free(o);
109 }
110 }
111
112 struct blame_entry {
113 struct blame_entry *prev;
114 struct blame_entry *next;
115
116 /* the first line of this group in the final image;
117 * internally all line numbers are 0 based.
118 */
119 int lno;
120
121 /* how many lines this group has */
122 int num_lines;
123
124 /* the commit that introduced this group into the final image */
125 struct origin *suspect;
126
127 /* true if the suspect is truly guilty; false while we have not
128 * checked if the group came from one of its parents.
129 */
130 char guilty;
131
132 /* the line number of the first line of this group in the
133 * suspect's file; internally all line numbers are 0 based.
134 */
135 int s_lno;
136
137 /* how significant this entry is -- cached to avoid
138 * scanning the lines over and over
139 */
140 unsigned score;
141 };
142
143 struct scoreboard {
144 /* the final commit (i.e. where we started digging from) */
145 struct commit *final;
146
147 const char *path;
148
149 /* the contents in the final; pointed into by buf pointers of
150 * blame_entries
151 */
152 const char *final_buf;
153 unsigned long final_buf_size;
154
155 /* linked list of blames */
156 struct blame_entry *ent;
157
158 /* look-up a line in the final buffer */
159 int num_lines;
160 int *lineno;
161 };
162
163 static int cmp_suspect(struct origin *a, struct origin *b)
164 {
165 int cmp = hashcmp(a->commit->object.sha1, b->commit->object.sha1);
166 if (cmp)
167 return cmp;
168 return strcmp(a->path, b->path);
169 }
170
171 #define cmp_suspect(a, b) ( ((a)==(b)) ? 0 : cmp_suspect(a,b) )
172
173 static void sanity_check_refcnt(struct scoreboard *);
174
175 static void coalesce(struct scoreboard *sb)
176 {
177 struct blame_entry *ent, *next;
178
179 for (ent = sb->ent; ent && (next = ent->next); ent = next) {
180 if (!cmp_suspect(ent->suspect, next->suspect) &&
181 ent->guilty == next->guilty &&
182 ent->s_lno + ent->num_lines == next->s_lno) {
183 ent->num_lines += next->num_lines;
184 ent->next = next->next;
185 if (ent->next)
186 ent->next->prev = ent;
187 origin_decref(next->suspect);
188 free(next);
189 ent->score = 0;
190 next = ent; /* again */
191 }
192 }
193
194 if (DEBUG) /* sanity */
195 sanity_check_refcnt(sb);
196 }
197
198 static struct origin *make_origin(struct commit *commit, const char *path)
199 {
200 struct origin *o;
201 o = xcalloc(1, sizeof(*o) + strlen(path) + 1);
202 o->commit = commit;
203 o->refcnt = 1;
204 strcpy(o->path, path);
205 return o;
206 }
207
208 static struct origin *get_origin(struct scoreboard *sb,
209 struct commit *commit,
210 const char *path)
211 {
212 struct blame_entry *e;
213
214 for (e = sb->ent; e; e = e->next) {
215 if (e->suspect->commit == commit &&
216 !strcmp(e->suspect->path, path))
217 return origin_incref(e->suspect);
218 }
219 return make_origin(commit, path);
220 }
221
222 static int fill_blob_sha1(struct origin *origin)
223 {
224 unsigned mode;
225 char type[10];
226
227 if (!is_null_sha1(origin->blob_sha1))
228 return 0;
229 if (get_tree_entry(origin->commit->object.sha1,
230 origin->path,
231 origin->blob_sha1, &mode))
232 goto error_out;
233 if (sha1_object_info(origin->blob_sha1, type, NULL) ||
234 strcmp(type, blob_type))
235 goto error_out;
236 return 0;
237 error_out:
238 hashclr(origin->blob_sha1);
239 return -1;
240 }
241
242 static struct origin *find_origin(struct scoreboard *sb,
243 struct commit *parent,
244 struct origin *origin)
245 {
246 struct origin *porigin = NULL;
247 struct diff_options diff_opts;
248 const char *paths[2];
249
250 if (parent->util) {
251 /* This is a freestanding copy of origin and not
252 * refcounted.
253 */
254 struct origin *cached = parent->util;
255 if (!strcmp(cached->path, origin->path)) {
256 porigin = get_origin(sb, parent, cached->path);
257 if (porigin->refcnt == 1)
258 hashcpy(porigin->blob_sha1, cached->blob_sha1);
259 return porigin;
260 }
261 /* otherwise it was not very useful; free it */
262 free(parent->util);
263 parent->util = NULL;
264 }
265
266 /* See if the origin->path is different between parent
267 * and origin first. Most of the time they are the
268 * same and diff-tree is fairly efficient about this.
269 */
270 diff_setup(&diff_opts);
271 diff_opts.recursive = 1;
272 diff_opts.detect_rename = 0;
273 diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;
274 paths[0] = origin->path;
275 paths[1] = NULL;
276
277 diff_tree_setup_paths(paths, &diff_opts);
278 if (diff_setup_done(&diff_opts) < 0)
279 die("diff-setup");
280 diff_tree_sha1(parent->tree->object.sha1,
281 origin->commit->tree->object.sha1,
282 "", &diff_opts);
283 diffcore_std(&diff_opts);
284
285 /* It is either one entry that says "modified", or "created",
286 * or nothing.
287 */
288 if (!diff_queued_diff.nr) {
289 /* The path is the same as parent */
290 porigin = get_origin(sb, parent, origin->path);
291 hashcpy(porigin->blob_sha1, origin->blob_sha1);
292 }
293 else if (diff_queued_diff.nr != 1)
294 die("internal error in blame::find_origin");
295 else {
296 struct diff_filepair *p = diff_queued_diff.queue[0];
297 switch (p->status) {
298 default:
299 die("internal error in blame::find_origin (%c)",
300 p->status);
301 case 'M':
302 porigin = get_origin(sb, parent, origin->path);
303 hashcpy(porigin->blob_sha1, p->one->sha1);
304 break;
305 case 'A':
306 case 'T':
307 /* Did not exist in parent, or type changed */
308 break;
309 }
310 }
311 diff_flush(&diff_opts);
312 if (porigin) {
313 struct origin *cached;
314 cached = make_origin(porigin->commit, porigin->path);
315 hashcpy(cached->blob_sha1, porigin->blob_sha1);
316 parent->util = cached;
317 }
318 return porigin;
319 }
320
321 static struct origin *find_rename(struct scoreboard *sb,
322 struct commit *parent,
323 struct origin *origin)
324 {
325 struct origin *porigin = NULL;
326 struct diff_options diff_opts;
327 int i;
328 const char *paths[2];
329
330 diff_setup(&diff_opts);
331 diff_opts.recursive = 1;
332 diff_opts.detect_rename = DIFF_DETECT_RENAME;
333 diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;
334 diff_opts.single_follow = origin->path;
335 paths[0] = NULL;
336 diff_tree_setup_paths(paths, &diff_opts);
337 if (diff_setup_done(&diff_opts) < 0)
338 die("diff-setup");
339 diff_tree_sha1(parent->tree->object.sha1,
340 origin->commit->tree->object.sha1,
341 "", &diff_opts);
342 diffcore_std(&diff_opts);
343
344 for (i = 0; i < diff_queued_diff.nr; i++) {
345 struct diff_filepair *p = diff_queued_diff.queue[i];
346 if ((p->status == 'R' || p->status == 'C') &&
347 !strcmp(p->two->path, origin->path)) {
348 porigin = get_origin(sb, parent, p->one->path);
349 hashcpy(porigin->blob_sha1, p->one->sha1);
350 break;
351 }
352 }
353 diff_flush(&diff_opts);
354 return porigin;
355 }
356
357 struct chunk {
358 /* line number in postimage; up to but not including this
359 * line is the same as preimage
360 */
361 int same;
362
363 /* preimage line number after this chunk */
364 int p_next;
365
366 /* postimage line number after this chunk */
367 int t_next;
368 };
369
370 struct patch {
371 struct chunk *chunks;
372 int num;
373 };
374
375 struct blame_diff_state {
376 struct xdiff_emit_state xm;
377 struct patch *ret;
378 unsigned hunk_post_context;
379 unsigned hunk_in_pre_context : 1;
380 };
381
382 static void process_u_diff(void *state_, char *line, unsigned long len)
383 {
384 struct blame_diff_state *state = state_;
385 struct chunk *chunk;
386 int off1, off2, len1, len2, num;
387
388 num = state->ret->num;
389 if (len < 4 || line[0] != '@' || line[1] != '@') {
390 if (state->hunk_in_pre_context && line[0] == ' ')
391 state->ret->chunks[num - 1].same++;
392 else {
393 state->hunk_in_pre_context = 0;
394 if (line[0] == ' ')
395 state->hunk_post_context++;
396 else
397 state->hunk_post_context = 0;
398 }
399 return;
400 }
401
402 if (num && state->hunk_post_context) {
403 chunk = &state->ret->chunks[num - 1];
404 chunk->p_next -= state->hunk_post_context;
405 chunk->t_next -= state->hunk_post_context;
406 }
407 state->ret->num = ++num;
408 state->ret->chunks = xrealloc(state->ret->chunks,
409 sizeof(struct chunk) * num);
410 chunk = &state->ret->chunks[num - 1];
411 if (parse_hunk_header(line, len, &off1, &len1, &off2, &len2)) {
412 state->ret->num--;
413 return;
414 }
415
416 /* Line numbers in patch output are one based. */
417 off1--;
418 off2--;
419
420 chunk->same = len2 ? off2 : (off2 + 1);
421
422 chunk->p_next = off1 + (len1 ? len1 : 1);
423 chunk->t_next = chunk->same + len2;
424 state->hunk_in_pre_context = 1;
425 state->hunk_post_context = 0;
426 }
427
428 static struct patch *compare_buffer(mmfile_t *file_p, mmfile_t *file_o,
429 int context)
430 {
431 struct blame_diff_state state;
432 xpparam_t xpp;
433 xdemitconf_t xecfg;
434 xdemitcb_t ecb;
435
436 xpp.flags = XDF_NEED_MINIMAL;
437 xecfg.ctxlen = context;
438 xecfg.flags = 0;
439 ecb.outf = xdiff_outf;
440 ecb.priv = &state;
441 memset(&state, 0, sizeof(state));
442 state.xm.consume = process_u_diff;
443 state.ret = xmalloc(sizeof(struct patch));
444 state.ret->chunks = NULL;
445 state.ret->num = 0;
446
447 xdl_diff(file_p, file_o, &xpp, &xecfg, &ecb);
448
449 if (state.ret->num) {
450 struct chunk *chunk;
451 chunk = &state.ret->chunks[state.ret->num - 1];
452 chunk->p_next -= state.hunk_post_context;
453 chunk->t_next -= state.hunk_post_context;
454 }
455 return state.ret;
456 }
457
458 static struct patch *get_patch(struct origin *parent, struct origin *origin)
459 {
460 mmfile_t file_p, file_o;
461 struct patch *patch;
462
463 fill_origin_blob(parent, &file_p);
464 fill_origin_blob(origin, &file_o);
465 if (!file_p.ptr || !file_o.ptr)
466 return NULL;
467 patch = compare_buffer(&file_p, &file_o, 0);
468 num_get_patch++;
469 return patch;
470 }
471
472 static void free_patch(struct patch *p)
473 {
474 free(p->chunks);
475 free(p);
476 }
477
478 static void add_blame_entry(struct scoreboard *sb, struct blame_entry *e)
479 {
480 struct blame_entry *ent, *prev = NULL;
481
482 origin_incref(e->suspect);
483
484 for (ent = sb->ent; ent && ent->lno < e->lno; ent = ent->next)
485 prev = ent;
486
487 /* prev, if not NULL, is the last one that is below e */
488 e->prev = prev;
489 if (prev) {
490 e->next = prev->next;
491 prev->next = e;
492 }
493 else {
494 e->next = sb->ent;
495 sb->ent = e;
496 }
497 if (e->next)
498 e->next->prev = e;
499 }
500
501 static void dup_entry(struct blame_entry *dst, struct blame_entry *src)
502 {
503 struct blame_entry *p, *n;
504
505 p = dst->prev;
506 n = dst->next;
507 origin_incref(src->suspect);
508 origin_decref(dst->suspect);
509 memcpy(dst, src, sizeof(*src));
510 dst->prev = p;
511 dst->next = n;
512 dst->score = 0;
513 }
514
515 static const char *nth_line(struct scoreboard *sb, int lno)
516 {
517 return sb->final_buf + sb->lineno[lno];
518 }
519
520 static void split_overlap(struct blame_entry *split,
521 struct blame_entry *e,
522 int tlno, int plno, int same,
523 struct origin *parent)
524 {
525 /* it is known that lines between tlno to same came from
526 * parent, and e has an overlap with that range. it also is
527 * known that parent's line plno corresponds to e's line tlno.
528 *
529 * <---- e ----->
530 * <------>
531 * <------------>
532 * <------------>
533 * <------------------>
534 *
535 * Potentially we need to split e into three parts; before
536 * this chunk, the chunk to be blamed for parent, and after
537 * that portion.
538 */
539 int chunk_end_lno;
540 memset(split, 0, sizeof(struct blame_entry [3]));
541
542 if (e->s_lno < tlno) {
543 /* there is a pre-chunk part not blamed on parent */
544 split[0].suspect = origin_incref(e->suspect);
545 split[0].lno = e->lno;
546 split[0].s_lno = e->s_lno;
547 split[0].num_lines = tlno - e->s_lno;
548 split[1].lno = e->lno + tlno - e->s_lno;
549 split[1].s_lno = plno;
550 }
551 else {
552 split[1].lno = e->lno;
553 split[1].s_lno = plno + (e->s_lno - tlno);
554 }
555
556 if (same < e->s_lno + e->num_lines) {
557 /* there is a post-chunk part not blamed on parent */
558 split[2].suspect = origin_incref(e->suspect);
559 split[2].lno = e->lno + (same - e->s_lno);
560 split[2].s_lno = e->s_lno + (same - e->s_lno);
561 split[2].num_lines = e->s_lno + e->num_lines - same;
562 chunk_end_lno = split[2].lno;
563 }
564 else
565 chunk_end_lno = e->lno + e->num_lines;
566 split[1].num_lines = chunk_end_lno - split[1].lno;
567
568 if (split[1].num_lines < 1)
569 return;
570 split[1].suspect = origin_incref(parent);
571 }
572
573 static void split_blame(struct scoreboard *sb,
574 struct blame_entry *split,
575 struct blame_entry *e)
576 {
577 struct blame_entry *new_entry;
578
579 if (split[0].suspect && split[2].suspect) {
580 /* we need to split e into two and add another for parent */
581 dup_entry(e, &split[0]);
582
583 new_entry = xmalloc(sizeof(*new_entry));
584 memcpy(new_entry, &(split[2]), sizeof(struct blame_entry));
585 add_blame_entry(sb, new_entry);
586
587 new_entry = xmalloc(sizeof(*new_entry));
588 memcpy(new_entry, &(split[1]), sizeof(struct blame_entry));
589 add_blame_entry(sb, new_entry);
590 }
591 else if (!split[0].suspect && !split[2].suspect)
592 /* parent covers the entire area */
593 dup_entry(e, &split[1]);
594 else if (split[0].suspect) {
595 dup_entry(e, &split[0]);
596
597 new_entry = xmalloc(sizeof(*new_entry));
598 memcpy(new_entry, &(split[1]), sizeof(struct blame_entry));
599 add_blame_entry(sb, new_entry);
600 }
601 else {
602 dup_entry(e, &split[1]);
603
604 new_entry = xmalloc(sizeof(*new_entry));
605 memcpy(new_entry, &(split[2]), sizeof(struct blame_entry));
606 add_blame_entry(sb, new_entry);
607 }
608
609 if (DEBUG) { /* sanity */
610 struct blame_entry *ent;
611 int lno = sb->ent->lno, corrupt = 0;
612
613 for (ent = sb->ent; ent; ent = ent->next) {
614 if (lno != ent->lno)
615 corrupt = 1;
616 if (ent->s_lno < 0)
617 corrupt = 1;
618 lno += ent->num_lines;
619 }
620 if (corrupt) {
621 lno = sb->ent->lno;
622 for (ent = sb->ent; ent; ent = ent->next) {
623 printf("L %8d l %8d n %8d\n",
624 lno, ent->lno, ent->num_lines);
625 lno = ent->lno + ent->num_lines;
626 }
627 die("oops");
628 }
629 }
630 }
631
632 static void decref_split(struct blame_entry *split)
633 {
634 int i;
635
636 for (i = 0; i < 3; i++)
637 origin_decref(split[i].suspect);
638 }
639
640 static void blame_overlap(struct scoreboard *sb, struct blame_entry *e,
641 int tlno, int plno, int same,
642 struct origin *parent)
643 {
644 struct blame_entry split[3];
645
646 split_overlap(split, e, tlno, plno, same, parent);
647 if (split[1].suspect)
648 split_blame(sb, split, e);
649 decref_split(split);
650 }
651
652 static int find_last_in_target(struct scoreboard *sb, struct origin *target)
653 {
654 struct blame_entry *e;
655 int last_in_target = -1;
656
657 for (e = sb->ent; e; e = e->next) {
658 if (e->guilty || cmp_suspect(e->suspect, target))
659 continue;
660 if (last_in_target < e->s_lno + e->num_lines)
661 last_in_target = e->s_lno + e->num_lines;
662 }
663 return last_in_target;
664 }
665
666 static void blame_chunk(struct scoreboard *sb,
667 int tlno, int plno, int same,
668 struct origin *target, struct origin *parent)
669 {
670 struct blame_entry *e;
671
672 for (e = sb->ent; e; e = e->next) {
673 if (e->guilty || cmp_suspect(e->suspect, target))
674 continue;
675 if (same <= e->s_lno)
676 continue;
677 if (tlno < e->s_lno + e->num_lines)
678 blame_overlap(sb, e, tlno, plno, same, parent);
679 }
680 }
681
682 static int pass_blame_to_parent(struct scoreboard *sb,
683 struct origin *target,
684 struct origin *parent)
685 {
686 int i, last_in_target, plno, tlno;
687 struct patch *patch;
688
689 last_in_target = find_last_in_target(sb, target);
690 if (last_in_target < 0)
691 return 1; /* nothing remains for this target */
692
693 patch = get_patch(parent, target);
694 plno = tlno = 0;
695 for (i = 0; i < patch->num; i++) {
696 struct chunk *chunk = &patch->chunks[i];
697
698 blame_chunk(sb, tlno, plno, chunk->same, target, parent);
699 plno = chunk->p_next;
700 tlno = chunk->t_next;
701 }
702 /* rest (i.e. anything above tlno) are the same as parent */
703 blame_chunk(sb, tlno, plno, last_in_target, target, parent);
704
705 free_patch(patch);
706 return 0;
707 }
708
709 static unsigned ent_score(struct scoreboard *sb, struct blame_entry *e)
710 {
711 unsigned score;
712 const char *cp, *ep;
713
714 if (e->score)
715 return e->score;
716
717 score = 1;
718 cp = nth_line(sb, e->lno);
719 ep = nth_line(sb, e->lno + e->num_lines);
720 while (cp < ep) {
721 unsigned ch = *((unsigned char *)cp);
722 if (isalnum(ch))
723 score++;
724 cp++;
725 }
726 e->score = score;
727 return score;
728 }
729
730 static void copy_split_if_better(struct scoreboard *sb,
731 struct blame_entry *best_so_far,
732 struct blame_entry *this)
733 {
734 int i;
735
736 if (!this[1].suspect)
737 return;
738 if (best_so_far[1].suspect) {
739 if (ent_score(sb, &this[1]) < ent_score(sb, &best_so_far[1]))
740 return;
741 }
742
743 for (i = 0; i < 3; i++)
744 origin_incref(this[i].suspect);
745 decref_split(best_so_far);
746 memcpy(best_so_far, this, sizeof(struct blame_entry [3]));
747 }
748
749 static void find_copy_in_blob(struct scoreboard *sb,
750 struct blame_entry *ent,
751 struct origin *parent,
752 struct blame_entry *split,
753 mmfile_t *file_p)
754 {
755 const char *cp;
756 int cnt;
757 mmfile_t file_o;
758 struct patch *patch;
759 int i, plno, tlno;
760
761 cp = nth_line(sb, ent->lno);
762 file_o.ptr = (char*) cp;
763 cnt = ent->num_lines;
764
765 while (cnt && cp < sb->final_buf + sb->final_buf_size) {
766 if (*cp++ == '\n')
767 cnt--;
768 }
769 file_o.size = cp - file_o.ptr;
770
771 patch = compare_buffer(file_p, &file_o, 1);
772
773 memset(split, 0, sizeof(struct blame_entry [3]));
774 plno = tlno = 0;
775 for (i = 0; i < patch->num; i++) {
776 struct chunk *chunk = &patch->chunks[i];
777
778 /* tlno to chunk->same are the same as ent */
779 if (ent->num_lines <= tlno)
780 break;
781 if (tlno < chunk->same) {
782 struct blame_entry this[3];
783 split_overlap(this, ent,
784 tlno + ent->s_lno, plno,
785 chunk->same + ent->s_lno,
786 parent);
787 copy_split_if_better(sb, split, this);
788 decref_split(this);
789 }
790 plno = chunk->p_next;
791 tlno = chunk->t_next;
792 }
793 free_patch(patch);
794 }
795
796 static int find_move_in_parent(struct scoreboard *sb,
797 struct origin *target,
798 struct origin *parent)
799 {
800 int last_in_target, made_progress;
801 struct blame_entry *e, split[3];
802 mmfile_t file_p;
803
804 last_in_target = find_last_in_target(sb, target);
805 if (last_in_target < 0)
806 return 1; /* nothing remains for this target */
807
808 fill_origin_blob(parent, &file_p);
809 if (!file_p.ptr)
810 return 0;
811
812 made_progress = 1;
813 while (made_progress) {
814 made_progress = 0;
815 for (e = sb->ent; e; e = e->next) {
816 if (e->guilty || cmp_suspect(e->suspect, target))
817 continue;
818 find_copy_in_blob(sb, e, parent, split, &file_p);
819 if (split[1].suspect &&
820 blame_move_score < ent_score(sb, &split[1])) {
821 split_blame(sb, split, e);
822 made_progress = 1;
823 }
824 decref_split(split);
825 }
826 }
827 return 0;
828 }
829
830
831 struct blame_list {
832 struct blame_entry *ent;
833 struct blame_entry split[3];
834 };
835
836 static struct blame_list *setup_blame_list(struct scoreboard *sb,
837 struct origin *target,
838 int *num_ents_p)
839 {
840 struct blame_entry *e;
841 int num_ents, i;
842 struct blame_list *blame_list = NULL;
843
844 /* Count the number of entries the target is suspected for,
845 * and prepare a list of entry and the best split.
846 */
847 for (e = sb->ent, num_ents = 0; e; e = e->next)
848 if (!e->guilty && !cmp_suspect(e->suspect, target))
849 num_ents++;
850 if (num_ents) {
851 blame_list = xcalloc(num_ents, sizeof(struct blame_list));
852 for (e = sb->ent, i = 0; e; e = e->next)
853 if (!e->guilty && !cmp_suspect(e->suspect, target))
854 blame_list[i++].ent = e;
855 }
856 *num_ents_p = num_ents;
857 return blame_list;
858 }
859
860 static int find_copy_in_parent(struct scoreboard *sb,
861 struct origin *target,
862 struct commit *parent,
863 struct origin *porigin,
864 int opt)
865 {
866 struct diff_options diff_opts;
867 const char *paths[1];
868 int i, j;
869 int retval;
870 struct blame_list *blame_list;
871 int num_ents;
872
873 blame_list = setup_blame_list(sb, target, &num_ents);
874 if (!blame_list)
875 return 1; /* nothing remains for this target */
876
877 diff_setup(&diff_opts);
878 diff_opts.recursive = 1;
879 diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;
880
881 paths[0] = NULL;
882 diff_tree_setup_paths(paths, &diff_opts);
883 if (diff_setup_done(&diff_opts) < 0)
884 die("diff-setup");
885
886 /* Try "find copies harder" on new path if requested;
887 * we do not want to use diffcore_rename() actually to
888 * match things up; find_copies_harder is set only to
889 * force diff_tree_sha1() to feed all filepairs to diff_queue,
890 * and this code needs to be after diff_setup_done(), which
891 * usually makes find-copies-harder imply copy detection.
892 */
893 if ((opt & PICKAXE_BLAME_COPY_HARDER) &&
894 (!porigin || strcmp(target->path, porigin->path)))
895 diff_opts.find_copies_harder = 1;
896
897 diff_tree_sha1(parent->tree->object.sha1,
898 target->commit->tree->object.sha1,
899 "", &diff_opts);
900
901 if (!diff_opts.find_copies_harder)
902 diffcore_std(&diff_opts);
903
904 retval = 0;
905 while (1) {
906 int made_progress = 0;
907
908 for (i = 0; i < diff_queued_diff.nr; i++) {
909 struct diff_filepair *p = diff_queued_diff.queue[i];
910 struct origin *norigin;
911 mmfile_t file_p;
912 struct blame_entry this[3];
913
914 if (!DIFF_FILE_VALID(p->one))
915 continue; /* does not exist in parent */
916 if (porigin && !strcmp(p->one->path, porigin->path))
917 /* find_move already dealt with this path */
918 continue;
919
920 norigin = get_origin(sb, parent, p->one->path);
921 hashcpy(norigin->blob_sha1, p->one->sha1);
922 fill_origin_blob(norigin, &file_p);
923 if (!file_p.ptr)
924 continue;
925
926 for (j = 0; j < num_ents; j++) {
927 find_copy_in_blob(sb, blame_list[j].ent,
928 norigin, this, &file_p);
929 copy_split_if_better(sb, blame_list[j].split,
930 this);
931 decref_split(this);
932 }
933 origin_decref(norigin);
934 }
935
936 for (j = 0; j < num_ents; j++) {
937 struct blame_entry *split = blame_list[j].split;
938 if (split[1].suspect &&
939 blame_copy_score < ent_score(sb, &split[1])) {
940 split_blame(sb, split, blame_list[j].ent);
941 made_progress = 1;
942 }
943 decref_split(split);
944 }
945 free(blame_list);
946
947 if (!made_progress)
948 break;
949 blame_list = setup_blame_list(sb, target, &num_ents);
950 if (!blame_list) {
951 retval = 1;
952 break;
953 }
954 }
955 diff_flush(&diff_opts);
956
957 return retval;
958 }
959
960 /* The blobs of origin and porigin exactly match, so everything
961 * origin is suspected for can be blamed on the parent.
962 */
963 static void pass_whole_blame(struct scoreboard *sb,
964 struct origin *origin, struct origin *porigin)
965 {
966 struct blame_entry *e;
967
968 if (!porigin->file.ptr && origin->file.ptr) {
969 /* Steal its file */
970 porigin->file = origin->file;
971 origin->file.ptr = NULL;
972 }
973 for (e = sb->ent; e; e = e->next) {
974 if (cmp_suspect(e->suspect, origin))
975 continue;
976 origin_incref(porigin);
977 origin_decref(e->suspect);
978 e->suspect = porigin;
979 }
980 }
981
982 #define MAXPARENT 16
983
984 static void pass_blame(struct scoreboard *sb, struct origin *origin, int opt)
985 {
986 int i, pass;
987 struct commit *commit = origin->commit;
988 struct commit_list *parent;
989 struct origin *parent_origin[MAXPARENT], *porigin;
990
991 memset(parent_origin, 0, sizeof(parent_origin));
992
993 /* The first pass looks for unrenamed path to optimize for
994 * common cases, then we look for renames in the second pass.
995 */
996 for (pass = 0; pass < 2; pass++) {
997 struct origin *(*find)(struct scoreboard *,
998 struct commit *, struct origin *);
999 find = pass ? find_rename : find_origin;
1000
1001 for (i = 0, parent = commit->parents;
1002 i < MAXPARENT && parent;
1003 parent = parent->next, i++) {
1004 struct commit *p = parent->item;
1005 int j, same;
1006
1007 if (parent_origin[i])
1008 continue;
1009 if (parse_commit(p))
1010 continue;
1011 porigin = find(sb, p, origin);
1012 if (!porigin)
1013 continue;
1014 if (!hashcmp(porigin->blob_sha1, origin->blob_sha1)) {
1015 pass_whole_blame(sb, origin, porigin);
1016 origin_decref(porigin);
1017 goto finish;
1018 }
1019 for (j = same = 0; j < i; j++)
1020 if (parent_origin[j] &&
1021 !hashcmp(parent_origin[j]->blob_sha1,
1022 porigin->blob_sha1)) {
1023 same = 1;
1024 break;
1025 }
1026 if (!same)
1027 parent_origin[i] = porigin;
1028 else
1029 origin_decref(porigin);
1030 }
1031 }
1032
1033 num_commits++;
1034 for (i = 0, parent = commit->parents;
1035 i < MAXPARENT && parent;
1036 parent = parent->next, i++) {
1037 struct origin *porigin = parent_origin[i];
1038 if (!porigin)
1039 continue;
1040 if (pass_blame_to_parent(sb, origin, porigin))
1041 goto finish;
1042 }
1043
1044 /*
1045 * Optionally run "miff" to find moves in parents' files here.
1046 */
1047 if (opt & PICKAXE_BLAME_MOVE)
1048 for (i = 0, parent = commit->parents;
1049 i < MAXPARENT && parent;
1050 parent = parent->next, i++) {
1051 struct origin *porigin = parent_origin[i];
1052 if (!porigin)
1053 continue;
1054 if (find_move_in_parent(sb, origin, porigin))
1055 goto finish;
1056 }
1057
1058 /*
1059 * Optionally run "ciff" to find copies from parents' files here.
1060 */
1061 if (opt & PICKAXE_BLAME_COPY)
1062 for (i = 0, parent = commit->parents;
1063 i < MAXPARENT && parent;
1064 parent = parent->next, i++) {
1065 struct origin *porigin = parent_origin[i];
1066 if (find_copy_in_parent(sb, origin, parent->item,
1067 porigin, opt))
1068 goto finish;
1069 }
1070
1071 finish:
1072 for (i = 0; i < MAXPARENT; i++)
1073 origin_decref(parent_origin[i]);
1074 }
1075
1076 static void assign_blame(struct scoreboard *sb, struct rev_info *revs, int opt)
1077 {
1078 while (1) {
1079 struct blame_entry *ent;
1080 struct commit *commit;
1081 struct origin *suspect = NULL;
1082
1083 /* find one suspect to break down */
1084 for (ent = sb->ent; !suspect && ent; ent = ent->next)
1085 if (!ent->guilty)
1086 suspect = ent->suspect;
1087 if (!suspect)
1088 return; /* all done */
1089
1090 origin_incref(suspect);
1091 commit = suspect->commit;
1092 if (!commit->object.parsed)
1093 parse_commit(commit);
1094 if (!(commit->object.flags & UNINTERESTING) &&
1095 !(revs->max_age != -1 && commit->date < revs->max_age))
1096 pass_blame(sb, suspect, opt);
1097 else {
1098 commit->object.flags |= UNINTERESTING;
1099 if (commit->object.parsed)
1100 mark_parents_uninteresting(commit);
1101 }
1102 /* treat root commit as boundary */
1103 if (!commit->parents && !show_root)
1104 commit->object.flags |= UNINTERESTING;
1105
1106 /* Take responsibility for the remaining entries */
1107 for (ent = sb->ent; ent; ent = ent->next)
1108 if (!cmp_suspect(ent->suspect, suspect))
1109 ent->guilty = 1;
1110 origin_decref(suspect);
1111
1112 if (DEBUG) /* sanity */
1113 sanity_check_refcnt(sb);
1114 }
1115 }
1116
1117 static const char *format_time(unsigned long time, const char *tz_str,
1118 int show_raw_time)
1119 {
1120 static char time_buf[128];
1121 time_t t = time;
1122 int minutes, tz;
1123 struct tm *tm;
1124
1125 if (show_raw_time) {
1126 sprintf(time_buf, "%lu %s", time, tz_str);
1127 return time_buf;
1128 }
1129
1130 tz = atoi(tz_str);
1131 minutes = tz < 0 ? -tz : tz;
1132 minutes = (minutes / 100)*60 + (minutes % 100);
1133 minutes = tz < 0 ? -minutes : minutes;
1134 t = time + minutes * 60;
1135 tm = gmtime(&t);
1136
1137 strftime(time_buf, sizeof(time_buf), "%Y-%m-%d %H:%M:%S ", tm);
1138 strcat(time_buf, tz_str);
1139 return time_buf;
1140 }
1141
1142 struct commit_info
1143 {
1144 char *author;
1145 char *author_mail;
1146 unsigned long author_time;
1147 char *author_tz;
1148
1149 /* filled only when asked for details */
1150 char *committer;
1151 char *committer_mail;
1152 unsigned long committer_time;
1153 char *committer_tz;
1154
1155 char *summary;
1156 };
1157
1158 static void get_ac_line(const char *inbuf, const char *what,
1159 int bufsz, char *person, char **mail,
1160 unsigned long *time, char **tz)
1161 {
1162 int len;
1163 char *tmp, *endp;
1164
1165 tmp = strstr(inbuf, what);
1166 if (!tmp)
1167 goto error_out;
1168 tmp += strlen(what);
1169 endp = strchr(tmp, '\n');
1170 if (!endp)
1171 len = strlen(tmp);
1172 else
1173 len = endp - tmp;
1174 if (bufsz <= len) {
1175 error_out:
1176 /* Ugh */
1177 person = *mail = *tz = "(unknown)";
1178 *time = 0;
1179 return;
1180 }
1181 memcpy(person, tmp, len);
1182
1183 tmp = person;
1184 tmp += len;
1185 *tmp = 0;
1186 while (*tmp != ' ')
1187 tmp--;
1188 *tz = tmp+1;
1189
1190 *tmp = 0;
1191 while (*tmp != ' ')
1192 tmp--;
1193 *time = strtoul(tmp, NULL, 10);
1194
1195 *tmp = 0;
1196 while (*tmp != ' ')
1197 tmp--;
1198 *mail = tmp + 1;
1199 *tmp = 0;
1200 }
1201
1202 static void get_commit_info(struct commit *commit,
1203 struct commit_info *ret,
1204 int detailed)
1205 {
1206 int len;
1207 char *tmp, *endp;
1208 static char author_buf[1024];
1209 static char committer_buf[1024];
1210 static char summary_buf[1024];
1211
1212 /* We've operated without save_commit_buffer, so
1213 * we now need to populate them for output.
1214 */
1215 if (!commit->buffer) {
1216 char type[20];
1217 unsigned long size;
1218 commit->buffer =
1219 read_sha1_file(commit->object.sha1, type, &size);
1220 }
1221 ret->author = author_buf;
1222 get_ac_line(commit->buffer, "\nauthor ",
1223 sizeof(author_buf), author_buf, &ret->author_mail,
1224 &ret->author_time, &ret->author_tz);
1225
1226 if (!detailed)
1227 return;
1228
1229 ret->committer = committer_buf;
1230 get_ac_line(commit->buffer, "\ncommitter ",
1231 sizeof(committer_buf), committer_buf, &ret->committer_mail,
1232 &ret->committer_time, &ret->committer_tz);
1233
1234 ret->summary = summary_buf;
1235 tmp = strstr(commit->buffer, "\n\n");
1236 if (!tmp) {
1237 error_out:
1238 sprintf(summary_buf, "(%s)", sha1_to_hex(commit->object.sha1));
1239 return;
1240 }
1241 tmp += 2;
1242 endp = strchr(tmp, '\n');
1243 if (!endp)
1244 goto error_out;
1245 len = endp - tmp;
1246 if (len >= sizeof(summary_buf))
1247 goto error_out;
1248 memcpy(summary_buf, tmp, len);
1249 summary_buf[len] = 0;
1250 }
1251
1252 #define OUTPUT_ANNOTATE_COMPAT 001
1253 #define OUTPUT_LONG_OBJECT_NAME 002
1254 #define OUTPUT_RAW_TIMESTAMP 004
1255 #define OUTPUT_PORCELAIN 010
1256 #define OUTPUT_SHOW_NAME 020
1257 #define OUTPUT_SHOW_NUMBER 040
1258 #define OUTPUT_SHOW_SCORE 0100
1259
1260 static void emit_porcelain(struct scoreboard *sb, struct blame_entry *ent)
1261 {
1262 int cnt;
1263 const char *cp;
1264 struct origin *suspect = ent->suspect;
1265 char hex[41];
1266
1267 strcpy(hex, sha1_to_hex(suspect->commit->object.sha1));
1268 printf("%s%c%d %d %d\n",
1269 hex,
1270 ent->guilty ? ' ' : '*', // purely for debugging
1271 ent->s_lno + 1,
1272 ent->lno + 1,
1273 ent->num_lines);
1274 if (!(suspect->commit->object.flags & METAINFO_SHOWN)) {
1275 struct commit_info ci;
1276 suspect->commit->object.flags |= METAINFO_SHOWN;
1277 get_commit_info(suspect->commit, &ci, 1);
1278 printf("author %s\n", ci.author);
1279 printf("author-mail %s\n", ci.author_mail);
1280 printf("author-time %lu\n", ci.author_time);
1281 printf("author-tz %s\n", ci.author_tz);
1282 printf("committer %s\n", ci.committer);
1283 printf("committer-mail %s\n", ci.committer_mail);
1284 printf("committer-time %lu\n", ci.committer_time);
1285 printf("committer-tz %s\n", ci.committer_tz);
1286 printf("filename %s\n", suspect->path);
1287 printf("summary %s\n", ci.summary);
1288 if (suspect->commit->object.flags & UNINTERESTING)
1289 printf("boundary\n");
1290 }
1291 else if (suspect->commit->object.flags & MORE_THAN_ONE_PATH)
1292 printf("filename %s\n", suspect->path);
1293
1294 cp = nth_line(sb, ent->lno);
1295 for (cnt = 0; cnt < ent->num_lines; cnt++) {
1296 char ch;
1297 if (cnt)
1298 printf("%s %d %d\n", hex,
1299 ent->s_lno + 1 + cnt,
1300 ent->lno + 1 + cnt);
1301 putchar('\t');
1302 do {
1303 ch = *cp++;
1304 putchar(ch);
1305 } while (ch != '\n' &&
1306 cp < sb->final_buf + sb->final_buf_size);
1307 }
1308 }
1309
1310 static void emit_other(struct scoreboard *sb, struct blame_entry *ent, int opt)
1311 {
1312 int cnt;
1313 const char *cp;
1314 struct origin *suspect = ent->suspect;
1315 struct commit_info ci;
1316 char hex[41];
1317 int show_raw_time = !!(opt & OUTPUT_RAW_TIMESTAMP);
1318
1319 get_commit_info(suspect->commit, &ci, 1);
1320 strcpy(hex, sha1_to_hex(suspect->commit->object.sha1));
1321
1322 cp = nth_line(sb, ent->lno);
1323 for (cnt = 0; cnt < ent->num_lines; cnt++) {
1324 char ch;
1325 int length = (opt & OUTPUT_LONG_OBJECT_NAME) ? 40 : 8;
1326
1327 if (suspect->commit->object.flags & UNINTERESTING) {
1328 if (!blank_boundary) {
1329 length--;
1330 putchar('^');
1331 }
1332 else
1333 memset(hex, ' ', length);
1334 }
1335
1336 printf("%.*s", length, hex);
1337 if (opt & OUTPUT_ANNOTATE_COMPAT)
1338 printf("\t(%10s\t%10s\t%d)", ci.author,
1339 format_time(ci.author_time, ci.author_tz,
1340 show_raw_time),
1341 ent->lno + 1 + cnt);
1342 else {
1343 if (opt & OUTPUT_SHOW_SCORE)
1344 printf(" %*d %02d",
1345 max_score_digits, ent->score,
1346 ent->suspect->refcnt);
1347 if (opt & OUTPUT_SHOW_NAME)
1348 printf(" %-*.*s", longest_file, longest_file,
1349 suspect->path);
1350 if (opt & OUTPUT_SHOW_NUMBER)
1351 printf(" %*d", max_orig_digits,
1352 ent->s_lno + 1 + cnt);
1353 printf(" (%-*.*s %10s %*d) ",
1354 longest_author, longest_author, ci.author,
1355 format_time(ci.author_time, ci.author_tz,
1356 show_raw_time),
1357 max_digits, ent->lno + 1 + cnt);
1358 }
1359 do {
1360 ch = *cp++;
1361 putchar(ch);
1362 } while (ch != '\n' &&
1363 cp < sb->final_buf + sb->final_buf_size);
1364 }
1365 }
1366
1367 static void output(struct scoreboard *sb, int option)
1368 {
1369 struct blame_entry *ent;
1370
1371 if (option & OUTPUT_PORCELAIN) {
1372 for (ent = sb->ent; ent; ent = ent->next) {
1373 struct blame_entry *oth;
1374 struct origin *suspect = ent->suspect;
1375 struct commit *commit = suspect->commit;
1376 if (commit->object.flags & MORE_THAN_ONE_PATH)
1377 continue;
1378 for (oth = ent->next; oth; oth = oth->next) {
1379 if ((oth->suspect->commit != commit) ||
1380 !strcmp(oth->suspect->path, suspect->path))
1381 continue;
1382 commit->object.flags |= MORE_THAN_ONE_PATH;
1383 break;
1384 }
1385 }
1386 }
1387
1388 for (ent = sb->ent; ent; ent = ent->next) {
1389 if (option & OUTPUT_PORCELAIN)
1390 emit_porcelain(sb, ent);
1391 else {
1392 emit_other(sb, ent, option);
1393 }
1394 }
1395 }
1396
1397 static int prepare_lines(struct scoreboard *sb)
1398 {
1399 const char *buf = sb->final_buf;
1400 unsigned long len = sb->final_buf_size;
1401 int num = 0, incomplete = 0, bol = 1;
1402
1403 if (len && buf[len-1] != '\n')
1404 incomplete++; /* incomplete line at the end */
1405 while (len--) {
1406 if (bol) {
1407 sb->lineno = xrealloc(sb->lineno,
1408 sizeof(int* ) * (num + 1));
1409 sb->lineno[num] = buf - sb->final_buf;
1410 bol = 0;
1411 }
1412 if (*buf++ == '\n') {
1413 num++;
1414 bol = 1;
1415 }
1416 }
1417 sb->lineno = xrealloc(sb->lineno,
1418 sizeof(int* ) * (num + incomplete + 1));
1419 sb->lineno[num + incomplete] = buf - sb->final_buf;
1420 sb->num_lines = num + incomplete;
1421 return sb->num_lines;
1422 }
1423
1424 static int read_ancestry(const char *graft_file)
1425 {
1426 FILE *fp = fopen(graft_file, "r");
1427 char buf[1024];
1428 if (!fp)
1429 return -1;
1430 while (fgets(buf, sizeof(buf), fp)) {
1431 /* The format is just "Commit Parent1 Parent2 ...\n" */
1432 int len = strlen(buf);
1433 struct commit_graft *graft = read_graft_line(buf, len);
1434 if (graft)
1435 register_commit_graft(graft, 0);
1436 }
1437 fclose(fp);
1438 return 0;
1439 }
1440
1441 static int lineno_width(int lines)
1442 {
1443 int i, width;
1444
1445 for (width = 1, i = 10; i <= lines + 1; width++)
1446 i *= 10;
1447 return width;
1448 }
1449
1450 static void find_alignment(struct scoreboard *sb, int *option)
1451 {
1452 int longest_src_lines = 0;
1453 int longest_dst_lines = 0;
1454 unsigned largest_score = 0;
1455 struct blame_entry *e;
1456
1457 for (e = sb->ent; e; e = e->next) {
1458 struct origin *suspect = e->suspect;
1459 struct commit_info ci;
1460 int num;
1461
1462 if (strcmp(suspect->path, sb->path))
1463 *option |= OUTPUT_SHOW_NAME;
1464 num = strlen(suspect->path);
1465 if (longest_file < num)
1466 longest_file = num;
1467 if (!(suspect->commit->object.flags & METAINFO_SHOWN)) {
1468 suspect->commit->object.flags |= METAINFO_SHOWN;
1469 get_commit_info(suspect->commit, &ci, 1);
1470 num = strlen(ci.author);
1471 if (longest_author < num)
1472 longest_author = num;
1473 }
1474 num = e->s_lno + e->num_lines;
1475 if (longest_src_lines < num)
1476 longest_src_lines = num;
1477 num = e->lno + e->num_lines;
1478 if (longest_dst_lines < num)
1479 longest_dst_lines = num;
1480 if (largest_score < ent_score(sb, e))
1481 largest_score = ent_score(sb, e);
1482 }
1483 max_orig_digits = lineno_width(longest_src_lines);
1484 max_digits = lineno_width(longest_dst_lines);
1485 max_score_digits = lineno_width(largest_score);
1486 }
1487
1488 static void sanity_check_refcnt(struct scoreboard *sb)
1489 {
1490 int baa = 0;
1491 struct blame_entry *ent;
1492
1493 for (ent = sb->ent; ent; ent = ent->next) {
1494 /* Nobody should have zero or negative refcnt */
1495 if (ent->suspect->refcnt <= 0) {
1496 fprintf(stderr, "%s in %s has negative refcnt %d\n",
1497 ent->suspect->path,
1498 sha1_to_hex(ent->suspect->commit->object.sha1),
1499 ent->suspect->refcnt);
1500 baa = 1;
1501 }
1502 }
1503 for (ent = sb->ent; ent; ent = ent->next) {
1504 /* Mark the ones that haven't been checked */
1505 if (0 < ent->suspect->refcnt)
1506 ent->suspect->refcnt = -ent->suspect->refcnt;
1507 }
1508 for (ent = sb->ent; ent; ent = ent->next) {
1509 /* then pick each and see if they have the the correct
1510 * refcnt.
1511 */
1512 int found;
1513 struct blame_entry *e;
1514 struct origin *suspect = ent->suspect;
1515
1516 if (0 < suspect->refcnt)
1517 continue;
1518 suspect->refcnt = -suspect->refcnt; /* Unmark */
1519 for (found = 0, e = sb->ent; e; e = e->next) {
1520 if (e->suspect != suspect)
1521 continue;
1522 found++;
1523 }
1524 if (suspect->refcnt != found) {
1525 fprintf(stderr, "%s in %s has refcnt %d, not %d\n",
1526 ent->suspect->path,
1527 sha1_to_hex(ent->suspect->commit->object.sha1),
1528 ent->suspect->refcnt, found);
1529 baa = 2;
1530 }
1531 }
1532 if (baa) {
1533 int opt = 0160;
1534 find_alignment(sb, &opt);
1535 output(sb, opt);
1536 die("Baa %d!", baa);
1537 }
1538 }
1539
1540 static int has_path_in_work_tree(const char *path)
1541 {
1542 struct stat st;
1543 return !lstat(path, &st);
1544 }
1545
1546 static unsigned parse_score(const char *arg)
1547 {
1548 char *end;
1549 unsigned long score = strtoul(arg, &end, 10);
1550 if (*end)
1551 return 0;
1552 return score;
1553 }
1554
1555 static const char *add_prefix(const char *prefix, const char *path)
1556 {
1557 if (!prefix || !prefix[0])
1558 return path;
1559 return prefix_path(prefix, strlen(prefix), path);
1560 }
1561
1562 static const char *parse_loc(const char *spec,
1563 struct scoreboard *sb, long lno,
1564 long begin, long *ret)
1565 {
1566 char *term;
1567 const char *line;
1568 long num;
1569 int reg_error;
1570 regex_t regexp;
1571 regmatch_t match[1];
1572
1573 /* Allow "-L <something>,+20" to mean starting at <something>
1574 * for 20 lines, or "-L <something>,-5" for 5 lines ending at
1575 * <something>.
1576 */
1577 if (1 < begin && (spec[0] == '+' || spec[0] == '-')) {
1578 num = strtol(spec + 1, &term, 10);
1579 if (term != spec + 1) {
1580 if (spec[0] == '-')
1581 num = 0 - num;
1582 if (0 < num)
1583 *ret = begin + num - 2;
1584 else if (!num)
1585 *ret = begin;
1586 else
1587 *ret = begin + num;
1588 return term;
1589 }
1590 return spec;
1591 }
1592 num = strtol(spec, &term, 10);
1593 if (term != spec) {
1594 *ret = num;
1595 return term;
1596 }
1597 if (spec[0] != '/')
1598 return spec;
1599
1600 /* it could be a regexp of form /.../ */
1601 for (term = (char*) spec + 1; *term && *term != '/'; term++) {
1602 if (*term == '\\')
1603 term++;
1604 }
1605 if (*term != '/')
1606 return spec;
1607
1608 /* try [spec+1 .. term-1] as regexp */
1609 *term = 0;
1610 begin--; /* input is in human terms */
1611 line = nth_line(sb, begin);
1612
1613 if (!(reg_error = regcomp(&regexp, spec + 1, REG_NEWLINE)) &&
1614 !(reg_error = regexec(&regexp, line, 1, match, 0))) {
1615 const char *cp = line + match[0].rm_so;
1616 const char *nline;
1617
1618 while (begin++ < lno) {
1619 nline = nth_line(sb, begin);
1620 if (line <= cp && cp < nline)
1621 break;
1622 line = nline;
1623 }
1624 *ret = begin;
1625 regfree(&regexp);
1626 *term++ = '/';
1627 return term;
1628 }
1629 else {
1630 char errbuf[1024];
1631 regerror(reg_error, &regexp, errbuf, 1024);
1632 die("-L parameter '%s': %s", spec + 1, errbuf);
1633 }
1634 }
1635
1636 static void prepare_blame_range(struct scoreboard *sb,
1637 const char *bottomtop,
1638 long lno,
1639 long *bottom, long *top)
1640 {
1641 const char *term;
1642
1643 term = parse_loc(bottomtop, sb, lno, 1, bottom);
1644 if (*term == ',') {
1645 term = parse_loc(term + 1, sb, lno, *bottom + 1, top);
1646 if (*term)
1647 usage(blame_usage);
1648 }
1649 if (*term)
1650 usage(blame_usage);
1651 }
1652
1653 static int git_blame_config(const char *var, const char *value)
1654 {
1655 if (!strcmp(var, "blame.showroot")) {
1656 show_root = git_config_bool(var, value);
1657 return 0;
1658 }
1659 if (!strcmp(var, "blame.blankboundary")) {
1660 blank_boundary = git_config_bool(var, value);
1661 return 0;
1662 }
1663 return git_default_config(var, value);
1664 }
1665
1666 int cmd_blame(int argc, const char **argv, const char *prefix)
1667 {
1668 struct rev_info revs;
1669 const char *path;
1670 struct scoreboard sb;
1671 struct origin *o;
1672 struct blame_entry *ent;
1673 int i, seen_dashdash, unk, opt;
1674 long bottom, top, lno;
1675 int output_option = 0;
1676 const char *revs_file = NULL;
1677 const char *final_commit_name = NULL;
1678 char type[10];
1679 const char *bottomtop = NULL;
1680
1681 git_config(git_blame_config);
1682 save_commit_buffer = 0;
1683
1684 opt = 0;
1685 seen_dashdash = 0;
1686 for (unk = i = 1; i < argc; i++) {
1687 const char *arg = argv[i];
1688 if (*arg != '-')
1689 break;
1690 else if (!strcmp("-b", arg))
1691 blank_boundary = 1;
1692 else if (!strcmp("--root", arg))
1693 show_root = 1;
1694 else if (!strcmp("-c", arg))
1695 output_option |= OUTPUT_ANNOTATE_COMPAT;
1696 else if (!strcmp("-t", arg))
1697 output_option |= OUTPUT_RAW_TIMESTAMP;
1698 else if (!strcmp("-l", arg))
1699 output_option |= OUTPUT_LONG_OBJECT_NAME;
1700 else if (!strcmp("-S", arg) && ++i < argc)
1701 revs_file = argv[i];
1702 else if (!strncmp("-M", arg, 2)) {
1703 opt |= PICKAXE_BLAME_MOVE;
1704 blame_move_score = parse_score(arg+2);
1705 }
1706 else if (!strncmp("-C", arg, 2)) {
1707 if (opt & PICKAXE_BLAME_COPY)
1708 opt |= PICKAXE_BLAME_COPY_HARDER;
1709 opt |= PICKAXE_BLAME_COPY | PICKAXE_BLAME_MOVE;
1710 blame_copy_score = parse_score(arg+2);
1711 }
1712 else if (!strncmp("-L", arg, 2)) {
1713 if (!arg[2]) {
1714 if (++i >= argc)
1715 usage(blame_usage);
1716 arg = argv[i];
1717 }
1718 else
1719 arg += 2;
1720 if (bottomtop)
1721 die("More than one '-L n,m' option given");
1722 bottomtop = arg;
1723 }
1724 else if (!strcmp("--score-debug", arg))
1725 output_option |= OUTPUT_SHOW_SCORE;
1726 else if (!strcmp("-f", arg) ||
1727 !strcmp("--show-name", arg))
1728 output_option |= OUTPUT_SHOW_NAME;
1729 else if (!strcmp("-n", arg) ||
1730 !strcmp("--show-number", arg))
1731 output_option |= OUTPUT_SHOW_NUMBER;
1732 else if (!strcmp("-p", arg) ||
1733 !strcmp("--porcelain", arg))
1734 output_option |= OUTPUT_PORCELAIN;
1735 else if (!strcmp("--", arg)) {
1736 seen_dashdash = 1;
1737 i++;
1738 break;
1739 }
1740 else
1741 argv[unk++] = arg;
1742 }
1743
1744 if (!blame_move_score)
1745 blame_move_score = BLAME_DEFAULT_MOVE_SCORE;
1746 if (!blame_copy_score)
1747 blame_copy_score = BLAME_DEFAULT_COPY_SCORE;
1748
1749 /* We have collected options unknown to us in argv[1..unk]
1750 * which are to be passed to revision machinery if we are
1751 * going to do the "bottom" procesing.
1752 *
1753 * The remaining are:
1754 *
1755 * (1) if seen_dashdash, its either
1756 * "-options -- <path>" or
1757 * "-options -- <path> <rev>".
1758 * but the latter is allowed only if there is no
1759 * options that we passed to revision machinery.
1760 *
1761 * (2) otherwise, we may have "--" somewhere later and
1762 * might be looking at the first one of multiple 'rev'
1763 * parameters (e.g. " master ^next ^maint -- path").
1764 * See if there is a dashdash first, and give the
1765 * arguments before that to revision machinery.
1766 * After that there must be one 'path'.
1767 *
1768 * (3) otherwise, its one of the three:
1769 * "-options <path> <rev>"
1770 * "-options <rev> <path>"
1771 * "-options <path>"
1772 * but again the first one is allowed only if
1773 * there is no options that we passed to revision
1774 * machinery.
1775 */
1776
1777 if (seen_dashdash) {
1778 /* (1) */
1779 if (argc <= i)
1780 usage(blame_usage);
1781 path = add_prefix(prefix, argv[i]);
1782 if (i + 1 == argc - 1) {
1783 if (unk != 1)
1784 usage(blame_usage);
1785 argv[unk++] = argv[i + 1];
1786 }
1787 else if (i + 1 != argc)
1788 /* garbage at end */
1789 usage(blame_usage);
1790 }
1791 else {
1792 int j;
1793 for (j = i; !seen_dashdash && j < argc; j++)
1794 if (!strcmp(argv[j], "--"))
1795 seen_dashdash = j;
1796 if (seen_dashdash) {
1797 if (seen_dashdash + 1 != argc - 1)
1798 usage(blame_usage);
1799 path = add_prefix(prefix, argv[seen_dashdash + 1]);
1800 for (j = i; j < seen_dashdash; j++)
1801 argv[unk++] = argv[j];
1802 }
1803 else {
1804 /* (3) */
1805 path = add_prefix(prefix, argv[i]);
1806 if (i + 1 == argc - 1) {
1807 final_commit_name = argv[i + 1];
1808
1809 /* if (unk == 1) we could be getting
1810 * old-style
1811 */
1812 if (unk == 1 && !has_path_in_work_tree(path)) {
1813 path = add_prefix(prefix, argv[i + 1]);
1814 final_commit_name = argv[i];
1815 }
1816 }
1817 else if (i != argc - 1)
1818 usage(blame_usage); /* garbage at end */
1819
1820 if (!has_path_in_work_tree(path))
1821 die("cannot stat path %s: %s",
1822 path, strerror(errno));
1823 }
1824 }
1825
1826 if (final_commit_name)
1827 argv[unk++] = final_commit_name;
1828
1829 /* Now we got rev and path. We do not want the path pruning
1830 * but we may want "bottom" processing.
1831 */
1832 argv[unk++] = "--"; /* terminate the rev name */
1833 argv[unk] = NULL;
1834
1835 init_revisions(&revs, NULL);
1836 setup_revisions(unk, argv, &revs, "HEAD");
1837 memset(&sb, 0, sizeof(sb));
1838
1839 /* There must be one and only one positive commit in the
1840 * revs->pending array.
1841 */
1842 for (i = 0; i < revs.pending.nr; i++) {
1843 struct object *obj = revs.pending.objects[i].item;
1844 if (obj->flags & UNINTERESTING)
1845 continue;
1846 while (obj->type == OBJ_TAG)
1847 obj = deref_tag(obj, NULL, 0);
1848 if (obj->type != OBJ_COMMIT)
1849 die("Non commit %s?",
1850 revs.pending.objects[i].name);
1851 if (sb.final)
1852 die("More than one commit to dig from %s and %s?",
1853 revs.pending.objects[i].name,
1854 final_commit_name);
1855 sb.final = (struct commit *) obj;
1856 final_commit_name = revs.pending.objects[i].name;
1857 }
1858
1859 if (!sb.final) {
1860 /* "--not A B -- path" without anything positive */
1861 unsigned char head_sha1[20];
1862
1863 final_commit_name = "HEAD";
1864 if (get_sha1(final_commit_name, head_sha1))
1865 die("No such ref: HEAD");
1866 sb.final = lookup_commit_reference(head_sha1);
1867 add_pending_object(&revs, &(sb.final->object), "HEAD");
1868 }
1869
1870 /* If we have bottom, this will mark the ancestors of the
1871 * bottom commits we would reach while traversing as
1872 * uninteresting.
1873 */
1874 prepare_revision_walk(&revs);
1875
1876 o = get_origin(&sb, sb.final, path);
1877 if (fill_blob_sha1(o))
1878 die("no such path %s in %s", path, final_commit_name);
1879
1880 sb.final_buf = read_sha1_file(o->blob_sha1, type, &sb.final_buf_size);
1881 num_read_blob++;
1882 lno = prepare_lines(&sb);
1883
1884 bottom = top = 0;
1885 if (bottomtop)
1886 prepare_blame_range(&sb, bottomtop, lno, &bottom, &top);
1887 if (bottom && top && top < bottom) {
1888 long tmp;
1889 tmp = top; top = bottom; bottom = tmp;
1890 }
1891 if (bottom < 1)
1892 bottom = 1;
1893 if (top < 1)
1894 top = lno;
1895 bottom--;
1896 if (lno < top)
1897 die("file %s has only %lu lines", path, lno);
1898
1899 ent = xcalloc(1, sizeof(*ent));
1900 ent->lno = bottom;
1901 ent->num_lines = top - bottom;
1902 ent->suspect = o;
1903 ent->s_lno = bottom;
1904
1905 sb.ent = ent;
1906 sb.path = path;
1907
1908 if (revs_file && read_ancestry(revs_file))
1909 die("reading graft file %s failed: %s",
1910 revs_file, strerror(errno));
1911
1912 assign_blame(&sb, &revs, opt);
1913
1914 coalesce(&sb);
1915
1916 if (!(output_option & OUTPUT_PORCELAIN))
1917 find_alignment(&sb, &output_option);
1918
1919 output(&sb, output_option);
1920 free((void *)sb.final_buf);
1921 for (ent = sb.ent; ent; ) {
1922 struct blame_entry *e = ent->next;
1923 free(ent);
1924 ent = e;
1925 }
1926
1927 if (DEBUG) {
1928 printf("num read blob: %d\n", num_read_blob);
1929 printf("num get patch: %d\n", num_get_patch);
1930 printf("num commits: %d\n", num_commits);
1931 }
1932 return 0;
1933 }