Flush output in start_async
[git/jnareb-git/bp-gitweb.git] / builtin-blame.c
blob4ea343189fdad035318e94ce0c6c2ec16b62ba7f
1 /*
2 * Pickaxe
4 * Copyright (c) 2006, Junio C Hamano
5 */
7 #include "cache.h"
8 #include "builtin.h"
9 #include "blob.h"
10 #include "commit.h"
11 #include "tag.h"
12 #include "tree-walk.h"
13 #include "diff.h"
14 #include "diffcore.h"
15 #include "revision.h"
16 #include "quote.h"
17 #include "xdiff-interface.h"
18 #include "cache-tree.h"
19 #include "string-list.h"
20 #include "mailmap.h"
21 #include "parse-options.h"
23 static char blame_usage[] = "git blame [options] [rev-opts] [rev] [--] file";
25 static const char *blame_opt_usage[] = {
26 blame_usage,
27 "",
28 "[rev-opts] are documented in git-rev-list(1)",
29 NULL
32 static int longest_file;
33 static int longest_author;
34 static int max_orig_digits;
35 static int max_digits;
36 static int max_score_digits;
37 static int show_root;
38 static int reverse;
39 static int blank_boundary;
40 static int incremental;
41 static int cmd_is_annotate;
42 static int xdl_opts = XDF_NEED_MINIMAL;
43 static struct string_list mailmap;
45 #ifndef DEBUG
46 #define DEBUG 0
47 #endif
49 /* stats */
50 static int num_read_blob;
51 static int num_get_patch;
52 static int num_commits;
54 #define PICKAXE_BLAME_MOVE 01
55 #define PICKAXE_BLAME_COPY 02
56 #define PICKAXE_BLAME_COPY_HARDER 04
57 #define PICKAXE_BLAME_COPY_HARDEST 010
60 * blame for a blame_entry with score lower than these thresholds
61 * is not passed to the parent using move/copy logic.
63 static unsigned blame_move_score;
64 static unsigned blame_copy_score;
65 #define BLAME_DEFAULT_MOVE_SCORE 20
66 #define BLAME_DEFAULT_COPY_SCORE 40
68 /* bits #0..7 in revision.h, #8..11 used for merge_bases() in commit.c */
69 #define METAINFO_SHOWN (1u<<12)
70 #define MORE_THAN_ONE_PATH (1u<<13)
73 * One blob in a commit that is being suspected
75 struct origin {
76 int refcnt;
77 struct commit *commit;
78 mmfile_t file;
79 unsigned char blob_sha1[20];
80 char path[FLEX_ARRAY];
84 * Given an origin, prepare mmfile_t structure to be used by the
85 * diff machinery
87 static void fill_origin_blob(struct origin *o, mmfile_t *file)
89 if (!o->file.ptr) {
90 enum object_type type;
91 num_read_blob++;
92 file->ptr = read_sha1_file(o->blob_sha1, &type,
93 (unsigned long *)(&(file->size)));
94 if (!file->ptr)
95 die("Cannot read blob %s for path %s",
96 sha1_to_hex(o->blob_sha1),
97 o->path);
98 o->file = *file;
100 else
101 *file = o->file;
105 * Origin is refcounted and usually we keep the blob contents to be
106 * reused.
108 static inline struct origin *origin_incref(struct origin *o)
110 if (o)
111 o->refcnt++;
112 return o;
115 static void origin_decref(struct origin *o)
117 if (o && --o->refcnt <= 0) {
118 free(o->file.ptr);
119 free(o);
123 static void drop_origin_blob(struct origin *o)
125 if (o->file.ptr) {
126 free(o->file.ptr);
127 o->file.ptr = NULL;
132 * Each group of lines is described by a blame_entry; it can be split
133 * as we pass blame to the parents. They form a linked list in the
134 * scoreboard structure, sorted by the target line number.
136 struct blame_entry {
137 struct blame_entry *prev;
138 struct blame_entry *next;
140 /* the first line of this group in the final image;
141 * internally all line numbers are 0 based.
143 int lno;
145 /* how many lines this group has */
146 int num_lines;
148 /* the commit that introduced this group into the final image */
149 struct origin *suspect;
151 /* true if the suspect is truly guilty; false while we have not
152 * checked if the group came from one of its parents.
154 char guilty;
156 /* true if the entry has been scanned for copies in the current parent
158 char scanned;
160 /* the line number of the first line of this group in the
161 * suspect's file; internally all line numbers are 0 based.
163 int s_lno;
165 /* how significant this entry is -- cached to avoid
166 * scanning the lines over and over.
168 unsigned score;
172 * The current state of the blame assignment.
174 struct scoreboard {
175 /* the final commit (i.e. where we started digging from) */
176 struct commit *final;
177 struct rev_info *revs;
178 const char *path;
181 * The contents in the final image.
182 * Used by many functions to obtain contents of the nth line,
183 * indexed with scoreboard.lineno[blame_entry.lno].
185 const char *final_buf;
186 unsigned long final_buf_size;
188 /* linked list of blames */
189 struct blame_entry *ent;
191 /* look-up a line in the final buffer */
192 int num_lines;
193 int *lineno;
196 static inline int same_suspect(struct origin *a, struct origin *b)
198 if (a == b)
199 return 1;
200 if (a->commit != b->commit)
201 return 0;
202 return !strcmp(a->path, b->path);
205 static void sanity_check_refcnt(struct scoreboard *);
208 * If two blame entries that are next to each other came from
209 * contiguous lines in the same origin (i.e. <commit, path> pair),
210 * merge them together.
212 static void coalesce(struct scoreboard *sb)
214 struct blame_entry *ent, *next;
216 for (ent = sb->ent; ent && (next = ent->next); ent = next) {
217 if (same_suspect(ent->suspect, next->suspect) &&
218 ent->guilty == next->guilty &&
219 ent->s_lno + ent->num_lines == next->s_lno) {
220 ent->num_lines += next->num_lines;
221 ent->next = next->next;
222 if (ent->next)
223 ent->next->prev = ent;
224 origin_decref(next->suspect);
225 free(next);
226 ent->score = 0;
227 next = ent; /* again */
231 if (DEBUG) /* sanity */
232 sanity_check_refcnt(sb);
236 * Given a commit and a path in it, create a new origin structure.
237 * The callers that add blame to the scoreboard should use
238 * get_origin() to obtain shared, refcounted copy instead of calling
239 * this function directly.
241 static struct origin *make_origin(struct commit *commit, const char *path)
243 struct origin *o;
244 o = xcalloc(1, sizeof(*o) + strlen(path) + 1);
245 o->commit = commit;
246 o->refcnt = 1;
247 strcpy(o->path, path);
248 return o;
252 * Locate an existing origin or create a new one.
254 static struct origin *get_origin(struct scoreboard *sb,
255 struct commit *commit,
256 const char *path)
258 struct blame_entry *e;
260 for (e = sb->ent; e; e = e->next) {
261 if (e->suspect->commit == commit &&
262 !strcmp(e->suspect->path, path))
263 return origin_incref(e->suspect);
265 return make_origin(commit, path);
269 * Fill the blob_sha1 field of an origin if it hasn't, so that later
270 * call to fill_origin_blob() can use it to locate the data. blob_sha1
271 * for an origin is also used to pass the blame for the entire file to
272 * the parent to detect the case where a child's blob is identical to
273 * that of its parent's.
275 static int fill_blob_sha1(struct origin *origin)
277 unsigned mode;
279 if (!is_null_sha1(origin->blob_sha1))
280 return 0;
281 if (get_tree_entry(origin->commit->object.sha1,
282 origin->path,
283 origin->blob_sha1, &mode))
284 goto error_out;
285 if (sha1_object_info(origin->blob_sha1, NULL) != OBJ_BLOB)
286 goto error_out;
287 return 0;
288 error_out:
289 hashclr(origin->blob_sha1);
290 return -1;
294 * We have an origin -- check if the same path exists in the
295 * parent and return an origin structure to represent it.
297 static struct origin *find_origin(struct scoreboard *sb,
298 struct commit *parent,
299 struct origin *origin)
301 struct origin *porigin = NULL;
302 struct diff_options diff_opts;
303 const char *paths[2];
305 if (parent->util) {
307 * Each commit object can cache one origin in that
308 * commit. This is a freestanding copy of origin and
309 * not refcounted.
311 struct origin *cached = parent->util;
312 if (!strcmp(cached->path, origin->path)) {
314 * The same path between origin and its parent
315 * without renaming -- the most common case.
317 porigin = get_origin(sb, parent, cached->path);
320 * If the origin was newly created (i.e. get_origin
321 * would call make_origin if none is found in the
322 * scoreboard), it does not know the blob_sha1,
323 * so copy it. Otherwise porigin was in the
324 * scoreboard and already knows blob_sha1.
326 if (porigin->refcnt == 1)
327 hashcpy(porigin->blob_sha1, cached->blob_sha1);
328 return porigin;
330 /* otherwise it was not very useful; free it */
331 free(parent->util);
332 parent->util = NULL;
335 /* See if the origin->path is different between parent
336 * and origin first. Most of the time they are the
337 * same and diff-tree is fairly efficient about this.
339 diff_setup(&diff_opts);
340 DIFF_OPT_SET(&diff_opts, RECURSIVE);
341 diff_opts.detect_rename = 0;
342 diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;
343 paths[0] = origin->path;
344 paths[1] = NULL;
346 diff_tree_setup_paths(paths, &diff_opts);
347 if (diff_setup_done(&diff_opts) < 0)
348 die("diff-setup");
350 if (is_null_sha1(origin->commit->object.sha1))
351 do_diff_cache(parent->tree->object.sha1, &diff_opts);
352 else
353 diff_tree_sha1(parent->tree->object.sha1,
354 origin->commit->tree->object.sha1,
355 "", &diff_opts);
356 diffcore_std(&diff_opts);
358 /* It is either one entry that says "modified", or "created",
359 * or nothing.
361 if (!diff_queued_diff.nr) {
362 /* The path is the same as parent */
363 porigin = get_origin(sb, parent, origin->path);
364 hashcpy(porigin->blob_sha1, origin->blob_sha1);
366 else if (diff_queued_diff.nr != 1)
367 die("internal error in blame::find_origin");
368 else {
369 struct diff_filepair *p = diff_queued_diff.queue[0];
370 switch (p->status) {
371 default:
372 die("internal error in blame::find_origin (%c)",
373 p->status);
374 case 'M':
375 porigin = get_origin(sb, parent, origin->path);
376 hashcpy(porigin->blob_sha1, p->one->sha1);
377 break;
378 case 'A':
379 case 'T':
380 /* Did not exist in parent, or type changed */
381 break;
384 diff_flush(&diff_opts);
385 diff_tree_release_paths(&diff_opts);
386 if (porigin) {
388 * Create a freestanding copy that is not part of
389 * the refcounted origin found in the scoreboard, and
390 * cache it in the commit.
392 struct origin *cached;
394 cached = make_origin(porigin->commit, porigin->path);
395 hashcpy(cached->blob_sha1, porigin->blob_sha1);
396 parent->util = cached;
398 return porigin;
402 * We have an origin -- find the path that corresponds to it in its
403 * parent and return an origin structure to represent it.
405 static struct origin *find_rename(struct scoreboard *sb,
406 struct commit *parent,
407 struct origin *origin)
409 struct origin *porigin = NULL;
410 struct diff_options diff_opts;
411 int i;
412 const char *paths[2];
414 diff_setup(&diff_opts);
415 DIFF_OPT_SET(&diff_opts, RECURSIVE);
416 diff_opts.detect_rename = DIFF_DETECT_RENAME;
417 diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;
418 diff_opts.single_follow = origin->path;
419 paths[0] = NULL;
420 diff_tree_setup_paths(paths, &diff_opts);
421 if (diff_setup_done(&diff_opts) < 0)
422 die("diff-setup");
424 if (is_null_sha1(origin->commit->object.sha1))
425 do_diff_cache(parent->tree->object.sha1, &diff_opts);
426 else
427 diff_tree_sha1(parent->tree->object.sha1,
428 origin->commit->tree->object.sha1,
429 "", &diff_opts);
430 diffcore_std(&diff_opts);
432 for (i = 0; i < diff_queued_diff.nr; i++) {
433 struct diff_filepair *p = diff_queued_diff.queue[i];
434 if ((p->status == 'R' || p->status == 'C') &&
435 !strcmp(p->two->path, origin->path)) {
436 porigin = get_origin(sb, parent, p->one->path);
437 hashcpy(porigin->blob_sha1, p->one->sha1);
438 break;
441 diff_flush(&diff_opts);
442 diff_tree_release_paths(&diff_opts);
443 return porigin;
447 * Parsing of patch chunks...
449 struct chunk {
450 /* line number in postimage; up to but not including this
451 * line is the same as preimage
453 int same;
455 /* preimage line number after this chunk */
456 int p_next;
458 /* postimage line number after this chunk */
459 int t_next;
462 struct patch {
463 struct chunk *chunks;
464 int num;
467 struct blame_diff_state {
468 struct xdiff_emit_state xm;
469 struct patch *ret;
470 unsigned hunk_post_context;
471 unsigned hunk_in_pre_context : 1;
474 static void process_u_diff(void *state_, char *line, unsigned long len)
476 struct blame_diff_state *state = state_;
477 struct chunk *chunk;
478 int off1, off2, len1, len2, num;
480 num = state->ret->num;
481 if (len < 4 || line[0] != '@' || line[1] != '@') {
482 if (state->hunk_in_pre_context && line[0] == ' ')
483 state->ret->chunks[num - 1].same++;
484 else {
485 state->hunk_in_pre_context = 0;
486 if (line[0] == ' ')
487 state->hunk_post_context++;
488 else
489 state->hunk_post_context = 0;
491 return;
494 if (num && state->hunk_post_context) {
495 chunk = &state->ret->chunks[num - 1];
496 chunk->p_next -= state->hunk_post_context;
497 chunk->t_next -= state->hunk_post_context;
499 state->ret->num = ++num;
500 state->ret->chunks = xrealloc(state->ret->chunks,
501 sizeof(struct chunk) * num);
502 chunk = &state->ret->chunks[num - 1];
503 if (parse_hunk_header(line, len, &off1, &len1, &off2, &len2)) {
504 state->ret->num--;
505 return;
508 /* Line numbers in patch output are one based. */
509 off1--;
510 off2--;
512 chunk->same = len2 ? off2 : (off2 + 1);
514 chunk->p_next = off1 + (len1 ? len1 : 1);
515 chunk->t_next = chunk->same + len2;
516 state->hunk_in_pre_context = 1;
517 state->hunk_post_context = 0;
520 static struct patch *compare_buffer(mmfile_t *file_p, mmfile_t *file_o,
521 int context)
523 struct blame_diff_state state;
524 xpparam_t xpp;
525 xdemitconf_t xecfg;
526 xdemitcb_t ecb;
528 xpp.flags = xdl_opts;
529 memset(&xecfg, 0, sizeof(xecfg));
530 xecfg.ctxlen = context;
531 ecb.outf = xdiff_outf;
532 ecb.priv = &state;
533 memset(&state, 0, sizeof(state));
534 state.xm.consume = process_u_diff;
535 state.ret = xmalloc(sizeof(struct patch));
536 state.ret->chunks = NULL;
537 state.ret->num = 0;
539 xdi_diff(file_p, file_o, &xpp, &xecfg, &ecb);
541 if (state.ret->num) {
542 struct chunk *chunk;
543 chunk = &state.ret->chunks[state.ret->num - 1];
544 chunk->p_next -= state.hunk_post_context;
545 chunk->t_next -= state.hunk_post_context;
547 return state.ret;
551 * Run diff between two origins and grab the patch output, so that
552 * we can pass blame for lines origin is currently suspected for
553 * to its parent.
555 static struct patch *get_patch(struct origin *parent, struct origin *origin)
557 mmfile_t file_p, file_o;
558 struct patch *patch;
560 fill_origin_blob(parent, &file_p);
561 fill_origin_blob(origin, &file_o);
562 if (!file_p.ptr || !file_o.ptr)
563 return NULL;
564 patch = compare_buffer(&file_p, &file_o, 0);
565 num_get_patch++;
566 return patch;
569 static void free_patch(struct patch *p)
571 free(p->chunks);
572 free(p);
576 * Link in a new blame entry to the scoreboard. Entries that cover the
577 * same line range have been removed from the scoreboard previously.
579 static void add_blame_entry(struct scoreboard *sb, struct blame_entry *e)
581 struct blame_entry *ent, *prev = NULL;
583 origin_incref(e->suspect);
585 for (ent = sb->ent; ent && ent->lno < e->lno; ent = ent->next)
586 prev = ent;
588 /* prev, if not NULL, is the last one that is below e */
589 e->prev = prev;
590 if (prev) {
591 e->next = prev->next;
592 prev->next = e;
594 else {
595 e->next = sb->ent;
596 sb->ent = e;
598 if (e->next)
599 e->next->prev = e;
603 * src typically is on-stack; we want to copy the information in it to
604 * a malloced blame_entry that is already on the linked list of the
605 * scoreboard. The origin of dst loses a refcnt while the origin of src
606 * gains one.
608 static void dup_entry(struct blame_entry *dst, struct blame_entry *src)
610 struct blame_entry *p, *n;
612 p = dst->prev;
613 n = dst->next;
614 origin_incref(src->suspect);
615 origin_decref(dst->suspect);
616 memcpy(dst, src, sizeof(*src));
617 dst->prev = p;
618 dst->next = n;
619 dst->score = 0;
622 static const char *nth_line(struct scoreboard *sb, int lno)
624 return sb->final_buf + sb->lineno[lno];
628 * It is known that lines between tlno to same came from parent, and e
629 * has an overlap with that range. it also is known that parent's
630 * line plno corresponds to e's line tlno.
632 * <---- e ----->
633 * <------>
634 * <------------>
635 * <------------>
636 * <------------------>
638 * Split e into potentially three parts; before this chunk, the chunk
639 * to be blamed for the parent, and after that portion.
641 static void split_overlap(struct blame_entry *split,
642 struct blame_entry *e,
643 int tlno, int plno, int same,
644 struct origin *parent)
646 int chunk_end_lno;
647 memset(split, 0, sizeof(struct blame_entry [3]));
649 if (e->s_lno < tlno) {
650 /* there is a pre-chunk part not blamed on parent */
651 split[0].suspect = origin_incref(e->suspect);
652 split[0].lno = e->lno;
653 split[0].s_lno = e->s_lno;
654 split[0].num_lines = tlno - e->s_lno;
655 split[1].lno = e->lno + tlno - e->s_lno;
656 split[1].s_lno = plno;
658 else {
659 split[1].lno = e->lno;
660 split[1].s_lno = plno + (e->s_lno - tlno);
663 if (same < e->s_lno + e->num_lines) {
664 /* there is a post-chunk part not blamed on parent */
665 split[2].suspect = origin_incref(e->suspect);
666 split[2].lno = e->lno + (same - e->s_lno);
667 split[2].s_lno = e->s_lno + (same - e->s_lno);
668 split[2].num_lines = e->s_lno + e->num_lines - same;
669 chunk_end_lno = split[2].lno;
671 else
672 chunk_end_lno = e->lno + e->num_lines;
673 split[1].num_lines = chunk_end_lno - split[1].lno;
676 * if it turns out there is nothing to blame the parent for,
677 * forget about the splitting. !split[1].suspect signals this.
679 if (split[1].num_lines < 1)
680 return;
681 split[1].suspect = origin_incref(parent);
685 * split_overlap() divided an existing blame e into up to three parts
686 * in split. Adjust the linked list of blames in the scoreboard to
687 * reflect the split.
689 static void split_blame(struct scoreboard *sb,
690 struct blame_entry *split,
691 struct blame_entry *e)
693 struct blame_entry *new_entry;
695 if (split[0].suspect && split[2].suspect) {
696 /* The first part (reuse storage for the existing entry e) */
697 dup_entry(e, &split[0]);
699 /* The last part -- me */
700 new_entry = xmalloc(sizeof(*new_entry));
701 memcpy(new_entry, &(split[2]), sizeof(struct blame_entry));
702 add_blame_entry(sb, new_entry);
704 /* ... and the middle part -- parent */
705 new_entry = xmalloc(sizeof(*new_entry));
706 memcpy(new_entry, &(split[1]), sizeof(struct blame_entry));
707 add_blame_entry(sb, new_entry);
709 else if (!split[0].suspect && !split[2].suspect)
711 * The parent covers the entire area; reuse storage for
712 * e and replace it with the parent.
714 dup_entry(e, &split[1]);
715 else if (split[0].suspect) {
716 /* me and then parent */
717 dup_entry(e, &split[0]);
719 new_entry = xmalloc(sizeof(*new_entry));
720 memcpy(new_entry, &(split[1]), sizeof(struct blame_entry));
721 add_blame_entry(sb, new_entry);
723 else {
724 /* parent and then me */
725 dup_entry(e, &split[1]);
727 new_entry = xmalloc(sizeof(*new_entry));
728 memcpy(new_entry, &(split[2]), sizeof(struct blame_entry));
729 add_blame_entry(sb, new_entry);
732 if (DEBUG) { /* sanity */
733 struct blame_entry *ent;
734 int lno = sb->ent->lno, corrupt = 0;
736 for (ent = sb->ent; ent; ent = ent->next) {
737 if (lno != ent->lno)
738 corrupt = 1;
739 if (ent->s_lno < 0)
740 corrupt = 1;
741 lno += ent->num_lines;
743 if (corrupt) {
744 lno = sb->ent->lno;
745 for (ent = sb->ent; ent; ent = ent->next) {
746 printf("L %8d l %8d n %8d\n",
747 lno, ent->lno, ent->num_lines);
748 lno = ent->lno + ent->num_lines;
750 die("oops");
756 * After splitting the blame, the origins used by the
757 * on-stack blame_entry should lose one refcnt each.
759 static void decref_split(struct blame_entry *split)
761 int i;
763 for (i = 0; i < 3; i++)
764 origin_decref(split[i].suspect);
768 * Helper for blame_chunk(). blame_entry e is known to overlap with
769 * the patch hunk; split it and pass blame to the parent.
771 static void blame_overlap(struct scoreboard *sb, struct blame_entry *e,
772 int tlno, int plno, int same,
773 struct origin *parent)
775 struct blame_entry split[3];
777 split_overlap(split, e, tlno, plno, same, parent);
778 if (split[1].suspect)
779 split_blame(sb, split, e);
780 decref_split(split);
784 * Find the line number of the last line the target is suspected for.
786 static int find_last_in_target(struct scoreboard *sb, struct origin *target)
788 struct blame_entry *e;
789 int last_in_target = -1;
791 for (e = sb->ent; e; e = e->next) {
792 if (e->guilty || !same_suspect(e->suspect, target))
793 continue;
794 if (last_in_target < e->s_lno + e->num_lines)
795 last_in_target = e->s_lno + e->num_lines;
797 return last_in_target;
801 * Process one hunk from the patch between the current suspect for
802 * blame_entry e and its parent. Find and split the overlap, and
803 * pass blame to the overlapping part to the parent.
805 static void blame_chunk(struct scoreboard *sb,
806 int tlno, int plno, int same,
807 struct origin *target, struct origin *parent)
809 struct blame_entry *e;
811 for (e = sb->ent; e; e = e->next) {
812 if (e->guilty || !same_suspect(e->suspect, target))
813 continue;
814 if (same <= e->s_lno)
815 continue;
816 if (tlno < e->s_lno + e->num_lines)
817 blame_overlap(sb, e, tlno, plno, same, parent);
822 * We are looking at the origin 'target' and aiming to pass blame
823 * for the lines it is suspected to its parent. Run diff to find
824 * which lines came from parent and pass blame for them.
826 static int pass_blame_to_parent(struct scoreboard *sb,
827 struct origin *target,
828 struct origin *parent)
830 int i, last_in_target, plno, tlno;
831 struct patch *patch;
833 last_in_target = find_last_in_target(sb, target);
834 if (last_in_target < 0)
835 return 1; /* nothing remains for this target */
837 patch = get_patch(parent, target);
838 plno = tlno = 0;
839 for (i = 0; i < patch->num; i++) {
840 struct chunk *chunk = &patch->chunks[i];
842 blame_chunk(sb, tlno, plno, chunk->same, target, parent);
843 plno = chunk->p_next;
844 tlno = chunk->t_next;
846 /* The rest (i.e. anything after tlno) are the same as the parent */
847 blame_chunk(sb, tlno, plno, last_in_target, target, parent);
849 free_patch(patch);
850 return 0;
854 * The lines in blame_entry after splitting blames many times can become
855 * very small and trivial, and at some point it becomes pointless to
856 * blame the parents. E.g. "\t\t}\n\t}\n\n" appears everywhere in any
857 * ordinary C program, and it is not worth to say it was copied from
858 * totally unrelated file in the parent.
860 * Compute how trivial the lines in the blame_entry are.
862 static unsigned ent_score(struct scoreboard *sb, struct blame_entry *e)
864 unsigned score;
865 const char *cp, *ep;
867 if (e->score)
868 return e->score;
870 score = 1;
871 cp = nth_line(sb, e->lno);
872 ep = nth_line(sb, e->lno + e->num_lines);
873 while (cp < ep) {
874 unsigned ch = *((unsigned char *)cp);
875 if (isalnum(ch))
876 score++;
877 cp++;
879 e->score = score;
880 return score;
884 * best_so_far[] and this[] are both a split of an existing blame_entry
885 * that passes blame to the parent. Maintain best_so_far the best split
886 * so far, by comparing this and best_so_far and copying this into
887 * bst_so_far as needed.
889 static void copy_split_if_better(struct scoreboard *sb,
890 struct blame_entry *best_so_far,
891 struct blame_entry *this)
893 int i;
895 if (!this[1].suspect)
896 return;
897 if (best_so_far[1].suspect) {
898 if (ent_score(sb, &this[1]) < ent_score(sb, &best_so_far[1]))
899 return;
902 for (i = 0; i < 3; i++)
903 origin_incref(this[i].suspect);
904 decref_split(best_so_far);
905 memcpy(best_so_far, this, sizeof(struct blame_entry [3]));
909 * We are looking at a part of the final image represented by
910 * ent (tlno and same are offset by ent->s_lno).
911 * tlno is where we are looking at in the final image.
912 * up to (but not including) same match preimage.
913 * plno is where we are looking at in the preimage.
915 * <-------------- final image ---------------------->
916 * <------ent------>
917 * ^tlno ^same
918 * <---------preimage----->
919 * ^plno
921 * All line numbers are 0-based.
923 static void handle_split(struct scoreboard *sb,
924 struct blame_entry *ent,
925 int tlno, int plno, int same,
926 struct origin *parent,
927 struct blame_entry *split)
929 if (ent->num_lines <= tlno)
930 return;
931 if (tlno < same) {
932 struct blame_entry this[3];
933 tlno += ent->s_lno;
934 same += ent->s_lno;
935 split_overlap(this, ent, tlno, plno, same, parent);
936 copy_split_if_better(sb, split, this);
937 decref_split(this);
942 * Find the lines from parent that are the same as ent so that
943 * we can pass blames to it. file_p has the blob contents for
944 * the parent.
946 static void find_copy_in_blob(struct scoreboard *sb,
947 struct blame_entry *ent,
948 struct origin *parent,
949 struct blame_entry *split,
950 mmfile_t *file_p)
952 const char *cp;
953 int cnt;
954 mmfile_t file_o;
955 struct patch *patch;
956 int i, plno, tlno;
959 * Prepare mmfile that contains only the lines in ent.
961 cp = nth_line(sb, ent->lno);
962 file_o.ptr = (char*) cp;
963 cnt = ent->num_lines;
965 while (cnt && cp < sb->final_buf + sb->final_buf_size) {
966 if (*cp++ == '\n')
967 cnt--;
969 file_o.size = cp - file_o.ptr;
971 patch = compare_buffer(file_p, &file_o, 1);
974 * file_o is a part of final image we are annotating.
975 * file_p partially may match that image.
977 memset(split, 0, sizeof(struct blame_entry [3]));
978 plno = tlno = 0;
979 for (i = 0; i < patch->num; i++) {
980 struct chunk *chunk = &patch->chunks[i];
982 handle_split(sb, ent, tlno, plno, chunk->same, parent, split);
983 plno = chunk->p_next;
984 tlno = chunk->t_next;
986 /* remainder, if any, all match the preimage */
987 handle_split(sb, ent, tlno, plno, ent->num_lines, parent, split);
988 free_patch(patch);
992 * See if lines currently target is suspected for can be attributed to
993 * parent.
995 static int find_move_in_parent(struct scoreboard *sb,
996 struct origin *target,
997 struct origin *parent)
999 int last_in_target, made_progress;
1000 struct blame_entry *e, split[3];
1001 mmfile_t file_p;
1003 last_in_target = find_last_in_target(sb, target);
1004 if (last_in_target < 0)
1005 return 1; /* nothing remains for this target */
1007 fill_origin_blob(parent, &file_p);
1008 if (!file_p.ptr)
1009 return 0;
1011 made_progress = 1;
1012 while (made_progress) {
1013 made_progress = 0;
1014 for (e = sb->ent; e; e = e->next) {
1015 if (e->guilty || !same_suspect(e->suspect, target) ||
1016 ent_score(sb, e) < blame_move_score)
1017 continue;
1018 find_copy_in_blob(sb, e, parent, split, &file_p);
1019 if (split[1].suspect &&
1020 blame_move_score < ent_score(sb, &split[1])) {
1021 split_blame(sb, split, e);
1022 made_progress = 1;
1024 decref_split(split);
1027 return 0;
1030 struct blame_list {
1031 struct blame_entry *ent;
1032 struct blame_entry split[3];
1036 * Count the number of entries the target is suspected for,
1037 * and prepare a list of entry and the best split.
1039 static struct blame_list *setup_blame_list(struct scoreboard *sb,
1040 struct origin *target,
1041 int min_score,
1042 int *num_ents_p)
1044 struct blame_entry *e;
1045 int num_ents, i;
1046 struct blame_list *blame_list = NULL;
1048 for (e = sb->ent, num_ents = 0; e; e = e->next)
1049 if (!e->scanned && !e->guilty &&
1050 same_suspect(e->suspect, target) &&
1051 min_score < ent_score(sb, e))
1052 num_ents++;
1053 if (num_ents) {
1054 blame_list = xcalloc(num_ents, sizeof(struct blame_list));
1055 for (e = sb->ent, i = 0; e; e = e->next)
1056 if (!e->scanned && !e->guilty &&
1057 same_suspect(e->suspect, target) &&
1058 min_score < ent_score(sb, e))
1059 blame_list[i++].ent = e;
1061 *num_ents_p = num_ents;
1062 return blame_list;
1066 * Reset the scanned status on all entries.
1068 static void reset_scanned_flag(struct scoreboard *sb)
1070 struct blame_entry *e;
1071 for (e = sb->ent; e; e = e->next)
1072 e->scanned = 0;
1076 * For lines target is suspected for, see if we can find code movement
1077 * across file boundary from the parent commit. porigin is the path
1078 * in the parent we already tried.
1080 static int find_copy_in_parent(struct scoreboard *sb,
1081 struct origin *target,
1082 struct commit *parent,
1083 struct origin *porigin,
1084 int opt)
1086 struct diff_options diff_opts;
1087 const char *paths[1];
1088 int i, j;
1089 int retval;
1090 struct blame_list *blame_list;
1091 int num_ents;
1093 blame_list = setup_blame_list(sb, target, blame_copy_score, &num_ents);
1094 if (!blame_list)
1095 return 1; /* nothing remains for this target */
1097 diff_setup(&diff_opts);
1098 DIFF_OPT_SET(&diff_opts, RECURSIVE);
1099 diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;
1101 paths[0] = NULL;
1102 diff_tree_setup_paths(paths, &diff_opts);
1103 if (diff_setup_done(&diff_opts) < 0)
1104 die("diff-setup");
1106 /* Try "find copies harder" on new path if requested;
1107 * we do not want to use diffcore_rename() actually to
1108 * match things up; find_copies_harder is set only to
1109 * force diff_tree_sha1() to feed all filepairs to diff_queue,
1110 * and this code needs to be after diff_setup_done(), which
1111 * usually makes find-copies-harder imply copy detection.
1113 if ((opt & PICKAXE_BLAME_COPY_HARDEST)
1114 || ((opt & PICKAXE_BLAME_COPY_HARDER)
1115 && (!porigin || strcmp(target->path, porigin->path))))
1116 DIFF_OPT_SET(&diff_opts, FIND_COPIES_HARDER);
1118 if (is_null_sha1(target->commit->object.sha1))
1119 do_diff_cache(parent->tree->object.sha1, &diff_opts);
1120 else
1121 diff_tree_sha1(parent->tree->object.sha1,
1122 target->commit->tree->object.sha1,
1123 "", &diff_opts);
1125 if (!DIFF_OPT_TST(&diff_opts, FIND_COPIES_HARDER))
1126 diffcore_std(&diff_opts);
1128 retval = 0;
1129 while (1) {
1130 int made_progress = 0;
1132 for (i = 0; i < diff_queued_diff.nr; i++) {
1133 struct diff_filepair *p = diff_queued_diff.queue[i];
1134 struct origin *norigin;
1135 mmfile_t file_p;
1136 struct blame_entry this[3];
1138 if (!DIFF_FILE_VALID(p->one))
1139 continue; /* does not exist in parent */
1140 if (porigin && !strcmp(p->one->path, porigin->path))
1141 /* find_move already dealt with this path */
1142 continue;
1144 norigin = get_origin(sb, parent, p->one->path);
1145 hashcpy(norigin->blob_sha1, p->one->sha1);
1146 fill_origin_blob(norigin, &file_p);
1147 if (!file_p.ptr)
1148 continue;
1150 for (j = 0; j < num_ents; j++) {
1151 find_copy_in_blob(sb, blame_list[j].ent,
1152 norigin, this, &file_p);
1153 copy_split_if_better(sb, blame_list[j].split,
1154 this);
1155 decref_split(this);
1157 origin_decref(norigin);
1160 for (j = 0; j < num_ents; j++) {
1161 struct blame_entry *split = blame_list[j].split;
1162 if (split[1].suspect &&
1163 blame_copy_score < ent_score(sb, &split[1])) {
1164 split_blame(sb, split, blame_list[j].ent);
1165 made_progress = 1;
1167 else
1168 blame_list[j].ent->scanned = 1;
1169 decref_split(split);
1171 free(blame_list);
1173 if (!made_progress)
1174 break;
1175 blame_list = setup_blame_list(sb, target, blame_copy_score, &num_ents);
1176 if (!blame_list) {
1177 retval = 1;
1178 break;
1181 reset_scanned_flag(sb);
1182 diff_flush(&diff_opts);
1183 diff_tree_release_paths(&diff_opts);
1184 return retval;
1188 * The blobs of origin and porigin exactly match, so everything
1189 * origin is suspected for can be blamed on the parent.
1191 static void pass_whole_blame(struct scoreboard *sb,
1192 struct origin *origin, struct origin *porigin)
1194 struct blame_entry *e;
1196 if (!porigin->file.ptr && origin->file.ptr) {
1197 /* Steal its file */
1198 porigin->file = origin->file;
1199 origin->file.ptr = NULL;
1201 for (e = sb->ent; e; e = e->next) {
1202 if (!same_suspect(e->suspect, origin))
1203 continue;
1204 origin_incref(porigin);
1205 origin_decref(e->suspect);
1206 e->suspect = porigin;
1211 * We pass blame from the current commit to its parents. We keep saying
1212 * "parent" (and "porigin"), but what we mean is to find scapegoat to
1213 * exonerate ourselves.
1215 static struct commit_list *first_scapegoat(struct rev_info *revs, struct commit *commit)
1217 if (!reverse)
1218 return commit->parents;
1219 return lookup_decoration(&revs->children, &commit->object);
1222 static int num_scapegoats(struct rev_info *revs, struct commit *commit)
1224 int cnt;
1225 struct commit_list *l = first_scapegoat(revs, commit);
1226 for (cnt = 0; l; l = l->next)
1227 cnt++;
1228 return cnt;
1231 #define MAXSG 16
1233 static void pass_blame(struct scoreboard *sb, struct origin *origin, int opt)
1235 struct rev_info *revs = sb->revs;
1236 int i, pass, num_sg;
1237 struct commit *commit = origin->commit;
1238 struct commit_list *sg;
1239 struct origin *sg_buf[MAXSG];
1240 struct origin *porigin, **sg_origin = sg_buf;
1242 num_sg = num_scapegoats(revs, commit);
1243 if (!num_sg)
1244 goto finish;
1245 else if (num_sg < ARRAY_SIZE(sg_buf))
1246 memset(sg_buf, 0, sizeof(sg_buf));
1247 else
1248 sg_origin = xcalloc(num_sg, sizeof(*sg_origin));
1251 * The first pass looks for unrenamed path to optimize for
1252 * common cases, then we look for renames in the second pass.
1254 for (pass = 0; pass < 2; pass++) {
1255 struct origin *(*find)(struct scoreboard *,
1256 struct commit *, struct origin *);
1257 find = pass ? find_rename : find_origin;
1259 for (i = 0, sg = first_scapegoat(revs, commit);
1260 i < num_sg && sg;
1261 sg = sg->next, i++) {
1262 struct commit *p = sg->item;
1263 int j, same;
1265 if (sg_origin[i])
1266 continue;
1267 if (parse_commit(p))
1268 continue;
1269 porigin = find(sb, p, origin);
1270 if (!porigin)
1271 continue;
1272 if (!hashcmp(porigin->blob_sha1, origin->blob_sha1)) {
1273 pass_whole_blame(sb, origin, porigin);
1274 origin_decref(porigin);
1275 goto finish;
1277 for (j = same = 0; j < i; j++)
1278 if (sg_origin[j] &&
1279 !hashcmp(sg_origin[j]->blob_sha1,
1280 porigin->blob_sha1)) {
1281 same = 1;
1282 break;
1284 if (!same)
1285 sg_origin[i] = porigin;
1286 else
1287 origin_decref(porigin);
1291 num_commits++;
1292 for (i = 0, sg = first_scapegoat(revs, commit);
1293 i < num_sg && sg;
1294 sg = sg->next, i++) {
1295 struct origin *porigin = sg_origin[i];
1296 if (!porigin)
1297 continue;
1298 if (pass_blame_to_parent(sb, origin, porigin))
1299 goto finish;
1303 * Optionally find moves in parents' files.
1305 if (opt & PICKAXE_BLAME_MOVE)
1306 for (i = 0, sg = first_scapegoat(revs, commit);
1307 i < num_sg && sg;
1308 sg = sg->next, i++) {
1309 struct origin *porigin = sg_origin[i];
1310 if (!porigin)
1311 continue;
1312 if (find_move_in_parent(sb, origin, porigin))
1313 goto finish;
1317 * Optionally find copies from parents' files.
1319 if (opt & PICKAXE_BLAME_COPY)
1320 for (i = 0, sg = first_scapegoat(revs, commit);
1321 i < num_sg && sg;
1322 sg = sg->next, i++) {
1323 struct origin *porigin = sg_origin[i];
1324 if (find_copy_in_parent(sb, origin, sg->item,
1325 porigin, opt))
1326 goto finish;
1329 finish:
1330 for (i = 0; i < num_sg; i++) {
1331 if (sg_origin[i]) {
1332 drop_origin_blob(sg_origin[i]);
1333 origin_decref(sg_origin[i]);
1336 drop_origin_blob(origin);
1337 if (sg_buf != sg_origin)
1338 free(sg_origin);
1342 * Information on commits, used for output.
1344 struct commit_info
1346 const char *author;
1347 const char *author_mail;
1348 unsigned long author_time;
1349 const char *author_tz;
1351 /* filled only when asked for details */
1352 const char *committer;
1353 const char *committer_mail;
1354 unsigned long committer_time;
1355 const char *committer_tz;
1357 const char *summary;
1361 * Parse author/committer line in the commit object buffer
1363 static void get_ac_line(const char *inbuf, const char *what,
1364 int bufsz, char *person, const char **mail,
1365 unsigned long *time, const char **tz)
1367 int len, tzlen, maillen;
1368 char *tmp, *endp, *timepos;
1370 tmp = strstr(inbuf, what);
1371 if (!tmp)
1372 goto error_out;
1373 tmp += strlen(what);
1374 endp = strchr(tmp, '\n');
1375 if (!endp)
1376 len = strlen(tmp);
1377 else
1378 len = endp - tmp;
1379 if (bufsz <= len) {
1380 error_out:
1381 /* Ugh */
1382 *mail = *tz = "(unknown)";
1383 *time = 0;
1384 return;
1386 memcpy(person, tmp, len);
1388 tmp = person;
1389 tmp += len;
1390 *tmp = 0;
1391 while (*tmp != ' ')
1392 tmp--;
1393 *tz = tmp+1;
1394 tzlen = (person+len)-(tmp+1);
1396 *tmp = 0;
1397 while (*tmp != ' ')
1398 tmp--;
1399 *time = strtoul(tmp, NULL, 10);
1400 timepos = tmp;
1402 *tmp = 0;
1403 while (*tmp != ' ')
1404 tmp--;
1405 *mail = tmp + 1;
1406 *tmp = 0;
1407 maillen = timepos - tmp;
1409 if (!mailmap.nr)
1410 return;
1413 * mailmap expansion may make the name longer.
1414 * make room by pushing stuff down.
1416 tmp = person + bufsz - (tzlen + 1);
1417 memmove(tmp, *tz, tzlen);
1418 tmp[tzlen] = 0;
1419 *tz = tmp;
1421 tmp = tmp - (maillen + 1);
1422 memmove(tmp, *mail, maillen);
1423 tmp[maillen] = 0;
1424 *mail = tmp;
1427 * Now, convert e-mail using mailmap
1429 map_email(&mailmap, tmp + 1, person, tmp-person-1);
1432 static void get_commit_info(struct commit *commit,
1433 struct commit_info *ret,
1434 int detailed)
1436 int len;
1437 char *tmp, *endp;
1438 static char author_buf[1024];
1439 static char committer_buf[1024];
1440 static char summary_buf[1024];
1443 * We've operated without save_commit_buffer, so
1444 * we now need to populate them for output.
1446 if (!commit->buffer) {
1447 enum object_type type;
1448 unsigned long size;
1449 commit->buffer =
1450 read_sha1_file(commit->object.sha1, &type, &size);
1451 if (!commit->buffer)
1452 die("Cannot read commit %s",
1453 sha1_to_hex(commit->object.sha1));
1455 ret->author = author_buf;
1456 get_ac_line(commit->buffer, "\nauthor ",
1457 sizeof(author_buf), author_buf, &ret->author_mail,
1458 &ret->author_time, &ret->author_tz);
1460 if (!detailed)
1461 return;
1463 ret->committer = committer_buf;
1464 get_ac_line(commit->buffer, "\ncommitter ",
1465 sizeof(committer_buf), committer_buf, &ret->committer_mail,
1466 &ret->committer_time, &ret->committer_tz);
1468 ret->summary = summary_buf;
1469 tmp = strstr(commit->buffer, "\n\n");
1470 if (!tmp) {
1471 error_out:
1472 sprintf(summary_buf, "(%s)", sha1_to_hex(commit->object.sha1));
1473 return;
1475 tmp += 2;
1476 endp = strchr(tmp, '\n');
1477 if (!endp)
1478 endp = tmp + strlen(tmp);
1479 len = endp - tmp;
1480 if (len >= sizeof(summary_buf) || len == 0)
1481 goto error_out;
1482 memcpy(summary_buf, tmp, len);
1483 summary_buf[len] = 0;
1487 * To allow LF and other nonportable characters in pathnames,
1488 * they are c-style quoted as needed.
1490 static void write_filename_info(const char *path)
1492 printf("filename ");
1493 write_name_quoted(path, stdout, '\n');
1497 * The blame_entry is found to be guilty for the range. Mark it
1498 * as such, and show it in incremental output.
1500 static void found_guilty_entry(struct blame_entry *ent)
1502 if (ent->guilty)
1503 return;
1504 ent->guilty = 1;
1505 if (incremental) {
1506 struct origin *suspect = ent->suspect;
1508 printf("%s %d %d %d\n",
1509 sha1_to_hex(suspect->commit->object.sha1),
1510 ent->s_lno + 1, ent->lno + 1, ent->num_lines);
1511 if (!(suspect->commit->object.flags & METAINFO_SHOWN)) {
1512 struct commit_info ci;
1513 suspect->commit->object.flags |= METAINFO_SHOWN;
1514 get_commit_info(suspect->commit, &ci, 1);
1515 printf("author %s\n", ci.author);
1516 printf("author-mail %s\n", ci.author_mail);
1517 printf("author-time %lu\n", ci.author_time);
1518 printf("author-tz %s\n", ci.author_tz);
1519 printf("committer %s\n", ci.committer);
1520 printf("committer-mail %s\n", ci.committer_mail);
1521 printf("committer-time %lu\n", ci.committer_time);
1522 printf("committer-tz %s\n", ci.committer_tz);
1523 printf("summary %s\n", ci.summary);
1524 if (suspect->commit->object.flags & UNINTERESTING)
1525 printf("boundary\n");
1527 write_filename_info(suspect->path);
1528 maybe_flush_or_die(stdout, "stdout");
1533 * The main loop -- while the scoreboard has lines whose true origin
1534 * is still unknown, pick one blame_entry, and allow its current
1535 * suspect to pass blames to its parents.
1537 static void assign_blame(struct scoreboard *sb, int opt)
1539 struct rev_info *revs = sb->revs;
1541 while (1) {
1542 struct blame_entry *ent;
1543 struct commit *commit;
1544 struct origin *suspect = NULL;
1546 /* find one suspect to break down */
1547 for (ent = sb->ent; !suspect && ent; ent = ent->next)
1548 if (!ent->guilty)
1549 suspect = ent->suspect;
1550 if (!suspect)
1551 return; /* all done */
1554 * We will use this suspect later in the loop,
1555 * so hold onto it in the meantime.
1557 origin_incref(suspect);
1558 commit = suspect->commit;
1559 if (!commit->object.parsed)
1560 parse_commit(commit);
1561 if (reverse ||
1562 (!(commit->object.flags & UNINTERESTING) &&
1563 !(revs->max_age != -1 && commit->date < revs->max_age)))
1564 pass_blame(sb, suspect, opt);
1565 else {
1566 commit->object.flags |= UNINTERESTING;
1567 if (commit->object.parsed)
1568 mark_parents_uninteresting(commit);
1570 /* treat root commit as boundary */
1571 if (!commit->parents && !show_root)
1572 commit->object.flags |= UNINTERESTING;
1574 /* Take responsibility for the remaining entries */
1575 for (ent = sb->ent; ent; ent = ent->next)
1576 if (same_suspect(ent->suspect, suspect))
1577 found_guilty_entry(ent);
1578 origin_decref(suspect);
1580 if (DEBUG) /* sanity */
1581 sanity_check_refcnt(sb);
1585 static const char *format_time(unsigned long time, const char *tz_str,
1586 int show_raw_time)
1588 static char time_buf[128];
1589 time_t t = time;
1590 int minutes, tz;
1591 struct tm *tm;
1593 if (show_raw_time) {
1594 sprintf(time_buf, "%lu %s", time, tz_str);
1595 return time_buf;
1598 tz = atoi(tz_str);
1599 minutes = tz < 0 ? -tz : tz;
1600 minutes = (minutes / 100)*60 + (minutes % 100);
1601 minutes = tz < 0 ? -minutes : minutes;
1602 t = time + minutes * 60;
1603 tm = gmtime(&t);
1605 strftime(time_buf, sizeof(time_buf), "%Y-%m-%d %H:%M:%S ", tm);
1606 strcat(time_buf, tz_str);
1607 return time_buf;
1610 #define OUTPUT_ANNOTATE_COMPAT 001
1611 #define OUTPUT_LONG_OBJECT_NAME 002
1612 #define OUTPUT_RAW_TIMESTAMP 004
1613 #define OUTPUT_PORCELAIN 010
1614 #define OUTPUT_SHOW_NAME 020
1615 #define OUTPUT_SHOW_NUMBER 040
1616 #define OUTPUT_SHOW_SCORE 0100
1617 #define OUTPUT_NO_AUTHOR 0200
1619 static void emit_porcelain(struct scoreboard *sb, struct blame_entry *ent)
1621 int cnt;
1622 const char *cp;
1623 struct origin *suspect = ent->suspect;
1624 char hex[41];
1626 strcpy(hex, sha1_to_hex(suspect->commit->object.sha1));
1627 printf("%s%c%d %d %d\n",
1628 hex,
1629 ent->guilty ? ' ' : '*', // purely for debugging
1630 ent->s_lno + 1,
1631 ent->lno + 1,
1632 ent->num_lines);
1633 if (!(suspect->commit->object.flags & METAINFO_SHOWN)) {
1634 struct commit_info ci;
1635 suspect->commit->object.flags |= METAINFO_SHOWN;
1636 get_commit_info(suspect->commit, &ci, 1);
1637 printf("author %s\n", ci.author);
1638 printf("author-mail %s\n", ci.author_mail);
1639 printf("author-time %lu\n", ci.author_time);
1640 printf("author-tz %s\n", ci.author_tz);
1641 printf("committer %s\n", ci.committer);
1642 printf("committer-mail %s\n", ci.committer_mail);
1643 printf("committer-time %lu\n", ci.committer_time);
1644 printf("committer-tz %s\n", ci.committer_tz);
1645 write_filename_info(suspect->path);
1646 printf("summary %s\n", ci.summary);
1647 if (suspect->commit->object.flags & UNINTERESTING)
1648 printf("boundary\n");
1650 else if (suspect->commit->object.flags & MORE_THAN_ONE_PATH)
1651 write_filename_info(suspect->path);
1653 cp = nth_line(sb, ent->lno);
1654 for (cnt = 0; cnt < ent->num_lines; cnt++) {
1655 char ch;
1656 if (cnt)
1657 printf("%s %d %d\n", hex,
1658 ent->s_lno + 1 + cnt,
1659 ent->lno + 1 + cnt);
1660 putchar('\t');
1661 do {
1662 ch = *cp++;
1663 putchar(ch);
1664 } while (ch != '\n' &&
1665 cp < sb->final_buf + sb->final_buf_size);
1669 static void emit_other(struct scoreboard *sb, struct blame_entry *ent, int opt)
1671 int cnt;
1672 const char *cp;
1673 struct origin *suspect = ent->suspect;
1674 struct commit_info ci;
1675 char hex[41];
1676 int show_raw_time = !!(opt & OUTPUT_RAW_TIMESTAMP);
1678 get_commit_info(suspect->commit, &ci, 1);
1679 strcpy(hex, sha1_to_hex(suspect->commit->object.sha1));
1681 cp = nth_line(sb, ent->lno);
1682 for (cnt = 0; cnt < ent->num_lines; cnt++) {
1683 char ch;
1684 int length = (opt & OUTPUT_LONG_OBJECT_NAME) ? 40 : 8;
1686 if (suspect->commit->object.flags & UNINTERESTING) {
1687 if (blank_boundary)
1688 memset(hex, ' ', length);
1689 else if (!cmd_is_annotate) {
1690 length--;
1691 putchar('^');
1695 printf("%.*s", length, hex);
1696 if (opt & OUTPUT_ANNOTATE_COMPAT)
1697 printf("\t(%10s\t%10s\t%d)", ci.author,
1698 format_time(ci.author_time, ci.author_tz,
1699 show_raw_time),
1700 ent->lno + 1 + cnt);
1701 else {
1702 if (opt & OUTPUT_SHOW_SCORE)
1703 printf(" %*d %02d",
1704 max_score_digits, ent->score,
1705 ent->suspect->refcnt);
1706 if (opt & OUTPUT_SHOW_NAME)
1707 printf(" %-*.*s", longest_file, longest_file,
1708 suspect->path);
1709 if (opt & OUTPUT_SHOW_NUMBER)
1710 printf(" %*d", max_orig_digits,
1711 ent->s_lno + 1 + cnt);
1713 if (!(opt & OUTPUT_NO_AUTHOR))
1714 printf(" (%-*.*s %10s",
1715 longest_author, longest_author,
1716 ci.author,
1717 format_time(ci.author_time,
1718 ci.author_tz,
1719 show_raw_time));
1720 printf(" %*d) ",
1721 max_digits, ent->lno + 1 + cnt);
1723 do {
1724 ch = *cp++;
1725 putchar(ch);
1726 } while (ch != '\n' &&
1727 cp < sb->final_buf + sb->final_buf_size);
1731 static void output(struct scoreboard *sb, int option)
1733 struct blame_entry *ent;
1735 if (option & OUTPUT_PORCELAIN) {
1736 for (ent = sb->ent; ent; ent = ent->next) {
1737 struct blame_entry *oth;
1738 struct origin *suspect = ent->suspect;
1739 struct commit *commit = suspect->commit;
1740 if (commit->object.flags & MORE_THAN_ONE_PATH)
1741 continue;
1742 for (oth = ent->next; oth; oth = oth->next) {
1743 if ((oth->suspect->commit != commit) ||
1744 !strcmp(oth->suspect->path, suspect->path))
1745 continue;
1746 commit->object.flags |= MORE_THAN_ONE_PATH;
1747 break;
1752 for (ent = sb->ent; ent; ent = ent->next) {
1753 if (option & OUTPUT_PORCELAIN)
1754 emit_porcelain(sb, ent);
1755 else {
1756 emit_other(sb, ent, option);
1762 * To allow quick access to the contents of nth line in the
1763 * final image, prepare an index in the scoreboard.
1765 static int prepare_lines(struct scoreboard *sb)
1767 const char *buf = sb->final_buf;
1768 unsigned long len = sb->final_buf_size;
1769 int num = 0, incomplete = 0, bol = 1;
1771 if (len && buf[len-1] != '\n')
1772 incomplete++; /* incomplete line at the end */
1773 while (len--) {
1774 if (bol) {
1775 sb->lineno = xrealloc(sb->lineno,
1776 sizeof(int* ) * (num + 1));
1777 sb->lineno[num] = buf - sb->final_buf;
1778 bol = 0;
1780 if (*buf++ == '\n') {
1781 num++;
1782 bol = 1;
1785 sb->lineno = xrealloc(sb->lineno,
1786 sizeof(int* ) * (num + incomplete + 1));
1787 sb->lineno[num + incomplete] = buf - sb->final_buf;
1788 sb->num_lines = num + incomplete;
1789 return sb->num_lines;
1793 * Add phony grafts for use with -S; this is primarily to
1794 * support git-cvsserver that wants to give a linear history
1795 * to its clients.
1797 static int read_ancestry(const char *graft_file)
1799 FILE *fp = fopen(graft_file, "r");
1800 char buf[1024];
1801 if (!fp)
1802 return -1;
1803 while (fgets(buf, sizeof(buf), fp)) {
1804 /* The format is just "Commit Parent1 Parent2 ...\n" */
1805 int len = strlen(buf);
1806 struct commit_graft *graft = read_graft_line(buf, len);
1807 if (graft)
1808 register_commit_graft(graft, 0);
1810 fclose(fp);
1811 return 0;
1815 * How many columns do we need to show line numbers in decimal?
1817 static int lineno_width(int lines)
1819 int i, width;
1821 for (width = 1, i = 10; i <= lines + 1; width++)
1822 i *= 10;
1823 return width;
1827 * How many columns do we need to show line numbers, authors,
1828 * and filenames?
1830 static void find_alignment(struct scoreboard *sb, int *option)
1832 int longest_src_lines = 0;
1833 int longest_dst_lines = 0;
1834 unsigned largest_score = 0;
1835 struct blame_entry *e;
1837 for (e = sb->ent; e; e = e->next) {
1838 struct origin *suspect = e->suspect;
1839 struct commit_info ci;
1840 int num;
1842 if (strcmp(suspect->path, sb->path))
1843 *option |= OUTPUT_SHOW_NAME;
1844 num = strlen(suspect->path);
1845 if (longest_file < num)
1846 longest_file = num;
1847 if (!(suspect->commit->object.flags & METAINFO_SHOWN)) {
1848 suspect->commit->object.flags |= METAINFO_SHOWN;
1849 get_commit_info(suspect->commit, &ci, 1);
1850 num = strlen(ci.author);
1851 if (longest_author < num)
1852 longest_author = num;
1854 num = e->s_lno + e->num_lines;
1855 if (longest_src_lines < num)
1856 longest_src_lines = num;
1857 num = e->lno + e->num_lines;
1858 if (longest_dst_lines < num)
1859 longest_dst_lines = num;
1860 if (largest_score < ent_score(sb, e))
1861 largest_score = ent_score(sb, e);
1863 max_orig_digits = lineno_width(longest_src_lines);
1864 max_digits = lineno_width(longest_dst_lines);
1865 max_score_digits = lineno_width(largest_score);
1869 * For debugging -- origin is refcounted, and this asserts that
1870 * we do not underflow.
1872 static void sanity_check_refcnt(struct scoreboard *sb)
1874 int baa = 0;
1875 struct blame_entry *ent;
1877 for (ent = sb->ent; ent; ent = ent->next) {
1878 /* Nobody should have zero or negative refcnt */
1879 if (ent->suspect->refcnt <= 0) {
1880 fprintf(stderr, "%s in %s has negative refcnt %d\n",
1881 ent->suspect->path,
1882 sha1_to_hex(ent->suspect->commit->object.sha1),
1883 ent->suspect->refcnt);
1884 baa = 1;
1887 for (ent = sb->ent; ent; ent = ent->next) {
1888 /* Mark the ones that haven't been checked */
1889 if (0 < ent->suspect->refcnt)
1890 ent->suspect->refcnt = -ent->suspect->refcnt;
1892 for (ent = sb->ent; ent; ent = ent->next) {
1894 * ... then pick each and see if they have the the
1895 * correct refcnt.
1897 int found;
1898 struct blame_entry *e;
1899 struct origin *suspect = ent->suspect;
1901 if (0 < suspect->refcnt)
1902 continue;
1903 suspect->refcnt = -suspect->refcnt; /* Unmark */
1904 for (found = 0, e = sb->ent; e; e = e->next) {
1905 if (e->suspect != suspect)
1906 continue;
1907 found++;
1909 if (suspect->refcnt != found) {
1910 fprintf(stderr, "%s in %s has refcnt %d, not %d\n",
1911 ent->suspect->path,
1912 sha1_to_hex(ent->suspect->commit->object.sha1),
1913 ent->suspect->refcnt, found);
1914 baa = 2;
1917 if (baa) {
1918 int opt = 0160;
1919 find_alignment(sb, &opt);
1920 output(sb, opt);
1921 die("Baa %d!", baa);
1926 * Used for the command line parsing; check if the path exists
1927 * in the working tree.
1929 static int has_string_in_work_tree(const char *path)
1931 struct stat st;
1932 return !lstat(path, &st);
1935 static unsigned parse_score(const char *arg)
1937 char *end;
1938 unsigned long score = strtoul(arg, &end, 10);
1939 if (*end)
1940 return 0;
1941 return score;
1944 static const char *add_prefix(const char *prefix, const char *path)
1946 return prefix_path(prefix, prefix ? strlen(prefix) : 0, path);
1950 * Parsing of (comma separated) one item in the -L option
1952 static const char *parse_loc(const char *spec,
1953 struct scoreboard *sb, long lno,
1954 long begin, long *ret)
1956 char *term;
1957 const char *line;
1958 long num;
1959 int reg_error;
1960 regex_t regexp;
1961 regmatch_t match[1];
1963 /* Allow "-L <something>,+20" to mean starting at <something>
1964 * for 20 lines, or "-L <something>,-5" for 5 lines ending at
1965 * <something>.
1967 if (1 < begin && (spec[0] == '+' || spec[0] == '-')) {
1968 num = strtol(spec + 1, &term, 10);
1969 if (term != spec + 1) {
1970 if (spec[0] == '-')
1971 num = 0 - num;
1972 if (0 < num)
1973 *ret = begin + num - 2;
1974 else if (!num)
1975 *ret = begin;
1976 else
1977 *ret = begin + num;
1978 return term;
1980 return spec;
1982 num = strtol(spec, &term, 10);
1983 if (term != spec) {
1984 *ret = num;
1985 return term;
1987 if (spec[0] != '/')
1988 return spec;
1990 /* it could be a regexp of form /.../ */
1991 for (term = (char*) spec + 1; *term && *term != '/'; term++) {
1992 if (*term == '\\')
1993 term++;
1995 if (*term != '/')
1996 return spec;
1998 /* try [spec+1 .. term-1] as regexp */
1999 *term = 0;
2000 begin--; /* input is in human terms */
2001 line = nth_line(sb, begin);
2003 if (!(reg_error = regcomp(&regexp, spec + 1, REG_NEWLINE)) &&
2004 !(reg_error = regexec(&regexp, line, 1, match, 0))) {
2005 const char *cp = line + match[0].rm_so;
2006 const char *nline;
2008 while (begin++ < lno) {
2009 nline = nth_line(sb, begin);
2010 if (line <= cp && cp < nline)
2011 break;
2012 line = nline;
2014 *ret = begin;
2015 regfree(&regexp);
2016 *term++ = '/';
2017 return term;
2019 else {
2020 char errbuf[1024];
2021 regerror(reg_error, &regexp, errbuf, 1024);
2022 die("-L parameter '%s': %s", spec + 1, errbuf);
2027 * Parsing of -L option
2029 static void prepare_blame_range(struct scoreboard *sb,
2030 const char *bottomtop,
2031 long lno,
2032 long *bottom, long *top)
2034 const char *term;
2036 term = parse_loc(bottomtop, sb, lno, 1, bottom);
2037 if (*term == ',') {
2038 term = parse_loc(term + 1, sb, lno, *bottom + 1, top);
2039 if (*term)
2040 usage(blame_usage);
2042 if (*term)
2043 usage(blame_usage);
2046 static int git_blame_config(const char *var, const char *value, void *cb)
2048 if (!strcmp(var, "blame.showroot")) {
2049 show_root = git_config_bool(var, value);
2050 return 0;
2052 if (!strcmp(var, "blame.blankboundary")) {
2053 blank_boundary = git_config_bool(var, value);
2054 return 0;
2056 return git_default_config(var, value, cb);
2060 * Prepare a dummy commit that represents the work tree (or staged) item.
2061 * Note that annotating work tree item never works in the reverse.
2063 static struct commit *fake_working_tree_commit(const char *path, const char *contents_from)
2065 struct commit *commit;
2066 struct origin *origin;
2067 unsigned char head_sha1[20];
2068 struct strbuf buf;
2069 const char *ident;
2070 time_t now;
2071 int size, len;
2072 struct cache_entry *ce;
2073 unsigned mode;
2075 if (get_sha1("HEAD", head_sha1))
2076 die("No such ref: HEAD");
2078 time(&now);
2079 commit = xcalloc(1, sizeof(*commit));
2080 commit->parents = xcalloc(1, sizeof(*commit->parents));
2081 commit->parents->item = lookup_commit_reference(head_sha1);
2082 commit->object.parsed = 1;
2083 commit->date = now;
2084 commit->object.type = OBJ_COMMIT;
2086 origin = make_origin(commit, path);
2088 strbuf_init(&buf, 0);
2089 if (!contents_from || strcmp("-", contents_from)) {
2090 struct stat st;
2091 const char *read_from;
2092 unsigned long fin_size;
2094 if (contents_from) {
2095 if (stat(contents_from, &st) < 0)
2096 die("Cannot stat %s", contents_from);
2097 read_from = contents_from;
2099 else {
2100 if (lstat(path, &st) < 0)
2101 die("Cannot lstat %s", path);
2102 read_from = path;
2104 fin_size = xsize_t(st.st_size);
2105 mode = canon_mode(st.st_mode);
2106 switch (st.st_mode & S_IFMT) {
2107 case S_IFREG:
2108 if (strbuf_read_file(&buf, read_from, st.st_size) != st.st_size)
2109 die("cannot open or read %s", read_from);
2110 break;
2111 case S_IFLNK:
2112 if (readlink(read_from, buf.buf, buf.alloc) != fin_size)
2113 die("cannot readlink %s", read_from);
2114 buf.len = fin_size;
2115 break;
2116 default:
2117 die("unsupported file type %s", read_from);
2120 else {
2121 /* Reading from stdin */
2122 contents_from = "standard input";
2123 mode = 0;
2124 if (strbuf_read(&buf, 0, 0) < 0)
2125 die("read error %s from stdin", strerror(errno));
2127 convert_to_git(path, buf.buf, buf.len, &buf, 0);
2128 origin->file.ptr = buf.buf;
2129 origin->file.size = buf.len;
2130 pretend_sha1_file(buf.buf, buf.len, OBJ_BLOB, origin->blob_sha1);
2131 commit->util = origin;
2134 * Read the current index, replace the path entry with
2135 * origin->blob_sha1 without mucking with its mode or type
2136 * bits; we are not going to write this index out -- we just
2137 * want to run "diff-index --cached".
2139 discard_cache();
2140 read_cache();
2142 len = strlen(path);
2143 if (!mode) {
2144 int pos = cache_name_pos(path, len);
2145 if (0 <= pos)
2146 mode = active_cache[pos]->ce_mode;
2147 else
2148 /* Let's not bother reading from HEAD tree */
2149 mode = S_IFREG | 0644;
2151 size = cache_entry_size(len);
2152 ce = xcalloc(1, size);
2153 hashcpy(ce->sha1, origin->blob_sha1);
2154 memcpy(ce->name, path, len);
2155 ce->ce_flags = create_ce_flags(len, 0);
2156 ce->ce_mode = create_ce_mode(mode);
2157 add_cache_entry(ce, ADD_CACHE_OK_TO_ADD|ADD_CACHE_OK_TO_REPLACE);
2160 * We are not going to write this out, so this does not matter
2161 * right now, but someday we might optimize diff-index --cached
2162 * with cache-tree information.
2164 cache_tree_invalidate_path(active_cache_tree, path);
2166 commit->buffer = xmalloc(400);
2167 ident = fmt_ident("Not Committed Yet", "not.committed.yet", NULL, 0);
2168 snprintf(commit->buffer, 400,
2169 "tree 0000000000000000000000000000000000000000\n"
2170 "parent %s\n"
2171 "author %s\n"
2172 "committer %s\n\n"
2173 "Version of %s from %s\n",
2174 sha1_to_hex(head_sha1),
2175 ident, ident, path, contents_from ? contents_from : path);
2176 return commit;
2179 static const char *prepare_final(struct scoreboard *sb)
2181 int i;
2182 const char *final_commit_name = NULL;
2183 struct rev_info *revs = sb->revs;
2186 * There must be one and only one positive commit in the
2187 * revs->pending array.
2189 for (i = 0; i < revs->pending.nr; i++) {
2190 struct object *obj = revs->pending.objects[i].item;
2191 if (obj->flags & UNINTERESTING)
2192 continue;
2193 while (obj->type == OBJ_TAG)
2194 obj = deref_tag(obj, NULL, 0);
2195 if (obj->type != OBJ_COMMIT)
2196 die("Non commit %s?", revs->pending.objects[i].name);
2197 if (sb->final)
2198 die("More than one commit to dig from %s and %s?",
2199 revs->pending.objects[i].name,
2200 final_commit_name);
2201 sb->final = (struct commit *) obj;
2202 final_commit_name = revs->pending.objects[i].name;
2204 return final_commit_name;
2207 static const char *prepare_initial(struct scoreboard *sb)
2209 int i;
2210 const char *final_commit_name = NULL;
2211 struct rev_info *revs = sb->revs;
2214 * There must be one and only one negative commit, and it must be
2215 * the boundary.
2217 for (i = 0; i < revs->pending.nr; i++) {
2218 struct object *obj = revs->pending.objects[i].item;
2219 if (!(obj->flags & UNINTERESTING))
2220 continue;
2221 while (obj->type == OBJ_TAG)
2222 obj = deref_tag(obj, NULL, 0);
2223 if (obj->type != OBJ_COMMIT)
2224 die("Non commit %s?", revs->pending.objects[i].name);
2225 if (sb->final)
2226 die("More than one commit to dig down to %s and %s?",
2227 revs->pending.objects[i].name,
2228 final_commit_name);
2229 sb->final = (struct commit *) obj;
2230 final_commit_name = revs->pending.objects[i].name;
2232 if (!final_commit_name)
2233 die("No commit to dig down to?");
2234 return final_commit_name;
2237 static int blame_copy_callback(const struct option *option, const char *arg, int unset)
2239 int *opt = option->value;
2242 * -C enables copy from removed files;
2243 * -C -C enables copy from existing files, but only
2244 * when blaming a new file;
2245 * -C -C -C enables copy from existing files for
2246 * everybody
2248 if (*opt & PICKAXE_BLAME_COPY_HARDER)
2249 *opt |= PICKAXE_BLAME_COPY_HARDEST;
2250 if (*opt & PICKAXE_BLAME_COPY)
2251 *opt |= PICKAXE_BLAME_COPY_HARDER;
2252 *opt |= PICKAXE_BLAME_COPY | PICKAXE_BLAME_MOVE;
2254 if (arg)
2255 blame_copy_score = parse_score(arg);
2256 return 0;
2259 static int blame_move_callback(const struct option *option, const char *arg, int unset)
2261 int *opt = option->value;
2263 *opt |= PICKAXE_BLAME_MOVE;
2265 if (arg)
2266 blame_move_score = parse_score(arg);
2267 return 0;
2270 static int blame_bottomtop_callback(const struct option *option, const char *arg, int unset)
2272 const char **bottomtop = option->value;
2273 if (!arg)
2274 return -1;
2275 if (*bottomtop)
2276 die("More than one '-L n,m' option given");
2277 *bottomtop = arg;
2278 return 0;
2281 int cmd_blame(int argc, const char **argv, const char *prefix)
2283 struct rev_info revs;
2284 const char *path;
2285 struct scoreboard sb;
2286 struct origin *o;
2287 struct blame_entry *ent;
2288 long dashdash_pos, bottom, top, lno;
2289 const char *final_commit_name = NULL;
2290 enum object_type type;
2292 static const char *bottomtop = NULL;
2293 static int output_option = 0, opt = 0;
2294 static int show_stats = 0;
2295 static const char *revs_file = NULL;
2296 static const char *contents_from = NULL;
2297 static const struct option options[] = {
2298 OPT_BOOLEAN(0, "incremental", &incremental, "Show blame entries as we find them, incrementally"),
2299 OPT_BOOLEAN('b', NULL, &blank_boundary, "Show blank SHA-1 for boundary commits (Default: off)"),
2300 OPT_BOOLEAN(0, "root", &show_root, "Do not treat root commits as boundaries (Default: off)"),
2301 OPT_BOOLEAN(0, "show-stats", &show_stats, "Show work cost statistics"),
2302 OPT_BIT(0, "score-debug", &output_option, "Show output score for blame entries", OUTPUT_SHOW_SCORE),
2303 OPT_BIT('f', "show-name", &output_option, "Show original filename (Default: auto)", OUTPUT_SHOW_NAME),
2304 OPT_BIT('n', "show-number", &output_option, "Show original linenumber (Default: off)", OUTPUT_SHOW_NUMBER),
2305 OPT_BIT('p', "porcelain", &output_option, "Show in a format designed for machine consumption", OUTPUT_PORCELAIN),
2306 OPT_BIT('c', NULL, &output_option, "Use the same output mode as git-annotate (Default: off)", OUTPUT_ANNOTATE_COMPAT),
2307 OPT_BIT('t', NULL, &output_option, "Show raw timestamp (Default: off)", OUTPUT_RAW_TIMESTAMP),
2308 OPT_BIT('l', NULL, &output_option, "Show long commit SHA1 (Default: off)", OUTPUT_LONG_OBJECT_NAME),
2309 OPT_BIT('s', NULL, &output_option, "Suppress author name and timestamp (Default: off)", OUTPUT_NO_AUTHOR),
2310 OPT_BIT('w', NULL, &xdl_opts, "Ignore whitespace differences", XDF_IGNORE_WHITESPACE),
2311 OPT_STRING('S', NULL, &revs_file, "file", "Use revisions from <file> instead of calling git-rev-list"),
2312 OPT_STRING(0, "contents", &contents_from, "file", "Use <file>'s contents as the final image"),
2313 { OPTION_CALLBACK, 'C', NULL, &opt, "score", "Find line copies within and across files", PARSE_OPT_OPTARG, blame_copy_callback },
2314 { OPTION_CALLBACK, 'M', NULL, &opt, "score", "Find line movements within and across files", PARSE_OPT_OPTARG, blame_move_callback },
2315 OPT_CALLBACK('L', NULL, &bottomtop, "n,m", "Process only line range n,m, counting from 1", blame_bottomtop_callback),
2316 OPT_END()
2319 struct parse_opt_ctx_t ctx;
2321 cmd_is_annotate = !strcmp(argv[0], "annotate");
2323 git_config(git_blame_config, NULL);
2324 init_revisions(&revs, NULL);
2325 save_commit_buffer = 0;
2326 dashdash_pos = 0;
2328 parse_options_start(&ctx, argc, argv, PARSE_OPT_KEEP_DASHDASH |
2329 PARSE_OPT_KEEP_ARGV0);
2330 for (;;) {
2331 switch (parse_options_step(&ctx, options, blame_opt_usage)) {
2332 case PARSE_OPT_HELP:
2333 exit(129);
2334 case PARSE_OPT_DONE:
2335 if (ctx.argv[0])
2336 dashdash_pos = ctx.cpidx;
2337 goto parse_done;
2340 if (!strcmp(ctx.argv[0], "--reverse")) {
2341 ctx.argv[0] = "--children";
2342 reverse = 1;
2344 parse_revision_opt(&revs, &ctx, options, blame_opt_usage);
2346 parse_done:
2347 argc = parse_options_end(&ctx);
2349 if (DIFF_OPT_TST(&revs.diffopt, FIND_COPIES_HARDER))
2350 opt |= (PICKAXE_BLAME_COPY | PICKAXE_BLAME_MOVE |
2351 PICKAXE_BLAME_COPY_HARDER);
2353 if (!blame_move_score)
2354 blame_move_score = BLAME_DEFAULT_MOVE_SCORE;
2355 if (!blame_copy_score)
2356 blame_copy_score = BLAME_DEFAULT_COPY_SCORE;
2359 * We have collected options unknown to us in argv[1..unk]
2360 * which are to be passed to revision machinery if we are
2361 * going to do the "bottom" processing.
2363 * The remaining are:
2365 * (1) if dashdash_pos != 0, its either
2366 * "blame [revisions] -- <path>" or
2367 * "blame -- <path> <rev>"
2369 * (2) otherwise, its one of the two:
2370 * "blame [revisions] <path>"
2371 * "blame <path> <rev>"
2373 * Note that we must strip out <path> from the arguments: we do not
2374 * want the path pruning but we may want "bottom" processing.
2376 if (dashdash_pos) {
2377 switch (argc - dashdash_pos - 1) {
2378 case 2: /* (1b) */
2379 if (argc != 4)
2380 usage_with_options(blame_opt_usage, options);
2381 /* reorder for the new way: <rev> -- <path> */
2382 argv[1] = argv[3];
2383 argv[3] = argv[2];
2384 argv[2] = "--";
2385 /* FALLTHROUGH */
2386 case 1: /* (1a) */
2387 path = add_prefix(prefix, argv[--argc]);
2388 argv[argc] = NULL;
2389 break;
2390 default:
2391 usage_with_options(blame_opt_usage, options);
2393 } else {
2394 if (argc < 2)
2395 usage_with_options(blame_opt_usage, options);
2396 path = add_prefix(prefix, argv[argc - 1]);
2397 if (argc == 3 && !has_string_in_work_tree(path)) { /* (2b) */
2398 path = add_prefix(prefix, argv[1]);
2399 argv[1] = argv[2];
2401 argv[argc - 1] = "--";
2403 setup_work_tree();
2404 if (!has_string_in_work_tree(path))
2405 die("cannot stat path %s: %s", path, strerror(errno));
2408 setup_revisions(argc, argv, &revs, NULL);
2409 memset(&sb, 0, sizeof(sb));
2411 sb.revs = &revs;
2412 if (!reverse)
2413 final_commit_name = prepare_final(&sb);
2414 else if (contents_from)
2415 die("--contents and --children do not blend well.");
2416 else
2417 final_commit_name = prepare_initial(&sb);
2419 if (!sb.final) {
2421 * "--not A B -- path" without anything positive;
2422 * do not default to HEAD, but use the working tree
2423 * or "--contents".
2425 setup_work_tree();
2426 sb.final = fake_working_tree_commit(path, contents_from);
2427 add_pending_object(&revs, &(sb.final->object), ":");
2429 else if (contents_from)
2430 die("Cannot use --contents with final commit object name");
2433 * If we have bottom, this will mark the ancestors of the
2434 * bottom commits we would reach while traversing as
2435 * uninteresting.
2437 if (prepare_revision_walk(&revs))
2438 die("revision walk setup failed");
2440 if (is_null_sha1(sb.final->object.sha1)) {
2441 char *buf;
2442 o = sb.final->util;
2443 buf = xmalloc(o->file.size + 1);
2444 memcpy(buf, o->file.ptr, o->file.size + 1);
2445 sb.final_buf = buf;
2446 sb.final_buf_size = o->file.size;
2448 else {
2449 o = get_origin(&sb, sb.final, path);
2450 if (fill_blob_sha1(o))
2451 die("no such path %s in %s", path, final_commit_name);
2453 sb.final_buf = read_sha1_file(o->blob_sha1, &type,
2454 &sb.final_buf_size);
2455 if (!sb.final_buf)
2456 die("Cannot read blob %s for path %s",
2457 sha1_to_hex(o->blob_sha1),
2458 path);
2460 num_read_blob++;
2461 lno = prepare_lines(&sb);
2463 bottom = top = 0;
2464 if (bottomtop)
2465 prepare_blame_range(&sb, bottomtop, lno, &bottom, &top);
2466 if (bottom && top && top < bottom) {
2467 long tmp;
2468 tmp = top; top = bottom; bottom = tmp;
2470 if (bottom < 1)
2471 bottom = 1;
2472 if (top < 1)
2473 top = lno;
2474 bottom--;
2475 if (lno < top)
2476 die("file %s has only %lu lines", path, lno);
2478 ent = xcalloc(1, sizeof(*ent));
2479 ent->lno = bottom;
2480 ent->num_lines = top - bottom;
2481 ent->suspect = o;
2482 ent->s_lno = bottom;
2484 sb.ent = ent;
2485 sb.path = path;
2487 if (revs_file && read_ancestry(revs_file))
2488 die("reading graft file %s failed: %s",
2489 revs_file, strerror(errno));
2491 read_mailmap(&mailmap, ".mailmap", NULL);
2493 if (!incremental)
2494 setup_pager();
2496 assign_blame(&sb, opt);
2498 if (incremental)
2499 return 0;
2501 coalesce(&sb);
2503 if (!(output_option & OUTPUT_PORCELAIN))
2504 find_alignment(&sb, &output_option);
2506 output(&sb, output_option);
2507 free((void *)sb.final_buf);
2508 for (ent = sb.ent; ent; ) {
2509 struct blame_entry *e = ent->next;
2510 free(ent);
2511 ent = e;
2514 if (show_stats) {
2515 printf("num read blob: %d\n", num_read_blob);
2516 printf("num get patch: %d\n", num_get_patch);
2517 printf("num commits: %d\n", num_commits);
2519 return 0;